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

let _allRequisitions = [];

const _fmtCurr = function (v) {
    const n = Number(v || 0);
    const locale = n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    return Number.isFinite(n) && n > 0 ? '\u20A6' + locale : '\u20A60.00';
};

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

    $.get('api/maintenance.php', {
        action: 'requisition_report',
        start_date: start,
        end_date: end,
        status: status
    }, function (res) {
        if (res.status !== 'success') {
            tbody.html('<tr><td colspan="7" class="text-center text-danger py-4">' + esc(res.message || 'Load failed') + '</td></tr>');
            return;
        }
        _allRequisitions = res.data || [];
        renderKpis(res.kpis || {});
        renderTable(_allRequisitions);
    });
}

function renderKpis(kpis) {
    $('#kpiTotalCount').text(kpis.total_count || 0);
    $('#kpiTotalValue').text(_fmtCurr(kpis.total_value));
    $('#kpiPendingValue').text(_fmtCurr(kpis.pending_value));
    $('#kpiPaidValue').text(_fmtCurr(kpis.paid_value));
}

function renderTable(data) {
    const tbody = $('#requisitionTableBody');
    if (!data.length) {
        tbody.html('<tr><td colspan="7" class="text-center text-muted py-4">No requisitions found</td></tr>');
        return;
    }
    tbody.html(data.map(function (r) {
        const status = r.requisition_status || 'Pending';
        const statusBadge = status === 'Paid'
            ? '<span class="badge bg-success">Paid</span>'
            : status === 'Approved'
                ? '<span class="badge bg-primary">Approved</span>'
                : status === 'Raised'
                    ? '<span class="badge bg-warning text-dark">Raised</span>'
                    : '<span class="badge bg-secondary">' + esc(status) + '</span>';
        return '<tr>' +
            '<td>' + esc(r.work_order_number || '-') + '</td>' +
            '<td>' + esc(r.created_at ? r.created_at.slice(0, 10) : '-') + '</td>' +
            '<td>' + esc(r.plate_number || '-') + '</td>' +
            '<td>' + esc(r.workshop || '-') + '</td>' +
            '<td class="text-end fw-semibold">' + _fmtCurr(r.approved_amount) + '</td>' +
            '<td>' + statusBadge + '</td>' +
            '<td><a href="maintenance.php" class="btn btn-sm btn-outline-primary">View Job</a></td>' +
            '</tr>';
    }).join(''));
}

function exportCsv() {
    if (!_allRequisitions.length) return;
    const rows = [['Work Order', 'Date', 'Vehicle', 'Workshop', 'Approved Amount', 'Status']];
    _allRequisitions.forEach(function (r) {
        rows.push([
            r.work_order_number || '',
            r.created_at ? r.created_at.slice(0, 10) : '',
            r.plate_number || '',
            r.workshop || '',
            Number(r.approved_amount || 0).toFixed(2),
            r.requisition_status || ''
        ]);
    });
    const csv = rows.map(function (r) { return r.map(csvEsc).join(','); }).join('\n');
    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'requisition_report_' + new Date().toISOString().split('T')[0] + '.csv';
    a.click();
    URL.revokeObjectURL(a.href);
}

function csvEsc(v) {
    const s = String(v == null ? '' : v);
    return /[,"\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}

function esc(text) {
    const d = document.createElement('div');
    d.textContent = text == null ? '' : String(text);
    return d.innerHTML;
}
