var _checklistCache = null, _inspectionCache = [];

$(function () {
    loadVehicles();
    loadChecklist(function () { loadInspections(); });
    $('#filterVehicle, #filterDateFrom, #filterDateTo').on('change', loadInspections);
    $('#btnRefresh').on('click', loadInspections);
    $('#btnAddInspection').on('click', function () { clearForm(); new bootstrap.Modal(document.getElementById('inspectionModal')).show(); });
    $('#saveInspection').on('click', saveInspection);
    $(document).on('click', '.btn-edit-inspection', function () {
        var r = _inspectionCache.find(function (x) { return String(x.id) === String($(this).data('id')); });
        if (r) loadAndEditInspection(r.id);
    });
    $(document).on('click', '.btn-delete-inspection', function () {
        if (!confirm('Delete this inspection?')) return;
        $.post('api/vehicle_inspection.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) {
            if (r.status === 'success') { showToast('Deleted', 'success'); loadInspections(); } else showToast(r.message, 'danger');
        }, 'json');
    });
    $('#btnExportInspCsv').on('click', function () { window.location.href = 'api/data_export.php?type=vehicle_inspection&format=csv'; });
    $('#btnExportInspXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=vehicle_inspection&format=xlsx'; });
    $('#btnExportInspPdf').on('click', function () { window.location.href = 'api/data_export.php?type=vehicle_inspection&format=pdf'; });
});

function loadVehicles() {
    $.get('api/compliance.php', { action: 'vehicles' }, function (r) {
        if (r.status === 'success') {
            populateSelect('#filterVehicle', r.data, 'All vehicles');
            populateSelect('#inspection_vehicle_id', r.data, 'Select vehicle');
        }
    }, 'json');
}

function loadChecklist(cb) {
    $.get('api/vehicle_inspection.php', { action: 'checklist' }, function (r) {
        if (r.status === 'success') {
            _checklistCache = r.data;
            renderChecklistTable('bodyInteriorTable', r.data.body_interior || []);
            renderChecklistTable('devicesRoutingTable', r.data.devices_routing || []);
            if (cb) cb();
        }
    }, 'json');
}

function renderChecklistTable(tableId, items) {
    var html = '';
    (items || []).forEach(function (item) {
        html += '<tr data-item-id="' + item.id + '">' +
            '<td class="fw-medium">' + escapeHtml(item.item_name) + '</td>' +
            '<td><div class="radio-group"><div class="form-check"><input class="form-check-input result-radio" type="radio" name="result_' + item.id + '" value="pass" checked></div></div></td>' +
            '<td><div class="radio-group"><div class="form-check"><input class="form-check-input result-radio" type="radio" name="result_' + item.id + '" value="fail"></div></div></td>' +
            '<td><div class="radio-group"><div class="form-check"><input class="form-check-input result-radio" type="radio" name="result_' + item.id + '" value="na"></div></div></td>' +
            '<td><input type="text" class="form-control form-control-sm item-remarks" placeholder="Remarks" maxlength="255"></td>' +
            '</tr>';
    });
    $('#' + tableId + ' tbody').html(html);
}

function loadInspections() {
    $.get('api/vehicle_inspection.php', {
        action: 'list',
        vehicle_id: $('#filterVehicle').val(),
        date_from: $('#filterDateFrom').val(),
        date_to: $('#filterDateTo').val()
    }, function (res) {
        if (res.status !== 'success') return;
        _inspectionCache = res.data || [];
        var html = '';
        if (!_inspectionCache.length) html = '<tr><td colspan="7" class="text-center py-4 text-muted">No inspections</td></tr>';
        else _inspectionCache.forEach(function (r) {
            var badge = r.overall_result === 'pass' ? '<span class="badge bg-success">Pass</span>' : '<span class="badge bg-danger">Fail</span>';
            html += '<tr><td>' + formatDate(r.inspection_date) + '</td><td>' + escapeHtml(r.plate_number || '-') + '</td><td>' + escapeHtml(r.inspector_name || '-') + '</td>' +
                '<td>' + (r.total_items || 0) + '</td><td>' + (r.fail_count || 0) + '</td><td>' + badge + '</td>' +
                '<td class="text-end"><div class="d-flex gap-1 justify-content-end"><button class="btn btn-sm btn-outline-primary btn-edit-inspection" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete-inspection" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#inspectionTable').html(html);
    }, 'json');
}

function loadAndEditInspection(id) {
    $.get('api/vehicle_inspection.php', { action: 'get', id: id }, function (r) {
        if (r.status !== 'success') { showToast(r.message, 'danger'); return; }
        var data = r.data;
        clearForm();
        $('#inspection_id').val(data.id);
        $('#inspection_vehicle_id').val(data.vehicle_id);
        $('#inspection_date').val(normalizeDate(data.inspection_date));
        $('#inspector_name').val(data.inspector_name || '');
        $('#overall_result').val(data.overall_result || 'pass');
        $('#inspection_notes').val(data.notes || '');

        (data.results || []).forEach(function (res) {
            var radio = document.querySelector('input[name="result_' + res.checklist_item_id + '"][value="' + res.result + '"]');
            if (radio) radio.checked = true;
            var remarks = document.querySelector('tr[data-item-id="' + res.checklist_item_id + '"] .item-remarks');
            if (remarks) remarks.value = res.remarks || '';
        });

        new bootstrap.Modal(document.getElementById('inspectionModal')).show();
    }, 'json');
}

function saveInspection() {
    var results = [];
    $('#inspectionModal .result-radio').each(function () {
        if (this.checked) {
            var tr = $(this).closest('tr');
            var itemId = tr.data('item-id');
            var remarks = tr.find('.item-remarks').val() || '';
            results.push({ checklist_item_id: itemId, result: this.value, remarks: remarks });
        }
    });

    var p = {
        id: $('#inspection_id').val(),
        vehicle_id: $('#inspection_vehicle_id').val(),
        inspection_date: $('#inspection_date').val(),
        inspector_name: $('#inspector_name').val(),
        overall_result: $('#overall_result').val(),
        notes: $('#inspection_notes').val(),
        results: results,
        csrf_token: window.CSRF_TOKEN
    };

    if (!p.vehicle_id || !p.inspection_date) { showToast('Vehicle and date are required', 'danger'); return; }

    $.ajax({
        url: 'api/vehicle_inspection.php?action=save',
        method: 'POST',
        data: JSON.stringify(p),
        contentType: 'application/json',
        success: function (r) {
            if (r.status !== 'success') { showToast(r.message, 'danger'); return; }
            bootstrap.Modal.getInstance(document.getElementById('inspectionModal')).hide();
            loadInspections();
            showToast('Inspection saved!', 'success');
        },
        error: function () { showToast('Server error', 'danger'); }
    });
}

function clearForm() {
    $('#inspectionForm')[0].reset();
    $('#inspection_id').val('');
    $('#inspection_notes').val('');
    $('#inspector_name').val('');
    $('#overall_result').val('pass');
    loadChecklist();
}

function populateSelect(sel, rows, p) { var h = '<option value="">' + escapeHtml(p) + '</option>'; (rows || []).forEach(function (r) { h += '<option value="' + escapeHtml(r.id) + '">' + escapeHtml(r.label || r.name || '-') + '</option>'; }); $(sel).html(h); }
function formatDate(d) { if (!d) return '-'; var dt = new Date(d); return Number.isNaN(dt.getTime()) ? d : dt.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); }
function normalizeDate(d) { return d ? String(d).slice(0, 10) : ''; }
function showToast(m, t) { var e = document.createElement('div'); e.className = 'position-fixed top-0 end-0 p-3'; e.style.zIndex = '9999'; e.innerHTML = '<div class="alert alert-' + t + ' alert-dismissible fade show" role="alert">' + escapeHtml(m) + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>'; document.body.appendChild(e); setTimeout(function () { e.remove(); }, 5000); }
function escapeHtml(t) { return $('<div>').text(t || '').html(); }
