let _allEntries = [];

$(function () {
    loadReport();
    $('#filterStartDate, #filterEndDate, #filterStatus').on('change', loadReport);
    $('#filterSearch').on('input', debounce(loadReport, 300));
    $('#btnRefresh').on('click', loadReport);
    $('#btnExport').on('click', exportCsv);
});

function loadReport() {
    const start = $('#filterStartDate').val();
    const end = $('#filterEndDate').val();
    const status = $('#filterStatus').val();
    const search = $('#filterSearch').val();
    const tbody = $('#reportTableBody');
    tbody.html('<tr><td colspan="11" class="text-center text-muted py-4">Loading report data...</td></tr>');

    $.get('api/fuel.php', {
        action: 'fuel_request_report',
        start_date: start,
        end_date: end,
        approval_status: status,
        search: search
    }, function (res) {
        if (res.status !== 'success') {
            tbody.html('<tr><td colspan="11" class="text-center text-danger py-4">' + esc(res.message || 'Load failed') + '</td></tr>');
            return;
        }
        _allEntries = res.data || [];
        renderKpis(res.kpis || {});
        renderTable(_allEntries);
    }).fail(function (jqXHR) {
        tbody.html('<tr><td colspan="11" class="text-center text-danger py-4">Network error: ' + (jqXHR.responseJSON?.message || jqXHR.statusText) + '</td></tr>');
    });
}

function renderKpis(kpis) {
    $('#kpiTotalCount').text(kpis.total_count || 0);
    $('#kpiTotalLiters').text(_fmtNum(kpis.total_liters));
    $('#kpiTotalAmount').text(_fmtCurr(kpis.total_amount));
    $('#kpiApprovedCount').text(kpis.approved_count || 0);
}

function renderTable(data) {
    const tbody = $('#reportTableBody');
    if (!data.length) {
        tbody.html('<tr><td colspan="11" class="text-center text-muted py-4">No fuel requests found</td></tr>');
        return;
    }
    tbody.html(data.map(function (r) {
        const statusClass = r.approval_status === 'Approved' ? 'text-success' : (r.approval_status === 'Rejected' ? 'text-danger' : 'text-warning');
        return '<tr>' +
            '<td>' + esc(r.voucher_id || '-') + '</td>' +
            '<td>' + esc(r.record_date || '-') + '</td>' +
            '<td>' + esc(r.vehicle_no || '-') + '</td>' +
            '<td>' + esc(r.driver_name || '-') + '</td>' +
            '<td>' + esc(r.fuel_type_name || '-') + '</td>' +
            '<td class="text-end">' + _fmtNum(r.fuel_purchase_liters) + '</td>' +
            '<td class="text-end">' + _fmtCurr(r.naira_per_liter) + '</td>' +
            '<td class="text-end">' + _fmtCurr(r.total_amount) + '</td>' +
            '<td>' + esc(r.filling_station || '-') + '</td>' +
            '<td class="' + statusClass + ' fw-semibold">' + esc(r.approval_status || 'Pending') + '</td>' +
            '<td>' + (r.approval_status === 'Approved' ? esc(r.approved_by_name || '-') : esc(r.created_by_name || '-')) + '</td>' +
            '</tr>';
    }).join(''));
}

function exportCsv() {
    if (!_allEntries.length) { alert('No data to export'); return; }
    var rows = [['Voucher','Date','Vehicle','Driver','Fuel Type','Litres','Rate (NGN/L)','Total (NGN)','Filling Station','Status','Month']];
    _allEntries.forEach(function (r) {
        rows.push([
            r.voucher_id || '', r.record_date || '', r.vehicle_no || '', r.driver_name || '',
            r.fuel_type_name || '', _fmtNum(r.fuel_purchase_liters), _fmtCurr(r.naira_per_liter),
            _fmtCurr(r.total_amount), r.filling_station || '', r.approval_status || 'Pending', r.month_year || ''
        ]);
    });
    var csv = rows.map(function (row) { return row.map(function (c) { return '"' + String(c).replace(/"/g, '""') + '"'; }).join(','); }).join('\n');
    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    var link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'fuel_request_report_' + new Date().toISOString().slice(0, 10) + '.csv';
    link.click();
    URL.revokeObjectURL(link.href);
}

function debounce(fn, ms) {
    var timer;
    return function () { clearTimeout(timer); timer = setTimeout(fn, ms); };
}

function _fmtNum(n) { return (n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function _fmtCurr(n) { return (n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function esc(s) { if (s === null || s === undefined) return ''; var d = document.createElement('div'); d.appendChild(document.createTextNode(String(s))); return d.innerHTML; }
