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

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

    $('#maxAgeLimit').on('change', function () {
        loadDriverOverageReport($('#searchDriver').val());
    });

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

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

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

function loadDriverOverageReport(search = '') {
    const maxAgeLimit = parseInt($('#maxAgeLimit').val(), 10) || 60;
    $('#maxAgeLabel').text(maxAgeLimit);

    $('#overageTable').html(`
        <tr>
            <td colspan="6" class="text-center text-muted">Loading driver data...</td>
        </tr>
    `);

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

            renderOverageReport(res.data || [], maxAgeLimit);
        },
        error: function () {
            showTableError('Server error while loading driver data');
        }
    });
}

function renderOverageReport(drivers, maxAgeLimit) {
    if (!Array.isArray(drivers) || drivers.length === 0) {
        $('#overageTable').html(`
            <tr>
                <td colspan="6" class="text-center text-muted">No drivers found</td>
            </tr>
        `);
        updateKpis(0, 0);
        return;
    }

    let withinLimit = 0;
    let overLimit = 0;
    let html = '';

    drivers.forEach(function (driver) {
        const age = calculateAge(driver.date_of_birth);
        const isOver = age !== null && age > maxAgeLimit;

        if (age !== null) {
            if (isOver) {
                overLimit++;
            } else {
                withinLimit++;
            }
        }

        html += `
            <tr>
                <td>${escapeHtml(driver.driver_id_code || 'N/A')}</td>
                <td>${escapeHtml(driver.full_name || 'Unnamed Driver')}</td>
                <td>${driver.date_of_birth ? formatDate(driver.date_of_birth) : 'N/A'}</td>
                <td>${age !== null ? age : 'N/A'}</td>
                <td>${age === null ? '<span class="badge bg-secondary">Unknown</span>' : isOver ? '<span class="badge bg-danger">Above Limit</span>' : '<span class="badge bg-success">Within Limit</span>'}</td>
                <td>
                    <button type="button" class="btn btn-sm btn-info btn-view-driver" data-id="${driver.id}">View</button>
                </td>
            </tr>
        `;
    });

    $('#overageTable').html(html);
    updateKpis(withinLimit, overLimit);
}

function updateKpis(withinLimit, overLimit) {
    $('#kpiWithinLimit').text(withinLimit);
    $('#kpiOverLimit').text(overLimit);
}

function calculateAge(dateString) {
    if (!dateString) {
        return null;
    }

    const birthDate = new Date(dateString);
    if (Number.isNaN(birthDate.getTime())) {
        return null;
    }

    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    const dayDiff = today.getDate() - birthDate.getDate();

    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
        age -= 1;
    }

    return age;
}

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 = [];
    $('#overageTable tr').each(function () {
        const columns = $(this).find('td');
        if (columns.length !== 6) {
            return;
        }

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

    if (!rows.length) {
        return;
    }

    let csv = 'Driver Code,Name,Date of Birth,Current Age,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_overage_report.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

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