<?php

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/role_filter.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT,
    ['options' => ['min_range' => 1]]
);

if (!$id) {
    http_response_code(400);
    exit('Invalid survey ID.');
}

$roleFilter = getSurveyRoleFilter('s');

$surveySql = '
    SELECT
        s.id,
        s.survey_date,
        s.entered_by,
        s.census_no,
        s.district,
        s.zone_name,
        s.division_name,
        s.school_name,
        s.school_category,
        s.school_type,
        s.principal_name,
        s.principal_phone,
        s.school_phone,
        s.it_teacher_name,
        s.it_teacher_phone
    FROM surveys s
    WHERE s.id = ?
    ' . $roleFilter['sql'] . '
    LIMIT 1
';

$surveyStatement = mysqli_prepare($conn, $surveySql);

$surveyTypes = 'i' . $roleFilter['types'];
$surveyParams = array_merge([$id], $roleFilter['params']);

mysqli_stmt_bind_param(
    $surveyStatement,
    $surveyTypes,
    ...$surveyParams
);

mysqli_stmt_execute($surveyStatement);

$surveyResult = mysqli_stmt_get_result($surveyStatement);
$survey = mysqli_fetch_assoc($surveyResult);

mysqli_stmt_close($surveyStatement);

if (!$survey) {
    http_response_code(404);
    exit('Survey not found or access denied.');
}

/*
|--------------------------------------------------------------------------
| Load required units and catalogue
|--------------------------------------------------------------------------
*/

$unitSql = "
    SELECT
        um.id AS unit_id,
        um.unit_name,
        um.display_order AS unit_order,
        em.id AS equipment_id,
        em.equipment_name,
        ue.display_order AS equipment_order
    FROM unit_master um
    LEFT JOIN unit_equipment ue
        ON ue.unit_id = um.id
       AND ue.status = 'Active'
    LEFT JOIN equipment_master em
        ON em.id = ue.equipment_id
       AND em.status = 'Active'
    WHERE um.status = 'Active'
      AND um.is_required = 'Yes'
    ORDER BY
        um.display_order ASC,
        ue.display_order ASC,
        em.display_order ASC,
        em.equipment_name ASC
";

$unitStatement = mysqli_prepare($conn, $unitSql);
mysqli_stmt_execute($unitStatement);
$unitResult = mysqli_stmt_get_result($unitStatement);

$units = [];

while ($row = mysqli_fetch_assoc($unitResult)) {
    $unitId = (int)$row['unit_id'];

    if (!isset($units[$unitId])) {
        $units[$unitId] = [
            'id' => $unitId,
            'name' => $row['unit_name'],
            'equipment' => []
        ];
    }

    if (!empty($row['equipment_id'])) {
        $units[$unitId]['equipment'][] = [
            'id' => (int)$row['equipment_id'],
            'name' => $row['equipment_name']
        ];
    }
}

mysqli_stmt_close($unitStatement);

$units = array_values($units);

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

mysqli_stmt_execute($catalogStatement);
$catalogResult = mysqli_stmt_get_result($catalogStatement);

$catalog = [];

while ($row = mysqli_fetch_assoc($catalogResult)) {
    $catalog[] = [
        'id' => (int)$row['id'],
        'name' => $row['equipment_name']
    ];
}

mysqli_stmt_close($catalogStatement);

/*
|--------------------------------------------------------------------------
| Load saved fixed equipment
|--------------------------------------------------------------------------
*/

$savedStandard = [];

$fixedStatement = mysqli_prepare(
    $conn,
    'SELECT
        section,
        equipment_id,
        working,
        not_working,
        repair
     FROM survey_equipment_details
     WHERE survey_id = ?'
);

mysqli_stmt_bind_param($fixedStatement, 'i', $id);
mysqli_stmt_execute($fixedStatement);
$fixedResult = mysqli_stmt_get_result($fixedStatement);

while ($row = mysqli_fetch_assoc($fixedResult)) {
    $section = (string)$row['section'];
    $equipmentId = (int)$row['equipment_id'];

    if (!isset($savedStandard[$section])) {
        $savedStandard[$section] = [];
    }

    $savedStandard[$section][$equipmentId] = [
        'working' => (int)$row['working'],
        'not_working' => (int)$row['not_working'],
        'repair' => (int)$row['repair']
    ];
}

mysqli_stmt_close($fixedStatement);

/*
|--------------------------------------------------------------------------
| Load saved other units
|--------------------------------------------------------------------------
*/

$savedOtherUnits = [];

$otherStatement = mysqli_prepare(
    $conn,
    'SELECT
        sou.id AS unit_id,
        sou.unit_name,
        sou.details,
        sou.display_order AS unit_order,
        soe.equipment_name,
        soe.working,
        soe.not_working,
        soe.repair,
        soe.display_order AS equipment_order
     FROM survey_other_units sou
     LEFT JOIN survey_other_equipment soe
        ON soe.other_unit_id = sou.id
     WHERE sou.survey_id = ?
     ORDER BY
        sou.display_order ASC,
        sou.id ASC,
        soe.display_order ASC,
        soe.id ASC'
);

mysqli_stmt_bind_param($otherStatement, 'i', $id);
mysqli_stmt_execute($otherStatement);
$otherResult = mysqli_stmt_get_result($otherStatement);

while ($row = mysqli_fetch_assoc($otherResult)) {
    $unitId = (int)$row['unit_id'];

    if (!isset($savedOtherUnits[$unitId])) {
        $savedOtherUnits[$unitId] = [
            'unit_name' => $row['unit_name'],
            'details' => $row['details'] ?? '',
            'equipment' => []
        ];
    }

    if ($row['equipment_name'] !== null) {
        $savedOtherUnits[$unitId]['equipment'][] = [
            'equipment_name' => $row['equipment_name'],
            'working' => (int)$row['working'],
            'not_working' => (int)$row['not_working'],
            'repair' => (int)$row['repair']
        ];
    }
}

mysqli_stmt_close($otherStatement);

$savedOtherUnits = array_values($savedOtherUnits);

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

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

    <form method="post" action="update_survey.php" id="surveyForm">

        <input type="hidden" name="csrf_token"
               value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">

        <input type="hidden" name="id" value="<?= (int)$survey['id'] ?>">
        <input type="hidden" name="survey_details" id="survey_details">

        <div class="card shadow">

            <div class="card-header bg-warning d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fa-solid fa-pen-to-square me-1"></i>
                    Edit Hardware Survey
                </h5>

                <span class="badge bg-dark" id="stepCounter"></span>
            </div>

            <div class="card-body">

                <div class="wizard-step active" data-title="School Details">

                    <h5 class="mb-3">
                        <i class="fa-solid fa-school me-1"></i>
                        School Details
                    </h5>

                    <div class="row">

                        <div class="col-md-3 mb-3">
                            <label class="form-label">Census No</label>
                            <input type="text"
                                   id="census_no"
                                   name="census_no"
                                   class="form-control"
                                   value="<?= htmlspecialchars($survey['census_no'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">District</label>
                            <input type="text" id="district" class="form-control"
                                   value="<?= htmlspecialchars($survey['district'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">Zone</label>
                            <input type="text" id="zone" class="form-control"
                                   value="<?= htmlspecialchars($survey['zone_name'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">Division</label>
                            <input type="text" id="division" class="form-control"
                                   value="<?= htmlspecialchars($survey['division_name'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                    </div>

                    <div class="row">

                        <div class="col-md-6 mb-3">
                            <label class="form-label">School</label>
                            <input type="text" id="school_name" class="form-control"
                                   value="<?= htmlspecialchars($survey['school_name'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">National / Provincial</label>
                            <input type="text" id="school_category" class="form-control"
                                   value="<?= htmlspecialchars($survey['school_category'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">School Type</label>
                            <input type="text" id="school_type" class="form-control"
                                   value="<?= htmlspecialchars($survey['school_type'], ENT_QUOTES, 'UTF-8') ?>"
                                   readonly>
                        </div>

                    </div>

                    <hr>

                    <h6 class="mb-3">Contact Details</h6>

                    <div class="row">

                        <div class="col-md-4 mb-3">
                            <label class="form-label">Principal Name</label>
                            <input type="text"
                                   name="principal_name"
                                   class="form-control"
                                   maxlength="255"
                                   value="<?= htmlspecialchars($survey['principal_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                        </div>

                        <div class="col-md-4 mb-3">
                            <label class="form-label">Principal Phone</label>
                            <input type="tel"
                                   name="principal_phone"
                                   class="form-control"
                                   maxlength="20"
                                   value="<?= htmlspecialchars($survey['principal_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                        </div>

                        <div class="col-md-4 mb-3">
                            <label class="form-label">School Phone</label>
                            <input type="tel"
                                   name="school_phone"
                                   class="form-control"
                                   maxlength="20"
                                   value="<?= htmlspecialchars($survey['school_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                        </div>

                    </div>

                    <div class="row">

                        <div class="col-md-6 mb-3">
                            <label class="form-label">IT Teacher Name</label>
                            <input type="text"
                                   name="it_teacher_name"
                                   class="form-control"
                                   maxlength="255"
                                   value="<?= htmlspecialchars($survey['it_teacher_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">IT Teacher Phone</label>
                            <input type="tel"
                                   name="it_teacher_phone"
                                   class="form-control"
                                   maxlength="20"
                                   value="<?= htmlspecialchars($survey['it_teacher_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                        </div>

                    </div>

                </div>

                <?php foreach ($units as $unit): ?>
                    <div class="wizard-step standard-unit-step"
                         data-title="<?= htmlspecialchars($unit['name'], ENT_QUOTES, 'UTF-8') ?>"
                         data-unit-id="<?= (int)$unit['id'] ?>">
                    </div>
                <?php endforeach; ?>

                <div class="wizard-step" data-title="Other Units">

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="fa-solid fa-layer-group me-1"></i>
                            Other Units
                        </h5>

                        <button type="button"
                                class="btn btn-primary btn-sm"
                                id="addOtherUnit">
                            <i class="fa-solid fa-plus"></i>
                            Add Unit
                        </button>
                    </div>

                    <p class="text-muted" id="otherUnitHelp">
                        Add another unit when applicable.
                    </p>

                    <div id="otherUnits"></div>

                </div>

                <div class="wizard-step" data-title="Summary">
                    <h5>
                        <i class="fa-solid fa-clipboard-check me-1"></i>
                        Survey Summary
                    </h5>

                    <p class="text-muted">
                        Totals are calculated for display only.
                    </p>

                    <div id="summary"></div>
                </div>

            </div>

            <div class="card-footer bg-white d-flex justify-content-between">

                <button type="button"
                        class="btn btn-secondary"
                        id="previousButton"
                        disabled>
                    <i class="fa-solid fa-arrow-left"></i>
                    Previous
                </button>

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

                    <a href="view_surveys.php" class="btn btn-outline-secondary">
                        Cancel
                    </a>

                    <button type="button"
                            class="btn btn-primary"
                            id="nextButton">
                        Next
                        <i class="fa-solid fa-arrow-right"></i>
                    </button>

                    <button type="submit"
                            class="btn btn-success d-none"
                            id="submitButton">
                        <i class="fa-solid fa-floppy-disk"></i>
                        Update Survey
                    </button>

                </div>

            </div>

        </div>

    </form>

</main>

<div class="modal fade" id="otherUnitModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" id="otherUnitForm">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Add Other Unit</h5>
                <button type="button"
                        class="btn-close btn-close-white"
                        data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <label class="form-label">Unit Name</label>
                <input class="form-control"
                       id="other_unit_name"
                       maxlength="150"
                       required>
            </div>

            <div class="modal-footer">
                <button type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal">
                    Cancel
                </button>

                <button class="btn btn-success">
                    Add Unit
                </button>
            </div>
        </form>
    </div>
</div>

<script>
const BASE_URL = <?= json_encode(
    BASE_URL,
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_AMP |
    JSON_HEX_QUOT
) ?>;

window.BASE_URL = BASE_URL;
window.SURVEY_MODE = 'edit';

window.SURVEY_UNITS = <?= json_encode(
    array_values($units),
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_AMP |
    JSON_HEX_QUOT
) ?>;

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

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

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

<script src="<?= BASE_URL ?>assets/js/survey_wizard.js?v=<?= urlencode(SYSTEM_VERSION) ?>"></script>

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