<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/db.php';

if (
    !isset($_SESSION['role']) ||
    !in_array(
        $_SESSION['role'],
        ['admin', 'zonal_director'],
        true
    )
) {
    http_response_code(403);
    exit('Access denied.');
}

$role = (string)$_SESSION['role'];
$sessionZone = trim(
    (string)($_SESSION['zone_name'] ?? '')
);

/*
|--------------------------------------------------------------------------
| Load district, zone and division hierarchy
|--------------------------------------------------------------------------
*/

$locationSql = '
    SELECT DISTINCT
        district,
        zone_name,
        division_name
    FROM schools
    WHERE district IS NOT NULL
      AND district <> \'\'
      AND zone_name IS NOT NULL
      AND zone_name <> \'\'
      AND division_name IS NOT NULL
      AND division_name <> \'\'
';

$locationTypes = '';
$locationParameters = [];

if ($role === 'zonal_director') {
    if ($sessionZone === '') {
        http_response_code(403);
        exit('Your account does not have a valid zone.');
    }

    $locationSql .= ' AND zone_name = ? ';
    $locationTypes = 's';
    $locationParameters[] = $sessionZone;
}

$locationSql .= '
    ORDER BY
        district ASC,
        zone_name ASC,
        division_name ASC
';

$locationStatement = mysqli_prepare(
    $conn,
    $locationSql
);

if (!$locationStatement) {
    exit('Unable to load report locations.');
}

if ($locationTypes !== '') {
    mysqli_stmt_bind_param(
        $locationStatement,
        $locationTypes,
        ...$locationParameters
    );
}

mysqli_stmt_execute($locationStatement);

$locationResult = mysqli_stmt_get_result(
    $locationStatement
);

$locationHierarchy = [];
$districts = [];

while ($row = mysqli_fetch_assoc($locationResult)) {
    $districtName = trim(
        (string)$row['district']
    );

    $zoneName = trim(
        (string)$row['zone_name']
    );

    $divisionName = trim(
        (string)$row['division_name']
    );

    if (
        $districtName === '' ||
        $zoneName === '' ||
        $divisionName === ''
    ) {
        continue;
    }

    $districts[$districtName] = $districtName;

    if (
        !isset(
            $locationHierarchy[
                $districtName
            ][$zoneName]
        )
    ) {
        $locationHierarchy[
            $districtName
        ][$zoneName] = [];
    }

    $locationHierarchy[
        $districtName
    ][$zoneName][$divisionName] =
        $divisionName;
}

mysqli_stmt_close($locationStatement);

ksort($districts);

foreach ($locationHierarchy as &$zones) {
    ksort($zones);

    foreach ($zones as &$divisions) {
        ksort($divisions);
    }

    unset($divisions);
}

unset($zones);

/*
|--------------------------------------------------------------------------
| Load active equipment
|--------------------------------------------------------------------------
*/

$equipmentStatement = mysqli_prepare(
    $conn,
    "SELECT
        id,
        equipment_name
     FROM equipment_master
     WHERE status = 'Active'
     ORDER BY
        display_order ASC,
        equipment_name ASC"
);

if (!$equipmentStatement) {
    exit('Unable to load equipment.');
}

mysqli_stmt_execute($equipmentStatement);

$equipmentResult = mysqli_stmt_get_result(
    $equipmentStatement
);

$equipment = [];

while ($row = mysqli_fetch_assoc($equipmentResult)) {
    $equipment[] = [
        'id' => (int)$row['id'],
        'equipment_name' =>
            (string)$row['equipment_name']
    ];
}

mysqli_stmt_close($equipmentStatement);

$extraFields = [
    'survey_date',
    'entered_by',
    'census_no',
    'school_name',
    'school_category',
    'school_type',
    'principal_name',
    'principal_phone',
    'school_phone',
    'it_teacher_name',
    'it_teacher_phone'
];

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/navbar.php';
?>

<main class="container mt-4 mb-5">

    <div class="card shadow">

        <div class="card-header bg-success text-white">

            <strong>
                <i class="fa-solid fa-file-export me-1"></i>
                Advanced Export Options
            </strong>

        </div>

        <div class="card-body">

            <form method="get" id="exportForm">

                <div class="row g-4">

                    <!-- Filters -->
                    <div class="col-md-4">

                        <h5 class="mb-3">
                            Filter Data
                        </h5>

                        <div class="mb-3">

                            <label
                                for="reportDistrict"
                                class="form-label"
                            >
                                District
                            </label>

                            <select
                                name="district"
                                id="reportDistrict"
                                class="form-select"
                            >

                                <option value="ALL">
                                    All Districts
                                </option>

                                <?php foreach ($districts as $district): ?>

                                    <option
                                        value="<?= htmlspecialchars(
                                            $district,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>"
                                    >
                                        <?= htmlspecialchars(
                                            $district,
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ) ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                        <div class="mb-3">

                            <label
                                for="reportZone"
                                class="form-label"
                            >
                                Zone
                            </label>

                            <select
                                name="zone"
                                id="reportZone"
                                class="form-select"
                                <?= $role === 'zonal_director'
                                    ? 'disabled'
                                    : '' ?>
                            >

                                <option value="">
                                    All Zones
                                </option>

                            </select>

                            <?php if ($role === 'zonal_director'): ?>

                                <input
                                    type="hidden"
                                    name="zone"
                                    value="<?= htmlspecialchars(
                                        $sessionZone,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                >

                            <?php endif; ?>

                        </div>

                        <div class="mb-3">

                            <label
                                for="reportDivision"
                                class="form-label"
                            >
                                Division
                            </label>

                            <select
                                name="division"
                                id="reportDivision"
                                class="form-select"
                            >

                                <option value="">
                                    All Divisions
                                </option>

                            </select>

                        </div>

                        <div class="alert alert-info small mb-0">

                            Zone and Division are optional.

                            Selecting only a District exports all
                            matching surveys in that District.

                        </div>

                    </div>

                    <!-- Additional fields -->
                    <div class="col-md-4">

                        <div
                            class="d-flex justify-content-between
                                   align-items-center mb-2"
                        >

                            <h5 class="mb-0">
                                Additional Details
                            </h5>

                            <div class="btn-group btn-group-sm">

                                <button
                                    type="button"
                                    class="btn btn-secondary"
                                    data-check-group="details-check"
                                    data-check-action="all"
                                >
                                    All
                                </button>

                                <button
                                    type="button"
                                    class="btn btn-warning"
                                    data-check-group="details-check"
                                    data-check-action="none"
                                >
                                    None
                                </button>

                            </div>

                        </div>

                        <?php foreach ($extraFields as $field): ?>

                            <div class="form-check">

                                <input
                                    class="form-check-input details-check"
                                    type="checkbox"
                                    name="fields[]"
                                    id="field_<?= htmlspecialchars(
                                        $field,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                    value="<?= htmlspecialchars(
                                        $field,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                >

                                <label
                                    class="form-check-label"
                                    for="field_<?= htmlspecialchars(
                                        $field,
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>"
                                >
                                    <?= htmlspecialchars(
                                        ucwords(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $field
                                            )
                                        ),
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </label>

                            </div>

                        <?php endforeach; ?>

                    </div>

                    <!-- Equipment -->
                    <div class="col-md-4">

                        <div
                            class="d-flex justify-content-between
                                   align-items-center mb-2"
                        >

                            <h5 class="mb-0">
                                Equipment
                            </h5>

                            <div class="btn-group btn-group-sm">

                                <button
                                    type="button"
                                    class="btn btn-secondary"
                                    data-check-group="equipment-check"
                                    data-check-action="all"
                                >
                                    All
                                </button>

                                <button
                                    type="button"
                                    class="btn btn-warning"
                                    data-check-group="equipment-check"
                                    data-check-action="none"
                                >
                                    None
                                </button>

                            </div>

                        </div>

                        <?php foreach ($equipment as $item): ?>

                            <div class="form-check">

                                <input
                                    class="form-check-input equipment-check"
                                    type="checkbox"
                                    name="equipment[]"
                                    id="equipment_<?= (int)$item['id'] ?>"
                                    value="<?= (int)$item['id'] ?>"
                                >

                                <label
                                    class="form-check-label"
                                    for="equipment_<?= (int)$item['id'] ?>"
                                >
                                    <?= htmlspecialchars(
                                        $item['equipment_name'],
                                        ENT_QUOTES,
                                        'UTF-8'
                                    ) ?>
                                </label>

                            </div>

                        <?php endforeach; ?>

                        <hr>

                        <div class="d-grid gap-2">

                            <button
                                type="submit"
                                formaction="export_excel.php"
                                formmethod="get"
                                class="btn btn-success"
                            >
                                <i class="fa-solid fa-file-excel me-1"></i>
                                Export Excel
                            </button>

                            <button
                                type="submit"
                                formaction="export_pdf.php"
                                formmethod="get"
                                class="btn btn-danger"
                            >
                                <i class="fa-solid fa-file-pdf me-1"></i>
                                Export PDF
                            </button>

                            <button
                                type="submit"
                                formaction="print_report.php"
                                formmethod="get"
                                formtarget="_blank"
                                class="btn btn-primary"
                            >
                                <i class="fa-solid fa-print me-1"></i>
                                Print Full Report
                            </button>

                        </div>

                    </div>

                </div>

            </form>

        </div>

    </div>

</main>

<script>
window.REPORT_LOCATION_HIERARCHY = <?= json_encode(
    $locationHierarchy,
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_AMP |
    JSON_HEX_QUOT
) ?>;

window.REPORT_USER_ROLE = <?= json_encode(
    $role,
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_AMP |
    JSON_HEX_QUOT
) ?>;

window.REPORT_USER_ZONE = <?= json_encode(
    $sessionZone,
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_AMP |
    JSON_HEX_QUOT
) ?>;
</script>

<script
    src="<?= htmlspecialchars(
        BASE_URL .
        'assets/js/survey_wizard.js?v=' .
        urlencode(SYSTEM_VERSION),
        ENT_QUOTES,
        'UTF-8'
    ) ?>"
></script>

<?php include __DIR__ . '/../includes/footer.php'; ?>