<?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';

$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);

if (!$unitStatement) {
    die('Unable to load survey units: ' . mysqli_error($conn));
}

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);

$catalogSql = "
    SELECT id, equipment_name
    FROM equipment_master
    WHERE status = 'Active'
    ORDER BY display_order ASC, equipment_name ASC
";

$catalogStatement = mysqli_prepare($conn, $catalogSql);

if (!$catalogStatement) {
    die('Unable to load equipment catalogue: ' . mysqli_error($conn));
}

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);

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

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

    <form method="POST" action="save_survey.php" id="surveyForm">

        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        <input type="hidden" name="survey_details" id="survey_details">

        <div class="card shadow">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Sabaragamuwa Province School Computer Hardware Survey</h5>
                <span class="badge bg-light text-primary" id="stepCounter">Step 1 of 7</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"
                            required>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">District</label>

                            <input
                            type="text"
                            id="district"
                            name="district"
                            class="form-control"
                            readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">Zone</label>

                            <input
                            type="text"
                            id="zone"
                            name="zone_name"
                            class="form-control"
                            readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">Division</label>

                            <input
                            type="text"
                            id="division"
                            name="division_name"
                            class="form-control"
                            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"
                            name="school_name"
                            class="form-control"
                            readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">National / Provincial</label>

                            <input
                            type="text"
                            id="school_category"
                            name="school_category"
                            class="form-control"
                            readonly>
                        </div>

                        <div class="col-md-3 mb-3">
                            <label class="form-label">School Type</label>

                            <input
                            type="text"
                            id="school_type"
                            name="school_type"
                            class="form-control"
                            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">
                        </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">
                        </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">
                        </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">
                        </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">
                        </div>

                    </div>

                </div>


                <?php foreach ($units as $unit) { ?>

                    <div
                        class="wizard-step standard-unit-step"
                        data-title="<?= htmlspecialchars($unit['name'], ENT_QUOTES) ?>"
                        data-unit-id="<?= (int)$unit['id'] ?>">
                    </div>

                <?php } ?>


                <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 units such as Library, Staff Room or Smart Room 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 and are not saved in the database.
                    </p>

                    <div id="summary"></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>
                <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-check"></i> 
                    Submit Survey
                </button>
            </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="100" 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 = 'add';

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 = {};
window.SAVED_OTHER_UNITS = [];
</script>

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

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

