$(document).ready(function () {
    loadComplianceData();

    $('#btnRefresh').on('click', function () {
        loadComplianceData($('#searchDriver').val());
    });

    let typingTimer;
    $('#searchDriver').on('keyup', function () {
        clearTimeout(typingTimer);
        const search = $(this).val();

        typingTimer = setTimeout(function () {
            loadComplianceData(search);
        }, 350);
    });

    $('#btnExport').on('click', exportReport);
});

function loadComplianceData(search = '') {
    $('#complianceTable').html(`
        <tr>
            <td colspan="6" class="text-center text-muted">Loading compliance data...</td>
        </tr>
    `);

    $.ajax({
        url: 'api/drivers.php',
        method: 'GET',
        dataType: 'json',
        data: { action: 'age_compliance', search: search },
        success: function (res) {
            if (res.status !== 'success') {
                showError(res.message || 'Failed to load compliance data');
                return;
            }

            renderKpis(res.data.kpis || {});
            renderComplianceTable(res.data.drivers || []);
        },
        error: function () {
            showError('Server error while loading compliance data');
        }
    });
}

function renderKpis(kpis) {
    $('#kpiTotalDrivers').text(kpis.total_drivers || 0);
    $('#kpiCompliant').text(kpis.compliant || 0);
    $('#kpiNonCompliant').text(kpis.non_compliant || 0);
    $('#kpiAverageAge').text(kpis.average_age || 0);
}

function renderComplianceTable(drivers) {
    if (!drivers.length) {
        $('#complianceTable').html(`
            <tr>
                <td colspan="6" class="text-center text-muted">No drivers found</td>
            </tr>
        `);
        return;
    }

    let html = '';

    $.each(drivers, function (_, driver) {
        const age = driver.age !== null ? driver.age : 'N/A';
        const complianceStatus = driver.compliant ? 
            '<span class="badge bg-success">Compliant</span>' : 
            '<span class="badge bg-danger">Non-Compliant</span>';
        const dob = driver.date_of_birth ? formatDate(driver.date_of_birth) : 'N/A';

        html += `
            <tr>
                <td>${escapeHtml(driver.driver_id_code || 'N/A')}</td>
                <td>${escapeHtml(driver.full_name || 'Unnamed Driver')}</td>
                <td>${dob}</td>
                <td>${age}</td>
                <td>${complianceStatus}</td>
                <td>
                    <button type="button" class="btn btn-sm btn-info btn-view-driver" data-id="${driver.id}">
                        View Profile
                    </button>
                </td>
            </tr>
        `;
    });

    $('#complianceTable').html(html);
}

function exportReport() {
    // Simple CSV export
    const table = document.getElementById('complianceTable');
    let csv = 'Driver Code,Name,Date of Birth,Age,Compliance Status\n';

    for (let i = 0; i < table.rows.length; i++) {
        const row = table.rows[i];
        const cells = row.cells;
        if (cells.length === 6) { // Skip loading/no data rows
            csv += `"${cells[0].textContent}","${cells[1].textContent}","${cells[2].textContent}","${cells[3].textContent}","${cells[4].textContent.replace(/<[^>]*>/g, '')}"\n`;
        }
    }

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'driver_age_compliance_report.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}

function showError(message) {
    $('#complianceTable').html(`
        <tr>
            <td colspan="6" class="text-center text-danger">${escapeHtml(message)}</td>
        </tr>
    `);
}

$(document).on('click', '.btn-view-driver', function () {
    const id = $(this).data('id');
    if (id) {
        window.location.href = 'driver_profile.php?id=' + id;
    }
});