document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    /*
|--------------------------------------------------------------------------
| Full report filters
|--------------------------------------------------------------------------
*/

const reportDistrict =
    document.getElementById('reportDistrict');

const reportZone =
    document.getElementById('reportZone');

const reportDivision =
    document.getElementById('reportDivision');

const reportHierarchy =
    window.REPORT_LOCATION_HIERARCHY || {};

function replaceSelectOptions(
    select,
    firstLabel,
    values
) {
    if (!select) {
        return;
    }

    select.innerHTML = '';

    const defaultOption =
        document.createElement('option');

    defaultOption.value = '';
    defaultOption.textContent = firstLabel;

    select.appendChild(defaultOption);

    values.forEach(function (value) {
        const option =
            document.createElement('option');

        option.value = value;
        option.textContent = value;

        select.appendChild(option);
    });
}

function getReportZones(district) {
    if (
        district &&
        district !== 'ALL' &&
        reportHierarchy[district]
    ) {
        return Object.keys(
            reportHierarchy[district]
        );
    }

    const zones = new Set();

    Object.values(reportHierarchy)
        .forEach(function (districtZones) {
            Object.keys(districtZones)
                .forEach(function (zone) {
                    zones.add(zone);
                });
        });

    return Array.from(zones).sort();
}

function getReportDivisions(
    district,
    zone
) {
    const divisions = new Set();

    if (
        district &&
        district !== 'ALL' &&
        reportHierarchy[district]
    ) {
        if (
            zone &&
            reportHierarchy[district][zone]
        ) {
            Object.keys(
                reportHierarchy[district][zone]
            ).forEach(function (division) {
                divisions.add(division);
            });
        } else {
            Object.values(
                reportHierarchy[district]
            ).forEach(function (zoneDivisions) {
                Object.keys(zoneDivisions)
                    .forEach(function (division) {
                        divisions.add(division);
                    });
            });
        }
    } else {
        Object.values(reportHierarchy)
            .forEach(function (districtZones) {
                Object.entries(districtZones)
                    .forEach(function (entry) {
                        const currentZone = entry[0];
                        const zoneDivisions = entry[1];

                        if (
                            !zone ||
                            currentZone === zone
                        ) {
                            Object.keys(zoneDivisions)
                                .forEach(function (division) {
                                    divisions.add(division);
                                });
                        }
                    });
            });
    }

    return Array.from(divisions).sort();
}

function refreshReportDivisions() {
    if (
        !reportDistrict ||
        !reportZone ||
        !reportDivision
    ) {
        return;
    }

    replaceSelectOptions(
        reportDivision,
        'All Divisions',
        getReportDivisions(
            reportDistrict.value,
            reportZone.value
        )
    );
}

function refreshReportZones() {
    if (!reportDistrict || !reportZone) {
        return;
    }

    if (
        window.REPORT_USER_ROLE ===
        'zonal_director'
    ) {
        replaceSelectOptions(
            reportZone,
            'All Zones',
            [window.REPORT_USER_ZONE]
        );

        reportZone.value =
            window.REPORT_USER_ZONE;

        reportZone.disabled = true;
    } else {
        replaceSelectOptions(
            reportZone,
            'All Zones',
            getReportZones(
                reportDistrict.value
            )
        );
    }

    refreshReportDivisions();
}

if (
    reportDistrict &&
    reportZone &&
    reportDivision
) {
    reportDistrict.addEventListener(
        'change',
        refreshReportZones
    );

    reportZone.addEventListener(
        'change',
        refreshReportDivisions
    );

    refreshReportZones();
}

/*
|--------------------------------------------------------------------------
| Report checkbox groups
|--------------------------------------------------------------------------
*/

document
    .querySelectorAll('[data-check-group]')
    .forEach(function (button) {
        button.addEventListener(
            'click',
            function () {
                const className =
                    this.dataset.checkGroup;

                const checked =
                    this.dataset.checkAction ===
                    'all';

                document
                    .querySelectorAll(
                        '.' + className
                    )
                    .forEach(function (checkbox) {
                        checkbox.checked = checked;
                    });
            }
        );
    });

        /*
    |--------------------------------------------------------------------------
    | Survey list delete modal
    |--------------------------------------------------------------------------
    */

    const deleteSurveyModal =
        document.getElementById('deleteSurveyModal');

    const deleteSurveyForm =
        document.getElementById('deleteSurveyForm');

    const deleteSurveyId =
        document.getElementById('deleteSurveyId');

    const deleteSurveySchoolName =
        document.getElementById('deleteSurveySchoolName');

    if (
        deleteSurveyModal &&
        deleteSurveyForm &&
        deleteSurveyId &&
        deleteSurveySchoolName
    ) {
        deleteSurveyModal.addEventListener(
            'show.bs.modal',
            function (event) {
                const button = event.relatedTarget;

                if (!button) {
                    return;
                }

                deleteSurveyId.value =
                    button.dataset.surveyId || '';

                deleteSurveySchoolName.textContent =
                    button.dataset.schoolName ||
                    'Selected survey';
            }
        );

        deleteSurveyForm.addEventListener(
            'submit',
            async function (event) {
                event.preventDefault();

                if (!deleteSurveyId.value) {
                    await Swal.fire({
                        icon: 'error',
                        title: 'Invalid survey',
                        text: 'A valid survey was not selected.'
                    });

                    return;
                }

                const confirmation = await Swal.fire({
                    icon: 'warning',
                    title: 'Delete this survey?',
                    text: 'All related equipment records will be permanently deleted.',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#dc3545'
                });

                if (confirmation.isConfirmed) {
                    deleteSurveyForm.submit();
                }
            }
        );
    }

        /*
    |--------------------------------------------------------------------------
    | Stop here when this is not a survey wizard page
    |--------------------------------------------------------------------------
    */

    const surveyFormElement =
        document.getElementById('surveyForm');

    if (!surveyFormElement) {
        return;
    }

    let currentStep = 0;

    const mode = window.SURVEY_MODE === 'edit' ? 'edit' : 'add';
    const isEditMode = mode === 'edit';

    const steps = Array.from(document.querySelectorAll('.wizard-step'));
    const form = surveyFormElement;
    const otherUnitModalElement = document.getElementById('otherUnitModal');
    const otherUnitModal = new bootstrap.Modal(otherUnitModalElement);

    const censusInput = document.getElementById('census_no');
    const nextButton = document.getElementById('nextButton');
    const otherUnitsContainer = document.getElementById('otherUnits');

    const savedStandard = window.SAVED_STANDARD || {};
    const savedOtherUnits = window.SAVED_OTHER_UNITS || [];

    const schoolFieldIds = {
        district: 'district',
        zone_name: 'zone',
        division_name: 'division',
        school_name: 'school_name',
        school_category: 'school_category',
        school_type: 'school_type'
    };

    const schoolCache = new Map();

    let schoolLookupTimer = null;
    let schoolLookupController = null;
    let validSchoolLoaded = isEditMode;

    function escapeHtml(value) {
        const div = document.createElement('div');
        div.textContent = String(value ?? '');
        return div.innerHTML;
    }

    function normalizeQuantity(value) {
        const number = Number.parseInt(value, 10);

        if (!Number.isInteger(number) || number < 0) {
            return 0;
        }

        return number;
    }

    function standardEquipmentRow(item, savedValues) {
        const values = savedValues || {};

        return `
            <div class="card border-secondary mb-3 equipment-row zero-equipment-row">

                <div class="card-body">

                    <input
                        type="hidden"
                        class="equipment-id"
                        value="${Number(item.id) || ''}">

                    <input
                        type="hidden"
                        class="equipment-name"
                        value="${escapeHtml(item.name || '')}">

                    <div class="row g-2 align-items-end">

                        <div class="col-12 col-md-4">

                            <label class="form-label small">
                                Equipment
                            </label>

                            <div class="form-control bg-light fw-semibold">
                                ${escapeHtml(item.name || '')}
                            </div>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Working
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input working"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.working)}"
                                required>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Not Working
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input not-working"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.not_working)}"
                                required>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Repair
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input repair"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.repair)}"
                                required>

                        </div>

                        <div class="col-12 col-md-2">

                            <label class="form-label small">
                                Total
                            </label>

                            <input
                                type="text"
                                class="form-control equipment-total text-center fw-bold"
                                value="0"
                                readonly>

                        </div>

                    </div>

                </div>

            </div>
        `;
    }

    function customEquipmentRow(item) {
        const values = item || {};

        return `
            <div class="card border-secondary mb-3 equipment-row zero-equipment-row">

                <div class="card-body">

                    <input
                        type="hidden"
                        class="equipment-id"
                        value="">

                    <div class="row g-2 align-items-end">

                        <div class="col-12 col-md-4">

                            <label class="form-label small">
                                Equipment Name
                            </label>

                            <input
                                type="text"
                                class="form-control equipment-name"
                                maxlength="150"
                                placeholder="Enter equipment name"
                                value="${escapeHtml(values.equipment_name || '')}"
                                required>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Working
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input working"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.working)}"
                                required>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Not Working
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input not-working"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.not_working)}"
                                required>

                        </div>

                        <div class="col-4 col-md-2">

                            <label class="form-label small">
                                Repair
                            </label>

                            <input
                                type="number"
                                class="form-control quantity-input repair"
                                min="0"
                                step="1"
                                inputmode="numeric"
                                value="${normalizeQuantity(values.repair)}"
                                required>

                        </div>

                        <div class="col-8 col-md-1">

                            <label class="form-label small">
                                Total
                            </label>

                            <input
                                type="text"
                                class="form-control equipment-total text-center fw-bold"
                                value="0"
                                readonly>

                        </div>

                        <div class="col-4 col-md-1 d-grid">

                            <button
                                type="button"
                                class="btn btn-outline-danger remove-equipment"
                                title="Remove equipment">

                                <i class="fa-solid fa-xmark"></i>

                            </button>

                        </div>

                    </div>

                </div>

            </div>
        `;
    }

    function unitCard(name, equipmentHtml, removable, details) {
        return `
            <div
                class="card shadow-sm unit-card mb-4"
                data-section="${escapeHtml(name)}"
                data-custom-unit="${removable ? '1' : '0'}">

                <div class="card-header bg-light d-flex justify-content-between align-items-center">

                    <strong>
                        ${escapeHtml(name)}
                    </strong>

                    ${
                        removable
                            ? `
                                <button
                                    type="button"
                                    class="btn btn-danger btn-sm remove-unit">

                                    <i class="fa-solid fa-trash"></i>
                                    Remove Unit

                                </button>
                            `
                            : ''
                    }

                </div>

                <div class="card-body">

                    ${
                        removable
                            ? `
                                <div class="mb-3">

                                    <label class="form-label">
                                        Unit Details
                                    </label>

                                    <textarea
                                        class="form-control unit-details"
                                        rows="2"
                                        maxlength="5000"
                                        placeholder="Optional details about this unit">${escapeHtml(details || '')}</textarea>

                                </div>
                            `
                            : ''
                    }

                    <div class="equipment-list">
                        ${equipmentHtml}
                    </div>

                    ${
                        removable
                            ? `
                                <button
                                    type="button"
                                    class="btn btn-outline-primary btn-sm add-equipment">

                                    <i class="fa-solid fa-plus"></i>
                                    Add Equipment

                                </button>
                            `
                            : ''
                    }

                    <hr>

                    <div class="row text-center unit-summary">

                        <div class="col-6 col-md-3 mb-2">
                            <small class="text-muted d-block">Working</small>
                            <strong class="unit-working-total">0</strong>
                        </div>

                        <div class="col-6 col-md-3 mb-2">
                            <small class="text-muted d-block">Not Working</small>
                            <strong class="unit-not-working-total">0</strong>
                        </div>

                        <div class="col-6 col-md-3 mb-2">
                            <small class="text-muted d-block">Repair</small>
                            <strong class="unit-repair-total">0</strong>
                        </div>

                        <div class="col-6 col-md-3 mb-2">
                            <small class="text-muted d-block">Total</small>
                            <strong class="unit-grand-total">0</strong>
                        </div>

                    </div>

                </div>

            </div>
        `;
    }

    document.querySelectorAll('.standard-unit-step').forEach(function (step) {
        const unitId = Number(step.dataset.unitId);

        const unit = window.SURVEY_UNITS.find(function (item) {
            return Number(item.id) === unitId;
        });

        if (!unit) {
            step.innerHTML = `
                <div class="alert alert-warning">
                    Unable to load this unit.
                </div>
            `;

            return;
        }

        const savedSection = savedStandard[unit.name] || {};

        const rows = unit.equipment.length
            ? unit.equipment.map(function (item) {
                return standardEquipmentRow(
                    item,
                    savedSection[String(item.id)] ||
                    savedSection[item.id] ||
                    {}
                );
            }).join('')
            : `
                <div class="alert alert-warning unit-empty-message">
                    No equipment has been assigned to this unit.
                </div>
            `;

        step.innerHTML = unitCard(
            unit.name,
            rows,
            false,
            ''
        );
    });

    savedOtherUnits.forEach(function (unit) {
        const rows = (unit.equipment || [])
            .map(customEquipmentRow)
            .join('');

        otherUnitsContainer.insertAdjacentHTML(
            'beforeend',
            unitCard(
                unit.unit_name,
                rows || `
                    <div class="alert alert-info unit-empty-message">
                        Click Add Equipment to enter equipment for this unit.
                    </div>
                `,
                true,
                unit.details || ''
            )
        );
    });

    document.getElementById('otherUnitHelp').classList.toggle(
        'd-none',
        savedOtherUnits.length > 0
    );

    function updateEquipmentRow(row) {
        if (!row) {
            return;
        }

        const workingInput = row.querySelector('.working');
        const notWorkingInput = row.querySelector('.not-working');
        const repairInput = row.querySelector('.repair');

        const working = normalizeQuantity(workingInput.value);
        const notWorking = normalizeQuantity(notWorkingInput.value);
        const repair = normalizeQuantity(repairInput.value);

        workingInput.value = working;
        notWorkingInput.value = notWorking;
        repairInput.value = repair;

        const total = working + notWorking + repair;

        row.querySelector('.equipment-total').value = total;

        row.classList.toggle(
            'zero-equipment-row',
            total === 0
        );

        updateUnitTotals(row.closest('.unit-card'));
    }

    function updateUnitTotals(unitCardElement) {
        if (!unitCardElement) {
            return;
        }

        let workingTotal = 0;
        let notWorkingTotal = 0;
        let repairTotal = 0;

        unitCardElement
            .querySelectorAll('.equipment-row')
            .forEach(function (row) {
                workingTotal += normalizeQuantity(
                    row.querySelector('.working').value
                );

                notWorkingTotal += normalizeQuantity(
                    row.querySelector('.not-working').value
                );

                repairTotal += normalizeQuantity(
                    row.querySelector('.repair').value
                );
            });

        unitCardElement.querySelector('.unit-working-total').textContent =
            workingTotal;

        unitCardElement.querySelector('.unit-not-working-total').textContent =
            notWorkingTotal;

        unitCardElement.querySelector('.unit-repair-total').textContent =
            repairTotal;

        unitCardElement.querySelector('.unit-grand-total').textContent =
            workingTotal + notWorkingTotal + repairTotal;
    }

    function updateAllUnitTotals() {
        document.querySelectorAll('.unit-card').forEach(function (unitCardElement) {
            updateUnitTotals(unitCardElement);
        });
    }

    function bindRows() {
        document.querySelectorAll('.add-equipment').forEach(function (button) {
            button.onclick = function () {
                const equipmentList =
                    this.closest('.unit-card')
                        .querySelector('.equipment-list');

                const emptyMessage =
                    equipmentList.querySelector('.unit-empty-message');

                if (emptyMessage) {
                    emptyMessage.remove();
                }

                equipmentList.insertAdjacentHTML(
                    'beforeend',
                    customEquipmentRow({})
                );

                bindRows();

                const newRow = equipmentList.lastElementChild;

                if (newRow) {
                    const nameInput = newRow.querySelector('.equipment-name');

                    if (nameInput) {
                        nameInput.focus();
                    }
                }
            };
        });

        document.querySelectorAll('.remove-equipment').forEach(function (button) {
            button.onclick = function () {
                const row = this.closest('.equipment-row');
                const unitCardElement = row.closest('.unit-card');

                row.remove();

                updateUnitTotals(unitCardElement);
            };
        });

        document.querySelectorAll('.remove-unit').forEach(function (button) {
            button.onclick = async function () {
                const unitCardElement = this.closest('.unit-card');
                const unitName = unitCardElement.dataset.section;

                const confirmation = await Swal.fire({
                    title: 'Remove ' + unitName + '?',
                    text: 'All equipment entered for this unit will be removed.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Remove'
                });

                if (!confirmation.isConfirmed) {
                    return;
                }

                unitCardElement.remove();

                document
                    .getElementById('otherUnitHelp')
                    .classList.toggle(
                        'd-none',
                        document.querySelectorAll(
                            '#otherUnits .unit-card'
                        ).length > 0
                    );
            };
        });

        document.querySelectorAll('.quantity-input').forEach(function (input) {
            input.oninput = function () {
                this.value = this.value.replace(/[^\d]/g, '');

                if (this.value === '') {
                    this.value = '0';
                }

                updateEquipmentRow(
                    this.closest('.equipment-row')
                );
            };

            input.onblur = function () {
                this.value = normalizeQuantity(this.value);

                updateEquipmentRow(
                    this.closest('.equipment-row')
                );
            };

            input.onkeydown = function (event) {
                if (
                    event.key === '-' ||
                    event.key === '+' ||
                    event.key === '.' ||
                    event.key === 'e' ||
                    event.key === 'E'
                ) {
                    event.preventDefault();
                }
            };
        });

        updateAllUnitTotals();
    }

    function collectDetails() {
        return Array.from(
            document.querySelectorAll('.unit-card')
        )
            .map(function (card) {
                const detailsField =
                    card.querySelector('.unit-details');

                return {
                    section: card.dataset.section,
                    is_custom:
                        card.dataset.customUnit === '1',
                    details:
                        detailsField
                            ? detailsField.value.trim()
                            : '',
                    equipment: Array.from(
                        card.querySelectorAll('.equipment-row')
                    )
                        .map(function (row) {
                            const equipmentIdField =
                                row.querySelector('.equipment-id');

                            const equipmentNameField =
                                row.querySelector('.equipment-name');

                            return {
                                equipment_id:
                                    equipmentIdField
                                        ? equipmentIdField.value
                                        : '',

                                equipment_name:
                                    equipmentNameField
                                        ? equipmentNameField.value.trim()
                                        : '',

                                working:
                                    normalizeQuantity(
                                        row.querySelector('.working').value
                                    ),

                                not_working:
                                    normalizeQuantity(
                                        row.querySelector('.not-working').value
                                    ),

                                repair:
                                    normalizeQuantity(
                                        row.querySelector('.repair').value
                                    )
                            };
                        })
                        .filter(function (item) {
                            return item.equipment_name !== '';
                        })
                };
            })
            .filter(function (unit) {
                return unit.equipment.length > 0;
            });
    }

    function renderSummary() {
        const units = collectDetails();

        if (!units.length) {
            document.getElementById('summary').innerHTML = `
                <div class="alert alert-warning">
                    Add at least one equipment record.
                </div>
            `;

            return;
        }

        let grandWorking = 0;
        let grandNotWorking = 0;
        let grandRepair = 0;

        const unitTables = units.map(function (unit) {
            let unitWorking = 0;
            let unitNotWorking = 0;
            let unitRepair = 0;

            const rows = unit.equipment.map(function (item) {
                const total =
                    item.working +
                    item.not_working +
                    item.repair;

                unitWorking += item.working;
                unitNotWorking += item.not_working;
                unitRepair += item.repair;

                return `
                    <tr>
                        <td>${escapeHtml(item.equipment_name)}</td>
                        <td>${item.working}</td>
                        <td>${item.not_working}</td>
                        <td>${item.repair}</td>
                        <td class="fw-bold">${total}</td>
                    </tr>
                `;
            }).join('');

            grandWorking += unitWorking;
            grandNotWorking += unitNotWorking;
            grandRepair += unitRepair;

            return `
                <div class="card mb-4">

                    <div class="card-header bg-light">
                        <strong>${escapeHtml(unit.section)}</strong>
                    </div>

                    <div class="table-responsive">

                        <table class="table table-bordered table-sm mb-0">

                            <thead class="table-dark">

                                <tr>
                                    <th>Equipment</th>
                                    <th>Working</th>
                                    <th>Not Working</th>
                                    <th>Repair</th>
                                    <th>Total</th>
                                </tr>

                            </thead>

                            <tbody>

                                ${rows}

                                <tr class="table-primary fw-bold">
                                    <td>Unit Total</td>
                                    <td>${unitWorking}</td>
                                    <td>${unitNotWorking}</td>
                                    <td>${unitRepair}</td>
                                    <td>${unitWorking + unitNotWorking + unitRepair}</td>
                                </tr>

                            </tbody>

                        </table>

                    </div>

                </div>
            `;
        }).join('');

        document.getElementById('summary').innerHTML = `
            <div class="row mb-4">

                <div class="col-6 col-md-3 mb-3">
                    <div class="card shadow-sm text-center h-100">
                        <div class="card-body">
                            <small class="text-muted d-block">Working</small>
                            <h3 class="text-success mb-0">${grandWorking}</h3>
                        </div>
                    </div>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <div class="card shadow-sm text-center h-100">
                        <div class="card-body">
                            <small class="text-muted d-block">Not Working</small>
                            <h3 class="text-danger mb-0">${grandNotWorking}</h3>
                        </div>
                    </div>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <div class="card shadow-sm text-center h-100">
                        <div class="card-body">
                            <small class="text-muted d-block">Repair</small>
                            <h3 class="text-warning mb-0">${grandRepair}</h3>
                        </div>
                    </div>
                </div>

                <div class="col-6 col-md-3 mb-3">
                    <div class="card shadow-sm text-center h-100">
                        <div class="card-body">
                            <small class="text-muted d-block">Grand Total</small>
                            <h3 class="text-primary mb-0">
                                ${grandWorking + grandNotWorking + grandRepair}
                            </h3>
                        </div>
                    </div>
                </div>

            </div>

            ${unitTables}
        `;
    }

    function updateStep() {
        steps.forEach(function (step, index) {
            step.classList.toggle(
                'active',
                index === currentStep
            );
        });

        document.getElementById('previousButton').disabled =
            currentStep === 0;

        nextButton.classList.toggle(
            'd-none',
            currentStep === steps.length - 1
        );

        document.getElementById('submitButton').classList.toggle(
            'd-none',
            currentStep !== steps.length - 1
        );

        document.getElementById('stepCounter').textContent =
            'Step ' + (currentStep + 1) +
            ' of ' + steps.length;

        if (currentStep === steps.length - 1) {
            renderSummary();
        }
    }

    document.getElementById('previousButton').onclick = function () {
        if (currentStep > 0) {
            currentStep--;
            updateStep();
        }
    };

    nextButton.onclick = async function () {
        if (
            currentStep === 0 &&
            !validSchoolLoaded
        ) {
            await Swal.fire(
                'School required',
                'Enter a valid census number and wait for the school details to load.',
                'warning'
            );

            censusInput.focus();
            return;
        }

        if (currentStep < steps.length - 1) {
            currentStep++;
            updateStep();
        }
    };

    document.getElementById('addOtherUnit').onclick = function () {
        document.getElementById('otherUnitForm').reset();
        otherUnitModal.show();
    };

    document.getElementById('otherUnitForm').onsubmit = function (event) {
        event.preventDefault();

        const nameInput =
            document.getElementById('other_unit_name');

        const unitName = nameInput.value.trim();

        if (unitName === '') {
            Swal.fire(
                'Unit name required',
                'Please enter the place or unit name.',
                'warning'
            );

            return;
        }

        const duplicateUnit = Array.from(
            document.querySelectorAll('.unit-card')
        ).some(function (card) {
            return (
                card.dataset.section.toLowerCase() ===
                unitName.toLowerCase()
            );
        });

        if (duplicateUnit) {
            Swal.fire(
                'Duplicate unit',
                'A unit with this name has already been added.',
                'warning'
            );

            return;
        }

        otherUnitsContainer.insertAdjacentHTML(
            'beforeend',
            unitCard(
                unitName,
                customEquipmentRow({}),
                true,
                ''
            )
        );

        document
            .getElementById('otherUnitHelp')
            .classList.add('d-none');

        otherUnitModal.hide();
        nameInput.value = '';

        bindRows();

        const newUnitCard =
            otherUnitsContainer.lastElementChild;

        updateUnitTotals(newUnitCard);

        const equipmentNameInput =
            newUnitCard.querySelector('.equipment-name');

        if (equipmentNameInput) {
            equipmentNameInput.focus();
        }
    };

    form.onsubmit = async function (event) {
        event.preventDefault();

        const details = collectDetails();

        if (!details.length) {
            await Swal.fire(
                'Equipment required',
                'Add at least one equipment record before submitting.',
                'warning'
            );

            return;
        }

        const totalQuantity = details.reduce(
            function (surveyTotal, unit) {
                return surveyTotal + unit.equipment.reduce(
                    function (unitTotal, item) {
                        return (
                            unitTotal +
                            item.working +
                            item.not_working +
                            item.repair
                        );
                    },
                    0
                );
            },
            0
        );

        if (totalQuantity === 0) {
            const zeroConfirmation = await Swal.fire({
                title: 'All quantities are zero',
                text: 'No equipment quantities have been entered. Do you still want to continue?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText:
                    isEditMode
                        ? 'Update with zero values'
                        : 'Submit with zero values',
                cancelButtonText: 'Go Back'
            });

            if (!zeroConfirmation.isConfirmed) {
                return;
            }
        }

        if (isEditMode) {
            const updateConfirmation = await Swal.fire({
                title: 'Update survey?',
                text: 'The saved equipment details will be replaced with these values.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Update Survey'
            });

            if (!updateConfirmation.isConfirmed) {
                return;
            }
        }

        document
            .getElementById('survey_details')
            .value = JSON.stringify(details);

        form.submit();
    };

    function clearSchoolFields() {
        Object.values(schoolFieldIds).forEach(function (elementId) {
            const field = document.getElementById(elementId);

            if (field) {
                field.value = '';
            }
        });

        validSchoolLoaded = false;
    }

    function fillSchoolFields(school) {
        Object.entries(schoolFieldIds).forEach(
            function ([property, elementId]) {
                const field = document.getElementById(elementId);

                if (field) {
                    field.value =
                        school[property] || '';
                }
            }
        );

        validSchoolLoaded =
            Boolean(school.school_name);
    }

    async function lookupSchool() {
        if (isEditMode) {
            return;
        }

        const censusNo = censusInput.value.trim();

        clearSchoolFields();

        if (censusNo === '') {
            return;
        }

        if (schoolCache.has(censusNo)) {
            fillSchoolFields(
                schoolCache.get(censusNo)
            );

            return;
        }

        if (schoolLookupController) {
            schoolLookupController.abort();
        }

        schoolLookupController =
            new AbortController();

        const originalPlaceholder =
            censusInput.placeholder;

        censusInput.disabled = true;
        censusInput.placeholder =
            'Searching school...';

        try {
            const formData = new FormData();
            formData.append('census_no', censusNo);

            const response = await fetch(
                window.BASE_URL +
                'admin/ajax/get_school.php',
                {
                    method: 'POST',
                    body: formData,
                    signal:
                        schoolLookupController.signal
                }
            );

            let result;

            try {
                result = await response.json();
            } catch (error) {
                throw new Error(
                    'The server returned an invalid response.'
                );
            }

            if (
                !response.ok ||
                !result.success
            ) {
                throw new Error(
                    result.message ||
                    'School not found.'
                );
            }

            if (result.survey_exists) {
                clearSchoolFields();

                await Swal.fire({
                    icon: 'warning',
                    title: 'Survey already exists',
                    text: 'A survey has already been submitted for this school.',
                    confirmButtonText: 'OK'
                });

                censusInput.value = '';
                censusInput.focus();

                return;
            }

            schoolCache.set(
                censusNo,
                result.school
            );

            fillSchoolFields(result.school);

        } catch (error) {
            if (error.name !== 'AbortError') {
                clearSchoolFields();

                await Swal.fire(
                    'School Lookup',
                    error.message ||
                    'Unable to find the school.',
                    'warning'
                );
            }
        } finally {
            censusInput.disabled = false;
            censusInput.placeholder =
                originalPlaceholder;

            censusInput.focus();
        }
    }

    if (!isEditMode) {
        censusInput.addEventListener(
            'input',
            function () {
                clearTimeout(schoolLookupTimer);
                clearSchoolFields();

                schoolLookupTimer = setTimeout(
                    lookupSchool,
                    500
                );
            }
        );

        censusInput.addEventListener(
            'keydown',
            function (event) {
                if (event.key === 'Enter') {
                    event.preventDefault();

                    clearTimeout(
                        schoolLookupTimer
                    );

                    lookupSchool();
                }
            }
        );
    }

    bindRows();
    updateStep();
});
