$(function () {
    let _search = '';
    let _offset = 0;
    let _limit = 200;
    let _hasMore = false;
    let _allData = [];

    $('#searchAssignment').on('keyup', function () {
        clearTimeout(window._searchTimer);
        window._searchTimer = setTimeout(function () {
            _search = $('#searchAssignment').val();
            _offset = 0;
            _allData = [];
            loadReport(true);
        }, 350);
    });

    $('#btnRefresh').on('click', function () {
        _offset = 0;
        _allData = [];
        loadReport(true);
    });

    $('#btnExportCsv').on('click', exportCsv);
    $('#btnExportPdf').on('click', exportPdf);

    loadReport(true);

    $('#btnLoadMore').on('click', function () {
        loadReport(false);
    });

    function loadReport(reset) {
        if (reset) {
            $('#assignmentReportTable').html('<tr><td colspan="7" class="text-center text-muted">Loading...</td></tr>');
            $('#btnLoadMore').addClass('d-none');
        }

        const params = {
            action: 'assignment_report',
            search: _search,
            limit: _limit,
            offset: _offset
        };

        $.getJSON('api/assignments.php', params, function (res) {
            if (res.status !== 'success') {
                $('#assignmentReportTable').html('<tr><td colspan="7" class="text-center text-danger">' + escapeHtml(res.message || 'Error loading data') + '</td></tr>');
                return;
            }

            const data = res.data || {};
            const rows = data.assignments || [];
            const kpis = data.kpis || {};

            $('#kpiTotal').text(kpis.total || 0);
            $('#kpiActive').text(kpis.active_count || 0);
            $('#kpiInactive').text(kpis.inactive_count || 0);
            $('#kpiUnique').text((kpis.unique_drivers || 0) + ' / ' + (kpis.unique_vehicles || 0));

            if (reset) {
                _allData = rows;
            } else {
                _allData = _allData.concat(rows);
            }

            if (!rows.length && reset) {
                $('#assignmentReportTable').html('<tr><td colspan="7" class="text-center text-muted">No assignment records found</td></tr>');
                $('#tableInfo').text('0 records');
                return;
            }

            if (reset) {
                $('#assignmentReportTable').empty();
            }

            _hasMore = rows.length >= _limit;
            if (_hasMore) {
                rows.pop();
            }

            $.each(reset ? _allData : rows, function (_, row) {
                $('#assignmentReportTable').append(renderRow(row));
            });

            _offset = _allData.length;
            $('#tableInfo').text(_allData.length + ' record' + (_allData.length !== 1 ? 's' : '') + (data.total > 0 ? ' (total ' + data.total + ')' : ''));

            if (_hasMore) {
                $('#btnLoadMore').removeClass('d-none');
            } else {
                $('#btnLoadMore').addClass('d-none');
            }
        }).fail(function () {
            $('#assignmentReportTable').html('<tr><td colspan="7" class="text-center text-danger">Server error loading data</td></tr>');
        });
    }

    function renderRow(row) {
        const status = row.status || 'unknown';
        const badgeColor = status === 'active' ? 'success' : (status === 'inactive' ? 'secondary' : 'warning');
        const endDate = row.assignment_end ? formatDate(row.assignment_end) : 'Ongoing';
        const duration = row.duration_days ? row.duration_days + ' days' : '-';

        return '<tr>' +
            '<td>' + escapeHtml(row.driver_name || 'Unknown') + (row.driver_code ? ' (' + escapeHtml(row.driver_code) + ')' : '') + '</td>' +
            '<td>' + escapeHtml(row.vehicle_plate || '-') + (row.vehicle_model ? ' / ' + escapeHtml(row.vehicle_model) : '') + '</td>' +
            '<td>' + escapeHtml(row.company_name || '-') + '</td>' +
            '<td>' + formatDate(row.assignment_start) + '</td>' +
            '<td>' + endDate + '</td>' +
            '<td>' + duration + '</td>' +
            '<td><span class="badge bg-' + badgeColor + '">' + escapeHtml(status.charAt(0).toUpperCase() + status.slice(1)) + '</span></td>' +
            '</tr>';
    }

    function exportCsv() {
        const rows = [['Driver', 'Driver Code', 'Vehicle Plate', 'Vehicle Model', 'Company', 'Start Date', 'End Date', 'Duration (Days)', 'Status']];

        $.each(_allData, function (_, row) {
            rows.push([
                row.driver_name || '',
                row.driver_code || '',
                row.vehicle_plate || '',
                row.vehicle_model || '',
                row.company_name || '',
                row.assignment_start || '',
                row.assignment_end || 'Ongoing',
                row.duration_days || '',
                row.status || ''
            ]);
        });

        const csv = rows.map(function (r) {
            return r.map(function (c) { return '"' + String(c).replace(/"/g, '""') + '"'; }).join(',');
        }).join('\n');

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

    function exportPdf() {
        if (!_allData.length) {
            alert('No data to export');
            return;
        }

        const title = 'Driver Assignment History Report';
        const date = new Date().toLocaleDateString();
        const rowsHtml = _allData.map(function (row) {
            const status = row.status || 'unknown';
            const endDate = row.assignment_end ? formatDate(row.assignment_end) : 'Ongoing';
            return '<tr>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + escapeHtml(row.driver_name || '') + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + escapeHtml(row.vehicle_plate || '') + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + escapeHtml(row.company_name || '-') + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + formatDate(row.assignment_start) + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + endDate + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + (row.duration_days || '-') + '</td>' +
                '<td style="padding:6px 8px;border:1px solid #ddd;">' + status.charAt(0).toUpperCase() + status.slice(1) + '</td>' +
                '</tr>';
        }).join('');

        const html = '<div id="pdf-report" style="padding:20px;font-family:Arial,sans-serif;">' +
            '<h2 style="text-align:center;margin-bottom:4px;">' + title + '</h2>' +
            '<p style="text-align:center;color:#666;margin-top:0;">Generated: ' + date + '</p>' +
            '<hr>' +
            '<table style="width:100%;border-collapse:collapse;margin-top:16px;font-size:12px;">' +
            '<thead><tr style="background:#f5f5f5;">' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Driver</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Vehicle</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Company</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Start</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">End</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Days</th>' +
            '<th style="padding:8px;border:1px solid #ddd;text-align:left;">Status</th>' +
            '</tr></thead>' +
            '<tbody>' + rowsHtml + '</tbody>' +
            '</table>' +
            '<p style="margin-top:20px;font-size:11px;color:#999;text-align:center;">Driver Assignment History Report</p>' +
            '</div>';

        if (typeof window.html2pdf === 'function') {
            window.html2pdf().set({
                margin: 0.35,
                filename: 'driver_assignment_report.pdf',
                image: { type: 'jpeg', quality: 0.98 },
                html2canvas: { scale: 2, useCORS: true, backgroundColor: '#ffffff' },
                jsPDF: { unit: 'in', format: 'a4', orientation: 'landscape' }
            }).from(html2pdfElement(html)).save();
        } else {
            const win = window.open('', '_blank');
            win.document.write('<html><head><title>Driver Assignment Report</title></head><body>' + html + '</body></html>');
            win.document.close();
            win.print();
        }
    }

    function html2pdfElement(html) {
        const el = document.createElement('div');
        el.innerHTML = html;
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        setTimeout(function () { document.body.removeChild(el); }, 5000);
        return el;
    }

    function formatDate(value) {
        if (!value) return '-';
        const d = new Date(value);
        if (isNaN(d.getTime())) return value;
        return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
    }

    function escapeHtml(text) {
        return $('<div>').text(text || '').html();
    }
});
