let _allData = [];
let _filters = {};

$(function () {
    populateYearSelect();
    loadVehicles();
    $('#filterYear').on('change', function () {
        const y = $(this).val();
        if (y) {
            $('#filterStartDate').val(y + '-01-01');
            $('#filterEndDate').val(y + '-12-31');
        }
        loadReport();
    });
    $('#filterVehicle, #filterStartDate, #filterEndDate').on('change', loadReport);
    $('#btnExportCsv').on('click', function () { exportReport('csv'); });
    $('#btnExportPdf').on('click', function () { exportReport('pdf'); });
    $('#btnExportExcel').on('click', function () { exportReport('xlsx'); });
    loadReport();

    $(document).on('click', '.tco-detail-btn', function () {
        const vid = $(this).data('vehicle-id');
        if (vid) showDetail(vid);
    });
});

function populateYearSelect() {
    const sel = $('#filterYear');
    const y = new Date().getFullYear();
    for (let i = y - 5; i <= y + 1; i++) {
        sel.append('<option value="' + i + '"' + (i === y ? ' selected' : '') + '>' + i + '</option>');
    }
    $('#filterStartDate').val(y + '-01-01');
    $('#filterEndDate').val(y + '-12-31');
}

function loadVehicles() {
    $.get('api/tco_report.php', { action: 'vehicles' }, function (res) {
        if (res.status !== 'success') return;
        const sel = $('#filterVehicle');
        res.data.forEach(function (v) {
            sel.append('<option value="' + v.id + '">' + esc(v.plate_number) + '</option>');
        });
    });
}

function loadReport() {
    _filters = {
        year: $('#filterYear').val(),
        vehicle_id: $('#filterVehicle').val(),
        start_date: $('#filterStartDate').val(),
        end_date: $('#filterEndDate').val(),
    };
    const tbody = $('#tcoTableBody');
    tbody.html('<tr><td colspan="10" class="text-center text-muted py-4">Loading TCO data...</td></tr>');

    $.get('api/tco_report.php', $.extend({}, _filters, { action: 'summary' }), function (res) {
        if (res.status !== 'success') {
            tbody.html('<tr><td colspan="10" class="text-center text-danger py-4">' + esc(res.message || 'Load failed') + '</td></tr>');
            return;
        }
        _allData = res.data || [];
        renderKpis(res.kpis || {});
        renderTable(_allData);
    }).fail(function (jqXHR) {
        tbody.html('<tr><td colspan="10" class="text-center text-danger py-4">Network error: ' + (jqXHR.responseJSON?.message || jqXHR.statusText) + '</td></tr>');
    });
}

function renderKpis(kpis) {
    $('#kpiFuel').text('₦' + _fmt(kpis.total_fuel));
    $('#kpiMaint').text('₦' + _fmt(kpis.total_maint));
    $('#kpiIns').text('₦' + _fmt(kpis.total_ins));
    $('#kpiExpense').text('₦' + _fmt(kpis.total_expense));
    $('#kpiGrandTotal').text('₦' + _fmt(kpis.grand_total));
    $('#kpiVehicleCount').text(kpis.vehicle_count + ' vehicles');

    const total = kpis.grand_total || 1;
    const pw = 25;
    $('#tcoBarFuel').css({ width: pw + '%', height: Math.max(4, (kpis.total_fuel / total) * 100) + 'px', background: '#f59e0b' });
    $('#tcoBarMaint').css({ left: pw + '%', width: pw + '%', height: Math.max(4, (kpis.total_maint / total) * 100) + 'px', background: '#ef4444' });
    $('#tcoBarIns').css({ left: (pw * 2) + '%', width: pw + '%', height: Math.max(4, (kpis.total_ins / total) * 100) + 'px', background: '#3b82f6' });
    $('#tcoBarExp').css({ width: pw + '%', height: Math.max(4, (kpis.total_expense / total) * 100) + 'px', background: '#8b5cf6' });
}

function renderTable(data) {
    const tbody = $('#tcoTableBody');
    if (!data.length) {
        tbody.html('<tr><td colspan="10" class="text-center text-muted py-4">No TCO data found for the selected period</td></tr>');
        return;
    }
    tbody.html(data.map(function (r, i) {
        return '<tr>' +
            '<td>' + (i + 1) + '</td>' +
            '<td><strong>' + esc(r.plate_number) + '</strong></td>' +
            '<td>' + esc(r.make_model) + '</td>' +
            '<td>' + esc(r.vehicle_type) + '</td>' +
            '<td class="text-end text-warning-emphasis">₦' + _fmt(r.fuel_cost) + '</td>' +
            '<td class="text-end text-danger-emphasis">₦' + _fmt(r.maint_cost) + '</td>' +
            '<td class="text-end text-primary-emphasis">₦' + _fmt(r.ins_cost) + '</td>' +
            '<td class="text-end text-purple-emphasis">₦' + _fmt(r.expense_cost) + '</td>' +
            '<td class="text-end fw-bold">₦' + _fmt(r.tco) + '</td>' +
            '<td><button class="btn btn-sm btn-outline-secondary tco-detail-btn" data-vehicle-id="' + r.vehicle_id + '"><i class="bi bi-eye"></i></button></td>' +
            '</tr>';
    }).join(''));
}

function showDetail(vehicleId) {
    const modal = new bootstrap.Modal(document.getElementById('tcoDetailModal'));
    $('#detailModalBody').html('<div class="text-center text-muted py-5">Loading details...</div>');
    modal.show();

    $.get('api/tco_report.php', $.extend({}, _filters, { action: 'detail', vehicle_id: vehicleId }), function (res) {
        if (res.status !== 'success') {
            $('#detailModalBody').html('<div class="text-danger">' + esc(res.message) + '</div>');
            return;
        }
        const v = res.vehicle;
        $('#detailModalTitle').text(esc(v.plate_number) + ' — ' + esc(v.vehicle_model) + ' (' + v.model_year + ')');
        var html = '<div class="row g-3">';

        html += '<div class="col-md-6"><h6 class="fw-semibold border-bottom pb-2"><i class="bi bi-fuel-pump text-warning"></i> Fuel Entries</h6>';
        if (!res.fuel_entries.length) { html += '<p class="text-muted small">None</p>'; }
        else {
            html += '<div class="table-responsive"><table class="table table-sm"><thead><tr><th>Date</th><th>Litres</th><th>Rate</th><th>Total</th><th>Station</th></tr></thead><tbody>';
            var tf = 0;
            res.fuel_entries.forEach(function (f) { tf += parseFloat(f.total_amount) || 0;
                html += '<tr><td>' + esc(f.record_date) + '</td><td>' + _fmt(f.fuel_purchase_liters) + '</td><td>' + _fmt(f.naira_per_liter) + '</td><td>₦' + _fmt(f.total_amount) + '</td><td>' + esc(f.filling_station) + '</td></tr>'; });
            html += '</tbody><tfoot><tr class="fw-bold"><td>Subtotal</td><td></td><td></td><td>₦' + _fmt(tf) + '</td><td></td></tr></tfoot></table></div>';
        }
        html += '</div>';

        html += '<div class="col-md-6"><h6 class="fw-semibold border-bottom pb-2"><i class="bi bi-tools text-danger"></i> Maintenance</h6>';
        if (!res.maint_entries.length) { html += '<p class="text-muted small">None</p>'; }
        else {
            html += '<div class="table-responsive"><table class="table table-sm"><thead><tr><th>Date</th><th>Title</th><th>Cost</th><th>Workshop</th></tr></thead><tbody>';
            var tm = 0;
            res.maint_entries.forEach(function (m) { tm += parseFloat(m.cost) || 0;
                html += '<tr><td>' + esc(m.complaint_date) + '</td><td>' + esc(m.complaint_title) + '</td><td>₦' + _fmt(m.cost) + '</td><td>' + esc(m.workshop) + '</td></tr>'; });
            html += '</tbody><tfoot><tr class="fw-bold"><td>Subtotal</td><td></td><td>₦' + _fmt(tm) + '</td><td></td></tr></tfoot></table></div>';
        }
        html += '</div>';

        html += '<div class="col-md-6"><h6 class="fw-semibold border-bottom pb-2"><i class="bi bi-shield-check text-primary"></i> Insurance</h6>';
        if (!res.ins_entries.length) { html += '<p class="text-muted small">None</p>'; }
        else {
            html += '<div class="table-responsive"><table class="table table-sm"><thead><tr><th>Policy</th><th>Insurer</th><th>Type</th><th>Start</th><th>End</th><th>Premium</th></tr></thead><tbody>';
            var ti = 0;
            res.ins_entries.forEach(function (p) { ti += parseFloat(p.premium_amount) || 0;
                html += '<tr><td>' + esc(p.policy_number) + '</td><td>' + esc(p.insurer_name) + '</td><td>' + esc(p.policy_type) + '</td><td>' + esc(p.coverage_start) + '</td><td>' + esc(p.coverage_end) + '</td><td>₦' + _fmt(p.premium_amount) + '</td></tr>'; });
            html += '</tbody><tfoot><tr class="fw-bold"><td colspan="5">Subtotal</td><td>₦' + _fmt(ti) + '</td></tr></tfoot></table></div>';
        }
        html += '</div>';

        html += '<div class="col-md-6"><h6 class="fw-semibold border-bottom pb-2"><i class="bi bi-receipt text-purple"></i> Other Expenses</h6>';
        if (!res.expense_entries.length) { html += '<p class="text-muted small">None</p>'; }
        else {
            html += '<div class="table-responsive"><table class="table table-sm"><thead><tr><th>Date</th><th>Description</th><th>Amount</th></tr></thead><tbody>';
            var te = 0;
            res.expense_entries.forEach(function (e) { te += parseFloat(e.amount) || 0;
                html += '<tr><td>' + esc(e.expense_date) + '</td><td>' + esc(e.description) + '</td><td>₦' + _fmt(e.amount) + '</td></tr>'; });
            html += '</tbody><tfoot><tr class="fw-bold"><td>Subtotal</td><td></td><td>₦' + _fmt(te) + '</td></tr></tfoot></table></div>';
        }
        html += '</div>';

        html += '</div>';
        $('#detailModalBody').html(html);
    }).fail(function () {
        $('#detailModalBody').html('<div class="text-danger">Network error loading details</div>');
    });
}

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

    if (format === 'csv') {
        var rows = [['Plate Number', 'Make/Model', 'Type', 'Fuel Cost (NGN)', 'Maintenance (NGN)', 'Insurance (NGN)', 'Expenses (NGN)', 'TCO (NGN)']];
        _allData.forEach(function (r) {
            rows.push([r.plate_number, r.make_model, r.vehicle_type, r.fuel_cost, r.maint_cost, r.ins_cost, r.expense_cost, r.tco]);
        });
        var csv = rows.map(function (row) { return row.map(function (c) { return '"' + String(c).replace(/"/g, '""') + '"'; }).join(','); }).join('\n');
        var blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'tco_report_' + new Date().toISOString().slice(0, 10) + '.csv';
        link.click();
        URL.revokeObjectURL(link.href);
    } else if (format === 'pdf' || format === 'xlsx') {
        var params = $.extend({}, _filters, { format: format });
        var qs = Object.keys(params).map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]); }).join('&');
        window.open('api/data_export.php?type=tco&' + qs, '_blank');
    }
}

function _fmt(n) { return (parseFloat(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; }
