let _incidentCache = [];

$(function () {
    loadIncidents(); loadIncidentVehicles(); loadIncidentDrivers();
    $('#incVehicleFilter, #incStatusFilter, #incTypeFilter, #incSeverityFilter, #incDateFrom, #incDateTo').on('change', loadIncidents);
    $('#btnRefreshIncidents').on('click', loadIncidents);
    $('#btnAddIncident').on('click', function () { clearIncidentForm(); new bootstrap.Modal(document.getElementById('incidentModal')).show(); });
    $('#saveIncident').on('click', saveIncident);
    $(document).on('click', '.btn-edit-incident', function () { var r = _incidentCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populateIncidentForm(r); });
    $(document).on('click', '.btn-delete-incident', function () { if (!confirm('Delete incident?')) return; $.post('api/incidents.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadIncidents(); showToast('Deleted','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $('#btnExportIncidentsCsv').on('click', function () { window.location.href = 'api/data_export.php?type=incidents&format=csv'; });
    $('#btnExportIncidentsXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=incidents&format=xlsx'; });
    $('#btnExportIncidentsPdf').on('click', function () { window.location.href = 'api/data_export.php?type=incidents&format=pdf'; });
});

function loadIncidentVehicles() {
    $.get('api/compliance.php', { action: 'vehicles' }, function (r) {
        if (r.status==='success') { populateSelect('#incVehicleFilter', r.data, 'All'); populateSelect('#incident_vehicle_id', r.data, 'Select vehicle'); }
    },'json');
}
function loadIncidentDrivers() {
    $.get('api/drivers.php', { action: 'list' }, function (r) {
        if (r.status==='success') { var d = (r.data||[]).map(function(x){return{id:x.id,label:x.full_name,name:x.full_name};}); populateSelect('#incident_driver_id', d, 'Select driver'); }
    },'json');
}

function loadIncidents() {
    $.get('api/incidents.php', {
        action: 'list', vehicle_id: $('#incVehicleFilter').val(), status: $('#incStatusFilter').val(),
        type: $('#incTypeFilter').val(), severity: $('#incSeverityFilter').val(),
        date_from: $('#incDateFrom').val(), date_to: $('#incDateTo').val()
    }, function (res) {
        if (res.status!=='success') return;
        var rows = res.data||[]; _incidentCache = rows;
        var reported=0,assessing=0,inRepair=0,resolved=0,major=0;
        rows.forEach(function(r){
            if (r.status==='reported') reported++; else if (r.status==='assessing') assessing++; else if (r.status==='in_repair') inRepair++; else if (r.status==='resolved'||r.status==='closed') resolved++;
            if (r.severity==='major'||r.severity==='total_loss') major++;
        });
        $('#kpiReported').text(reported); $('#kpiAssessing').text(assessing); $('#kpiInRepair').text(inRepair); $('#kpiResolved').text(resolved); $('#kpiMajor').text(major); $('#kpiTotal').text(rows.length);

        var html = '';
        if (!rows.length) html = '<tr><td colspan="9" class="text-center py-4 text-muted">No incidents</td></tr>';
        else rows.forEach(function(r){
            var statusColors={reported:'secondary',assessing:'info',in_repair:'warning',resolved:'success',closed:'dark'};
            var sevColors={minor:'success',moderate:'warning',major:'danger',total_loss:'dark'};
            html += '<tr><td>' + escapeHtml(r.plate_number||'-') + '</td><td>' + escapeHtml(r.driver_name||'-') + '</td><td>' + formatDate(r.incident_date) + '</td>' +
                '<td><span class="badge bg-info">' + escapeHtml(r.incident_type) + '</span></td><td><span class="badge bg-' + (sevColors[r.severity]||'secondary') + '">' + escapeHtml(r.severity) + '</span></td>' +
                '<td>' + escapeHtml(r.location||'-') + '</td><td>₦' + Number(r.damage_cost_estimate||0).toLocaleString() + '</td>' +
                '<td><span class="badge bg-' + (statusColors[r.status]||'secondary') + '">' + escapeHtml(r.status) + '</span></td>' +
                '<td class="text-end"><div class="d-flex gap-1 justify-content-end"><button class="btn btn-sm btn-outline-primary btn-edit-incident" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete-incident" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#incidentTable').html(html);
    },'json');
}

function saveIncident() {
    var p = { id: $('#incident_id').val(), vehicle_id: $('#incident_vehicle_id').val(), driver_id: $('#incident_driver_id').val(), incident_date: $('#incident_date').val(), incident_time: $('#incident_time').val(), location: $('#incident_location').val(), incident_type: $('#incident_type').val(), severity: $('#incident_severity').val(), description: $('#incident_description').val(), police_report_number: $('#incident_police_report_number').val(), police_station: $('#incident_police_station').val(), third_party_details: $('#incident_third_party_details').val(), is_fleet_fault: $('#incident_is_fleet_fault').val(), damage_cost_estimate: $('#incident_damage_cost_estimate').val(), status: $('#incident_status').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.vehicle_id||!p.incident_date) { showToast('Vehicle and date required','danger'); return; }
    $.post('api/incidents.php?action=save', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('incidentModal')).hide(); loadIncidents(); showToast('Incident saved!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function clearIncidentForm() { $('#incidentForm')[0].reset(); $('#incident_id').val(''); $('#incident_is_fleet_fault').val(''); }
function populateIncidentForm(r) {
    clearIncidentForm(); $('#incident_id').val(r.id); $('#incident_vehicle_id').val(r.vehicle_id); $('#incident_driver_id').val(r.driver_id||'');
    $('#incident_date').val(normalizeDate(r.incident_date)); $('#incident_time').val(r.incident_time||''); $('#incident_location').val(r.location||'');
    $('#incident_type').val(r.incident_type); $('#incident_severity').val(r.severity); $('#incident_description').val(r.description||'');
    $('#incident_police_report_number').val(r.police_report_number||''); $('#incident_police_station').val(r.police_station||'');
    $('#incident_third_party_details').val(r.third_party_details||''); $('#incident_is_fleet_fault').val(r.is_fleet_fault!==null?String(r.is_fleet_fault):'');
    $('#incident_damage_cost_estimate').val(r.damage_cost_estimate||''); $('#incident_status').val(r.status);
    new bootstrap.Modal(document.getElementById('incidentModal')).show();
}

function populateSelect(s,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>';});$(s).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();}
