let _expenseCache = [];

$(function () {
    loadExpenses(); loadExpenseVehicles(); loadExpenseCategories();
    $('#expVehicleFilter, #expCategoryFilter, #expDateFrom, #expDateTo').on('change', loadExpenses);
    $('#expSearch').on('input', debounce(loadExpenses, 300));
    $('#btnRefreshExpenses').on('click', loadExpenses);
    $('#btnAddExpense').on('click', function () { clearExpenseForm(); new bootstrap.Modal(document.getElementById('expenseModal')).show(); });
    $('#saveExpense').on('click', saveExpense);
    $(document).on('click', '.btn-edit-expense', function () { var r = _expenseCache.find(x => String(x.id) === String($(this).data('id'))); if (r) populateExpenseForm(r); });
    $(document).on('click', '.btn-delete-expense', function () { if (!confirm('Delete expense?')) return; $.post('api/expenses.php?action=delete', { id: $(this).data('id'), csrf_token: window.CSRF_TOKEN }, function (r) { if (r.status==='success') { loadExpenses(); showToast('Deleted','success'); } else showToast(r.message,'danger'); }, 'json'); });
    $('#btnExportExpensesCsv').on('click', function () { window.location.href = 'api/data_export.php?type=expenses&format=csv'; });
    $('#btnExportExpensesXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=expenses&format=xlsx'; });
    $('#btnExportExpensesPdf').on('click', function () { window.location.href = 'api/data_export.php?type=expenses&format=pdf'; });
});

function loadExpenseVehicles() {
    $.get('api/compliance.php', { action: 'vehicles' }, function (r) {
        if (r.status==='success') { populateSelect('#expVehicleFilter', r.data, 'All'); populateSelect('#expense_vehicle_id', r.data, 'Select vehicle'); }
    },'json');
}
function loadExpenseCategories() {
    $.get('api/expenses.php', { action: 'categories' }, function (r) {
        if (r.status==='success') { populateSelect('#expCategoryFilter', r.data, 'All'); populateSelect('#expense_category_id', r.data, 'Select category'); }
    },'json');
    $.get('api/drivers.php', { action: 'list' }, function (r) {
        if (r.status==='success') { var d = (r.data||[]).map(function(x){return{id:x.id,label:x.full_name||x.name};}); populateSelect('#expense_driver_id', d, 'Select driver'); }
    },'json');
}

function loadExpenses() {
    $.get('api/expenses.php', {
        action: 'list', vehicle_id: $('#expVehicleFilter').val(), category_id: $('#expCategoryFilter').val(),
        date_from: $('#expDateFrom').val(), date_to: $('#expDateTo').val(), search: $('#expSearch').val()
    }, function (res) {
        if (res.status!=='success') return;
        var rows = res.data||[]; _expenseCache = rows;
        var total = 0; rows.forEach(function(r){total+=Number(r.amount||0);});

        $.get('api/expenses.php', { action: 'summary', vehicle_id: $('#expVehicleFilter').val() }, function (sres) {
            if (sres.status==='success') {
                var sd = sres.data;
                var sh = '';
                (sd.by_category||[]).forEach(function(c){
                    sh += '<div class="col-6 col-md-3"><div class="card kpi-card shadow-sm border-0 h-100"><div class="card-body"><div class="kpi-label">'+escapeHtml(c.name||'Uncategorized')+'</div><div class="kpi-value small-value">₦'+Number(c.total).toLocaleString()+'</div><div class="text-muted small">'+c.count+' entries</div></div></div></div>';
                });
                if (!sh) sh = '<div class="col-12"><p class="text-muted text-center">No expense data</p></div>';
                $('#expenseSummary').html(sh);
            }
        },'json');

        var html = '';
        if (!rows.length) html = '<tr><td colspan="7" class="text-center py-4 text-muted">No expenses</td></tr>';
        else rows.forEach(function(r){
            html += '<tr><td>'+formatDate(r.expense_date)+'</td><td class="fw-semibold">'+escapeHtml(r.plate_number||'-')+'</td><td>'+escapeHtml(r.category_name||'-')+'</td>' +
                '<td>'+escapeHtml(r.description||'-')+'</td><td class="fw-semibold">₦'+Number(r.amount).toLocaleString()+'</td><td>'+escapeHtml(r.driver_name||'-')+'</td>' +
                '<td class="text-end"><div class="d-flex gap-1 justify-content-end"><button class="btn btn-sm btn-outline-primary btn-edit-expense" data-id="'+r.id+'"><i class="bi bi-pencil"></i></button><button class="btn btn-sm btn-outline-danger btn-delete-expense" data-id="'+r.id+'"><i class="bi bi-trash3"></i></button></div></td></tr>';
        });
        $('#expenseTable').html(html);
    },'json');
}

function saveExpense() {
    var p = { id: $('#expense_id').val(), vehicle_id: $('#expense_vehicle_id').val(), category_id: $('#expense_category_id').val(), expense_date: $('#expense_date').val(), amount: $('#expense_amount').val(), description: $('#expense_description').val(), driver_id: $('#expense_driver_id').val(), receipt_url: $('#expense_receipt_url').val(), notes: $('#expense_notes').val(), csrf_token: window.CSRF_TOKEN };
    if (!p.vehicle_id||!p.amount||p.amount<=0) { showToast('Vehicle and amount required','danger'); return; }
    $.post('api/expenses.php?action=save', p, function (r) {
        if (r.status!=='success') { showToast(r.message,'danger'); return; }
        bootstrap.Modal.getInstance(document.getElementById('expenseModal')).hide(); loadExpenses(); showToast('Expense saved!','success');
    },'json').fail(function(){showToast('Server error','danger');});
}

function clearExpenseForm() { $('#expenseForm')[0].reset(); $('#expense_id').val(''); $('#expense_date').val(new Date().toISOString().slice(0,10)); }
function populateExpenseForm(r) {
    clearExpenseForm(); $('#expense_id').val(r.id); $('#expense_vehicle_id').val(r.vehicle_id); $('#expense_category_id').val(r.category_id||'');
    $('#expense_date').val(normalizeDate(r.expense_date)); $('#expense_amount').val(r.amount||''); $('#expense_description').val(r.description||'');
    $('#expense_driver_id').val(r.driver_id||''); $('#expense_receipt_url').val(r.receipt_url||''); $('#expense_notes').val(r.notes||'');
    new bootstrap.Modal(document.getElementById('expenseModal')).show();
}

function populateSelect(s,rows,p){var h='<option value="">'+escapeHtml(p)+'</option>';(rows||[]).forEach(function(r){h+='<option value="'+escapeHtml(r.id)+'">'+escapeHtml(r.label||r.name||'-')+'</option>';});$(s).html(h);}
function formatDate(d){if(!d)return'-';var dt=new Date(d);return Number.isNaN(dt.getTime())?d:dt.toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'});}
function normalizeDate(d){return d?String(d).slice(0,10):'';}
function showToast(m,t){var e=document.createElement('div');e.className='position-fixed top-0 end-0 p-3';e.style.zIndex='9999';e.innerHTML='<div class="alert alert-'+t+' alert-dismissible fade show" role="alert">'+escapeHtml(m)+'<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';document.body.appendChild(e);setTimeout(function(){e.remove()},5000);}
function escapeHtml(t){return $('<div>').text(t||'').html();}
function debounce(fn,ms){var t;return function(){var c=this,a=arguments;clearTimeout(t);t=setTimeout(function(){fn.apply(c,a);},ms);};}
