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

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

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

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

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

function loadUnderageLicenseReport(search = '') {
    $('#underageTable').html(`
        <tr>
            <td colspan="8" class="text-center text-muted">Loading license data...</td>
        </tr>
    `);

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

            renderUnderageReport(res.data);
        },
        error: function () {
            showTableError('Server error while loading license data');
        }
    });
}

function renderUnderageReport(data) {
    const drivers = data.drivers || [];
    const kpis = data.kpis || { total_drivers: 0, compliant_drivers: 0, non_compliant_drivers: 0 };

    $('#kpiTotalDrivers').text(kpis.total_drivers);
    $('#kpiCompliant').text(kpis.compliant_drivers);
    $('#kpiNonCompliant').text(kpis.non_compliant_drivers);

    if (!Array.isArray(drivers) || drivers.length === 0) {
        $('#underageTable').html(`
            <tr>
                <td colspan="8" class="text-center text-muted">No drivers with license data found</td>
            </tr>
        `);
        return;
    }

    let html = '';

    drivers.forEach(function (driver) {
        const complianceBadge = driver.compliant ?
            '<span class="badge bg-success">Compliant</span>' :
            '<span class="badge bg-danger">Non-Compliant</span>';

        html += `
            <tr>
                <td>${escapeHtml(driver.driver_id_code || 'N/A')}</td>
                <td>${escapeHtml(driver.full_name || 'Unnamed Driver')}</td>
                <td>${driver.date_of_birth ? escapeHtml(formatDate(driver.date_of_birth)) : 'N/A'}</td>
                <td>${escapeHtml(driver.license_number || 'N/A')}</td>
                <td>${driver.date_of_first_issue ? escapeHtml(formatDate(driver.date_of_first_issue)) : 'N/A'}</td>
                <td>${driver.age_at_first_issue !== null ? driver.age_at_first_issue : 'N/A'}</td>
                <td>${complianceBadge}</td>
                <td>
                    <button type="button" class="btn btn-sm btn-info btn-view-driver" data-id="${escapeHtml(driver.id || '')}">View</button>
                </td>
            </tr>
        `;
    });

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

function formatDate(value) {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
        return 'Invalid date';
    }

    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const year = date.getFullYear();

    return `${year}-${month}-${day}`;
}

function escapeHtml(text) {
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function exportCsvReport() {
    const rows = [];
    $('#underageTable tr').each(function () {
        const columns = $(this).find('td');
        if (columns.length !== 8) {
            return;
        }

        rows.push([
            $(columns[0]).text().trim(),
            $(columns[1]).text().trim(),
            $(columns[2]).text().trim(),
            $(columns[3]).text().trim(),
            $(columns[4]).text().trim(),
            $(columns[5]).text().trim(),
            $(columns[6]).text().trim()
        ]);
    });

    if (!rows.length) {
        return;
    }

    let csv = 'Driver Code,Name,Date of Birth,License Number,First Issue Date,Age at Issue,Compliance Status\n';
    rows.forEach(function (row) {
        csv += row.map(function (value) {
            return '"' + value.replace(/"/g, '""') + '"';
        }).join(',') + '\n';
    });

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'driver_underage_license_report.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

function showTableError(message) {
    $('#underageTable').html(`
        <tr>
            <td colspan="8" 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=' + encodeURIComponent(id);
    }
});