let _policyCache = [];

$(function () {
    loadPolicies(); loadPolicyVehicles(); loadClaimPolicies(); loadInsurers();
    $('#policyVehicleFilter, #policyStatusFilter, #policyExpiringFilter, #policyExpiredFilter').on('change', loadPolicies);
    $('#btnRefreshPolicies').on('click', loadPolicies);
    $('#btnAddPolicy').on('click', function () { clearInsuranceForm(); new bootstrap.Modal(document.getElementById('insuranceModal')).show(); });
    $('#saveInsurance').on('click', savePolicy);
    $(document).on('click', '.btn-edit-policy', function () { const r = _policyCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populatePolicyForm(r); });
    $(document).on('click', '.btn-delete-policy', function () { if (!confirm('Delete this policy?')) return; $.post('api/insurance.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { showToast('Deleted','success'); loadPolicies(); } else showToast(r.message,'danger'); }, 'json'); });
    $('#btnAddClaim').on('click', function () { clearClaimForm(); new bootstrap.Modal(document.getElementById('claimModal')).show(); });
    $('#saveClaim').on('click', saveClaim);
    $('#claimPolicyFilter, #claimStatusFilter').on('change', loadClaims);
    $(document).on('click', '.btn-edit-claim', function () { const r = _claimCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populateClaimForm(r); });
    $(document).on('click', '.btn-delete-claim', function () { if (!confirm('Delete claim?')) return; $.post('api/insurance.php?action=delete_claim', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { showToast('Deleted','success'); loadClaims(); } else showToast(r.message,'danger'); }, 'json'); });
    $('#insuranceTabs a').on('shown.bs.tab', function (e) { if ($(e.target).text().trim() === 'Claims') loadClaims(); });
    $('#btnExportInsuranceCsv').on('click', function () { window.location.href = 'api/data_export.php?type=insurance&format=csv'; });
    $('#btnExportInsuranceXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=insurance&format=xlsx'; });
    $('#btnExportInsurancePdf').on('click', function () { window.location.href = 'api/data_export.php?type=insurance&format=pdf'; });
    $('#btnExportClaimsCsv').on('click', function () { window.location.href = 'api/data_export.php?type=insurance_claims&format=csv'; });
    $('#btnExportClaimsXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=insurance_claims&format=xlsx'; });
    $('#btnExportClaimsPdf').on('click', function () { window.location.href = 'api/data_export.php?type=insurance_claims&format=pdf'; });
});

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

function loadClaimPolicies() {
    $.get('api/insurance.php', { action: 'list' }, function (r) {
        if (r.status==='success') {
            const opts = (r.data||[]).map(function (p) { return { id: p.id, label: p.policy_number + ' - ' + (p.plate_number||'') }; });
            populateSelect('#claim_policy_id', opts, 'Select policy');
            populateSelect('#claimPolicyFilter', opts, 'All policies');
        }
    }, 'json');
}

function loadInsurers() {
    $.get('api/insurance.php', { action: 'insurers' }, function (r) {
        if (r.status==='success') {
            populateSelect('#insurance_insurer_id', r.data, 'Select insurer');
        }
    }, 'json');
}

function loadPolicies() {
    const params = { action: 'list', vehicle_id: $('#policyVehicleFilter').val(), status: $('#policyStatusFilter').val() };
    var expiring = $('#policyExpiringFilter').val(), expired = $('#policyExpiredFilter').val();
    if (expiring) params.expiring_soon = 1;
    if (expired) params.expired = 1;

    $.get('api/insurance.php', params, function (res) {
        if (res.status !== 'success') return;
        const rows = res.data || []; _policyCache = rows;
        let active=0, expiringSoon=0, expiredCount=0;
        rows.forEach(function (r) {
            if (r.is_active == 1) active++;
            if (r.days_remaining !== null && r.days_remaining >= 0 && r.days_remaining <= 30) expiringSoon++;
            if (r.days_remaining !== null && r.days_remaining < 0) expiredCount++;
        });
        $('#kpiActivePolicies').text(active);
        $('#kpiExpiringPolicies').text(expiringSoon);
        $('#kpiExpiredPolicies').text(expiredCount);
        $('#kpiTotalPolicies').text(rows.length);

        let html = '';
        if (!rows.length) html = '<tr><td colspan="10" class="text-center py-4 text-muted">No policies</td></tr>';
        else rows.forEach(function (r) {
            const days = r.days_remaining !== null ? (r.days_remaining < 0 ? '<span class="text-danger fw-semibold">' + Math.abs(r.days_remaining) + 'd overdue</span>' : r.days_remaining + 'd') : '-';
            const act = r.is_active == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>';
            const cov = formatDate(r.coverage_start) + ' — ' + formatDate(r.coverage_end);
            html += '<tr><td>' + escapeHtml(r.plate_number||'-') + '</td><td>' + escapeHtml(r.policy_number) + '</td><td>' + escapeHtml(r.insurer_name) + '</td><td>' + escapeHtml(r.policy_type||'-') + '</td><td class="small">' + cov + '</td><td class="fw-semibold">' + days + '</td><td>₦' + Number(r.premium_amount||0).toLocaleString() + '</td><td>' + (r.claim_count||0) + '</td><td>' + act + '</td>' +
                '<td class="text-end"><div class="d-flex gap-1 justify-content-end"><button class="btn btn-sm btn-outline-primary btn-edit-policy" title="Edit" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete-policy" title="Delete" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#policyTable').html(html);
    }, 'json');
}

function savePolicy() {
    const p = { id: $('#insurance_id').val(), vehicle_id: $('#insurance_vehicle_id').val(), policy_number: $('#insurance_policy_number').val(), insurer_id: $('#insurance_insurer_id').val(), policy_type: $('#insurance_policy_type').val(), coverage_start: $('#insurance_coverage_start').val(), coverage_end: $('#insurance_coverage_end').val(), premium_amount: $('#insurance_premium_amount').val(), is_active: $('#insurance_is_active').val(), notes: $('#insurance_notes').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.vehicle_id||!p.policy_number||!p.insurer_id||!p.coverage_start||!p.coverage_end) { showToast('Required fields missing','danger'); return; }
    $.post('api/insurance.php?action=save', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('insuranceModal')).hide();
        loadPolicies(); loadClaimPolicies(); showToast('Policy saved!','success');
    }, 'json').fail(function () { showToast('Server error','danger'); });
}

function clearInsuranceForm() { $('#insuranceForm')[0].reset(); $('#insurance_id').val(''); $('#insurance_insurer_id').val(''); }
function populatePolicyForm(r) {
    clearInsuranceForm(); $('#insurance_id').val(r.id); $('#insurance_vehicle_id').val(r.vehicle_id); $('#insurance_policy_number').val(r.policy_number);
    $('#insurance_insurer_id').val(r.insurer_id); $('#insurance_policy_type').val(r.policy_type); $('#insurance_coverage_start').val(normalizeDate(r.coverage_start));
    $('#insurance_coverage_end').val(normalizeDate(r.coverage_end)); $('#insurance_premium_amount').val(r.premium_amount||''); $('#insurance_is_active').val(r.is_active); $('#insurance_notes').val(r.notes||'');
    // If insurer_id is empty but insurer_name exists, try to set by name
    if (!r.insurer_id && r.insurer_name) {
        var found = false;
        $('#insurance_insurer_id option').each(function() {
            if ($(this).text() === r.insurer_name) { $('#insurance_insurer_id').val($(this).val()); found = true; return false; }
        });
        if (!found) $('#insurance_insurer_id').append(new Option(r.insurer_name, '', true, true));
    }
    new bootstrap.Modal(document.getElementById('insuranceModal')).show();
}

let _claimCache=[];
function loadClaims() {
    $.get('api/insurance.php', { action: 'claims', policy_id: $('#claimPolicyFilter').val(), status: $('#claimStatusFilter').val() }, function (res) {
        if (res.status!=='success') return;
        const rows = res.data||[]; _claimCache=rows;
        let html='';
        if (!rows.length) html='<tr><td colspan="9" class="text-center py-4 text-muted">No claims</td></tr>';
        else rows.forEach(function (r) {
            const badges={filed:'secondary',assessed:'info',approved:'primary',settled:'success',rejected:'danger'};
            html += '<tr><td>' + escapeHtml(r.plate_number||'-') + '</td><td>' + escapeHtml(r.policy_number||'-') + '</td><td>' + escapeHtml(r.claim_number||'-') + '</td><td>' + formatDate(r.incident_date) + '</td>' +
                '<td>₦' + Number(r.claim_amount||0).toLocaleString() + '</td><td>₦' + Number(r.settlement_amount||0).toLocaleString() + '</td><td>' + formatDate(r.payment_date) + '</td>' +
                '<td><span class="badge bg-' + (badges[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-claim" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete-claim" data-id="' + r.id + '"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#claimTable').html(html);
    },'json');
}

function saveClaim() {
    const p = { id: $('#claim_id').val(), policy_id: $('#claim_policy_id').val(), claim_number: $('#claim_number').val(), incident_date: $('#claim_incident_date').val(), claim_amount: $('#claim_amount').val(), settlement_amount: $('#claim_settlement_amount').val(), payment_date: $('#claim_payment_date').val(), status: $('#claim_status').val(), description: $('#claim_description').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.policy_id) { showToast('Policy required','danger'); return; }
    $.post('api/insurance.php?action=save_claim', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('claimModal')).hide();
        loadClaims(); showToast('Claim saved!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function clearClaimForm() { $('#claimForm')[0].reset(); $('#claim_id').val(''); }
function populateClaimForm(r) { clearClaimForm(); $('#claim_id').val(r.id); $('#claim_policy_id').val(r.policy_id); $('#claim_number').val(r.claim_number||''); $('#claim_incident_date').val(normalizeDate(r.incident_date)); $('#claim_amount').val(r.claim_amount||''); $('#claim_settlement_amount').val(r.settlement_amount||''); $('#claim_payment_date').val(normalizeDate(r.payment_date)); $('#claim_status').val(r.status); $('#claim_description').val(r.description||''); new bootstrap.Modal(document.getElementById('claimModal')).show(); }

function populateSelect(sel, rows, p) { let h = '<option value="">' + escapeHtml(p) + '</option>'; (rows||[]).forEach(function (r) { h += '<option value="' + escapeHtml(r.id) + '">' + escapeHtml(r.label||r.name||r.policy_number||'-') + '</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(); }
