<?php require_once(ROOT_URL . '/includes/finance/finance_functions.php');
$paymentType = 'Expenses';

if (!function_exists('getCompanyDetails')) {
    function getCompanyDetails($k){ return '0.20'; } // fallback VAT
}
?>
<style>
@media (min-width: 1200px) {
    .sidebar-hidden .col-xl-4 {
        display: none !important;
    }

    .sidebar-hidden .col-xl-8 {
        flex: 0 0 100% !important;
        max-width: 100% !important;
    }
}

.select-wrapper {
    background-color: #fff !important
}
</style>

<div class="container-fluid py-3">
    <div class="row">
        <div class="col-12">
            <div class="btn-group me-2 mb-4" role="group" aria-label="Receipts">
                <a href="index.php?t=includes/finance&p=finance_receipts.php" class="btn btn-outline-secondary">Receipts</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Expenses">
                <a href="index.php?t=includes/finance&p=finance_expenses.php" class="btn btn-dark active">Expenses</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Outgoings">
                <a href="index.php?t=includes/finance&p=finance_outgoings.php" class="btn btn-outline-secondary">Outgoings</a>
            </div>

            <div class="float-end">
                <button type="button" id="btnToggleSidebar" class="btn btn-success"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Toggle sidebar">
                    <i class="fad fa-columns me-2"></i>New entry
                </button>
                <button type="button" id="btnPrint" class="btn btn-info"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Print current list">
                    <i class="fad fa-print me-2"></i>Print
                </button>

                <div class="btn-group">
                    <button
                            type="button"
                            class="btn btn-secondary dropdown-toggle"
                            data-mdb-dropdown-init
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                            title="Export expenses to CSV"
                            id="btnExportExpenses">
                        <i class="fad fa-file-csv me-1"></i> Export CSV
                    </button>

                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item exp-export" href="#"
                               data-preset="generic"
                               data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover"
                               title="Generic CSV">
                                Generic
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item exp-export" href="#"
                               data-preset="xero_bank"
                               data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover"
                               title="Xero bank statement style CSV">
                                Xero
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item exp-export" href="#"
                               data-preset="sage_bank"
                               data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover"
                               title="Sage bank transaction style CSV">
                                Sage
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div class="row g-3">

        <!-- Sidebar -->
        <div class="col-12 col-xl-4">
            <div class="card shadow-2-strong note note-secondary">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <i class="fad fa-cash-register fa-lg me-2"></i>
                        <h5 class="mb-0">Register Expenses</h5>
                    </div>

                    <form id="expenseForm" autocomplete="off">
                        <div class="row g-2 mt-2">

                            <!-- Date -->
                            <div class="mt-2">
                                <div class="col-5 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                                    <label class="mb-1" for="date">Date</label>
                                    <input type="text" id="date" name="date" class="form-control"
                                           placeholder="dd-mm-yyyy" value="<?= date('d-m-Y') ?>"
                                           data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" />
                                </div>
                            </div>

                            <div class="col-5">
                                <label for="employee">Employee</label>
                                <?php echo listSurveyor($_SESSION['userid'], "employee"); ?>
                            </div>

                            <div class="col-5">
                                <label for="payee">Payee</label>
                                <select class="form-control form-control-sm" id="payee" name="payee" data-placeholder="Select Payee"><?php echo listPayee('out')?></select>
                            </div>
                            <div class="col-2 d-flex align-items-end">
                                <button type="button" id="btnNewPayee" class="btn btn-secondary w-100"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Add new payee">
                                    <i class="fad fa-plus me-2"></i>
                                </button>
                            </div>
                        </div>
                        <div class="row g-2 mt-2">
                            <div class="col-5">
                                <label for="type">Expense Type</label>
                                <select id="type" class="form-select" name="type">
                                    <?php echo getExpenses(); ?>
                                </select>
                            </div>
                            <div class="col-2 d-flex align-items-end">
                                <button type="button" id="btnNewExpenseType" class="btn btn-secondary w-100"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Register new expense type">
                                    <i class="fad fa-plus me-2"></i></button>
                            </div>
                        </div>

                        <!-- Description -->
                        <div class="mt-2">
                            <label for="desc">Details</label>
                            <textarea id="desc" name="desc" class="form-control" rows="2" placeholder="What was this expense for?"></textarea>
                        </div>

                        <!-- Method -->
                        <div class="mt-3">
                            <label class="control-label d-block mb-1">Method</label>
                            <div class="btn-group" role="group" aria-label="Method">
                                <input type="radio" class="btn-check" name="payment_method" id="m_cash_exp" value="Cash" autocomplete="off" checked>
                                <label class="btn btn-info" for="m_cash_exp" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Cash">
                                    <i class="fad fa-university me-1"></i>Cash
                                </label>
                                <input type="radio" class="btn-check" name="payment_method" id="m_bacs_exp" value="BACS" autocomplete="off" >
                                <label class="btn btn-secondary" for="m_bacs_exp" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="BACS transfer">
                                    <i class="fad fa-university me-1"></i>BACS
                                </label>

                                <input type="radio" class="btn-check" name="payment_method" id="m_cheque_exp" value="Cheque" autocomplete="off">
                                <label class="btn btn-secondary" for="m_cheque_exp" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Cheque">
                                    <i class="fad fa-money-check-edit me-1"></i>Cheque
                                </label>

                                <input type="radio" class="btn-check" name="payment_method" id="m_card_exp" value="Card" autocomplete="off">
                                <label class="btn btn-secondary" for="m_card_exp" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Card payment">
                                    <i class="fad fa-credit-card me-1"></i>Card
                                </label>

                                <input type="radio" class="btn-check" name="payment_method" id="m_other_exp" value="Other" autocomplete="off">
                                <label class="btn btn-secondary" for="m_other_exp" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Other method">
                                    <i class="fad fa-ellipsis-h me-1"></i>Other
                                </label>
                            </div>

                            <div id="chequeRow_exp" class="mt-2" style="display:none">
                                <label class="control-label" for="chequeNo">Cheque number</label>
                                <input type="text" id="chequeNo" name="chequeNo" class="form-control" placeholder="Cheque number">
                            </div>
                        </div>

                        <!-- Amount + VAT -->
                        <div class="mt-3">
                            <label class="control-label" for="amount_gross">Amount (gross)</label>
                            <input type="text" id="amount_gross" name="amount" class="form-control" placeholder="0.00">
                            <small id="vatHelper" class="text-muted d-none"></small>
                        </div>

                        <div class="mt-3">
                            <label class="control-label d-block mb-1">VAT</label>
                            <div class="btn-group" role="group" aria-label="VAT">
                                <input type="radio" class="btn-check" name="vatMode" id="vat_on" value="on" autocomplete="off" checked>
                                <label class="btn btn-info" for="vat_on"
                                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Apply VAT">
                                    <i class="fad fa-percent me-1"></i>Apply VAT
                                </label>

                                <input type="radio" class="btn-check" name="vatMode" id="vat_off" value="off" autocomplete="off">
                                <label class="btn btn-secondary" for="vat_off"
                                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="No VAT">
                                    <i class="fad fa-ban me-1"></i>No VAT
                                </label>
                            </div>
                        </div>

                        <!-- Mileage block (hidden unless Type = Mileage) -->
                        <div id="vehicle" class="col-12 white p-2 border mt-2 note note-dark text-secondary" style="display:none">
                            <div class="row">
                                <div class="form-group mb-3 col-6">
                                    <div class="col-12"><label for="vReg">Vehicle Reg</label></div>
                                    <div class="col-12 input-group">
                                        <select class="form-select" id="vReg" name="vReg" style="max-width:200px">
                                            <?php echo listVehicles('vReg'); ?>
                                        </select>
                                        <button type="button" id="newVehicle" class="btn btn-secondary px-3 py-2 ms-2"
                                                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Register vehicle">
                                            <i class="fad fa-car-side"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="form-group mb-3 col-3">
                                    <label for="vMileage">Miles</label>
                                    <input type="number" step="0.1" id="vMileage" name="vMileage" class="form-control" placeholder="0">
                                </div>
                                <div class="form-group mb-3 col-3 d-flex align-items-end">
                                    <button type="button" id="checkMileage" class="btn btn-info w-100"
                                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Calculate mileage">
                                        <i class="fad fa-calculator me-2"></i>Calc
                                    </button>
                                </div>
                            </div>
                            <div id="mileageDetails" class="mt-2"></div>
                            <input type="hidden" name="vRate" id="vRate" value="">
                            <input type="hidden" name="vDetails" id="vDetails" value="">
                        </div>

                        <!-- Hidden fields -->
                        <input type="hidden" id="vatrate" name="vatrate" value="<?= htmlspecialchars(getCompanyDetails('vatrate')) ?>">
                        <input type="hidden" name="use_vat" id="use_vat" value="applyvat"><!-- maps radios to handler -->
                        <input type="hidden" name="FUNCTION" value="register_expense">
                        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                        <input type="hidden" name="payment_type" value="Expenses">
                        <input type="hidden" id="totals" name="totals" value="0|0">
                        <input type="hidden" id="vat_flag" name="vat_flag" value="1">

                        <div class="d-flex gap-2 mt-3">
                            <button type="button" id="btnSaveExpense" class="btn btn-info"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save expense">
                                <i class="fad fa-save me-2"></i>Save
                            </button>
                            <button type="reset" class="btn btn-secondary"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear">
                                <i class="fad fa-undo me-2"></i>Reset
                            </button>
                        </div>
                    </form>

                </div>
            </div>
        </div>

        <!-- Main -->
        <div class="col-12 col-xl-8">
            <div class="card shadow-2-strong">
                <div class="card-body">
                    <!-- Header -->
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="d-flex align-items-center">
                            <i class="fad fa-file-invoice-dollar fa-lg me-2"></i>
                            <h5 class="mb-0">Expenses</h5>
                        </div>

                    </div>

                    <!-- Filters -->
                    <div class="row g-2 mb-2">
                        <div class="col-12 col-md-3 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="control-label" for="flt_from">From</label>
                            <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   type="text" id="flt_from" value="<?= date('01-m-Y') ?>" />
                        </div>
                        <div class="col-12 col-md-3 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="control-label" for="flt_to">To</label>
                            <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   type="text" id="flt_to" value="<?= date('d-m-Y') ?>" />
                        </div>
                        <div class="col-12 col-12 col-md-2">
                            <label class="control-label" for="btnFilter">&nbsp;</label>
                            <button type="button" id="btnFilter" class="btn btn-info mt-md-4"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Apply date filter">
                                <i class="fad fa-filter me-2"></i>Filter
                            </button>
                        </div>
                        <div class="col-12 col-md-3">
                            <label class="control-label" for="txtSearch">Search</label>
                            <input id="txtSearch" type="text" class="form-control" placeholder="Payee, employee or details">
                        </div>
                        <div class="col-12 col-md-1">
                            <label class="control-label" for="btnSearch">&nbsp;</label>
                            <button type="button" id="btnSearch" class="btn btn-secondary mt-md-4"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Search all records">
                                <i class="fad fa-search"></i>
                            </button>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 id="rangeTitle" class="mb-0"></h6>
                    </div>

                    <div id="expenseList"></div>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    document.body.classList.add('sidebar-hidden');
    reloadList();
    initSearchableSelects();

    // Sidebar toggle
    document.addEventListener('click', (e) => {
        const btn = e.target.closest('#btnToggleSidebar');
        if (!btn) return;
        const hidden = document.body.classList.toggle('sidebar-hidden');
        btn.classList.toggle('btn-success', hidden);
        btn.classList.toggle('btn-warning', !hidden);
        btn.innerHTML = hidden ?
            '<i class="fad fa-columns me-2"></i>New entry' :
            '<i class="fad fa-times me-2"></i>Close';
    });

    wireTypeMileage();
    wireMethodRadios();

    // VAT UI + preview + hidden mapping
    styleVatButtons();
    bindValueRecalc();
    recomputeTotalsFields();
    updateVatHelper();

    // New Expense Type modal
    document.getElementById('btnNewExpenseType')?.addEventListener('click', () => {
        const url = ROOT_URL + '/includes/finance/expenses/finance_newExpense.php?tenant=' + TENANT_URL;
        loadModalContent(url, "popupBox", "modal-md", 1060, "true", "Register Expense Type", "", "");
    });


    window.onNewExpenseTypeSaved = function(name) {
        const sel = document.getElementById('type');
        if (!sel || !name) return;
        let opt = Array.from(sel.options).find(o => o.value === name);
        if (!opt) {
            opt = document.createElement('option');
            opt.value = name;
            opt.textContent = name;
            sel.appendChild(opt);
        }
        sel.value = name;
        sel.dispatchEvent(new Event('change', {
            bubbles: true
        }));
        initSearchableSelects();
    };

    // New Vehicle modal
    document.getElementById('newVehicle')?.addEventListener('click', () => {
        const url = ROOT_URL + '/includes/finance/finance_newVehicle.php?tenant=' + TENANT_URL;
        loadModalContent(url, "popupBox", "modal-md", 1060, "true", "Register Vehicle", "", "");
    });

    document.getElementById('checkMileage')?.addEventListener('click', handleMileageCalc);
    document.getElementById('btnSaveExpense')?.addEventListener('click', submitExpense);
    document.getElementById('btnFilter')?.addEventListener('click', () => reloadList());
});


function initSearchableSelects() {
    ['payee', 'employee', 'type', 'vReg'].forEach(id => {
        const el = document.getElementById(id);
        if (!el) return;
        try {
            mdb.Select.getInstance(el)?.dispose();
        } catch {}
        try {
            new mdb.Select(el, {
                filter: true,
                container: 'body'
            });
        } catch {}
    });
}

// Show vehicle block only when type = Mileage
function wireTypeMileage() {
    const sel = document.getElementById('type');
    const box = document.getElementById('vehicle');
    if (!sel || !box) return;
    const isMileage = () => {
        const v = (sel.value || '').toLowerCase();
        const txt = (sel.options[sel.selectedIndex]?.textContent || '').toLowerCase();
        return v === 'mileage' || txt === 'mileage';
    };
    const toggle = () => {
        box.style.display = isMileage() ? 'block' : 'none';
    };
    sel.addEventListener('change', toggle);
    toggle();
}

// Method radios: cheque field + active label colour
function wireMethodRadios() {
    const form = document.getElementById('expenseForm');
    const row = document.getElementById('chequeRow_exp');
    if (!form) return;
    const radios = form.querySelectorAll('input[name="payment_method"].btn-check');
    const update = () => {
        let m = 'Cash';
        radios.forEach(r => {
            const lbl = form.querySelector(`label[for="${r.id}"]`);
            if (r.checked) {
                m = r.value;
                lbl?.classList.add('btn-info');
                lbl?.classList.remove('btn-secondary');
            } else {
                lbl?.classList.remove('btn-info');
                lbl?.classList.add('btn-secondary');
            }
        });
        if (row) {
            row.style.display = (m === 'Cheque') ? 'block' : 'none';
            if (m !== 'Cheque') {
                const ch = form.querySelector('#chequeNo');
                if (ch) ch.value = '';
            }
        }
    };
    radios.forEach(r => r.addEventListener('change', update));
    update();
}

// ---------- VAT ----------
function r_num(val) {
    const n = parseFloat(String(val || '').replace(/[^0-9.\-]/g, ''));
    return isNaN(n) ? 0 : n;
}

function r_fmt(n) {
    return '£' + (Number(n || 0)).toFixed(2);
}

// Selected = btn-info, others = btn-secondary
function styleVatButtons() {
    const radios = document.querySelectorAll('input[type="radio"][name="vatMode"]');
    if (!radios.length) return;
    const refresh = () => {
        radios.forEach(r => {
            const lab = document.querySelector(`label[for="${r.id}"]`);
            if (!lab) return;
            lab.classList.remove('btn-info', 'btn-secondary');
            lab.classList.add(r.checked ? 'btn-info' : 'btn-secondary');
        });
    };
    radios.forEach(r => r.addEventListener('change', refresh));
    refresh();
}

// Helper preview under Amount (net)
function updateVatHelper() {
    const helper = document.getElementById('vatHelper');
    const vatOn = !!document.getElementById('vat_on')?.checked;
    const grossVal = r_num(document.getElementById('amount_gross')?.value);
    if (!helper) return;
    if (!vatOn || grossVal <= 0) {
        helper.classList.add('d-none');
        helper.textContent = '';
        return;
    }
    const raw = document.getElementById('vatrate')?.value ?? '0.20';
    let rate = parseFloat(String(raw).replace(',', '.'));
    if (isNaN(rate)) rate = 0.20;
    if (rate > 1) rate = rate / 100;
    const div = 1 + rate;
    const net = +(grossVal / div).toFixed(2);
    const vat = +(grossVal - net).toFixed(2);
    helper.textContent = `${r_fmt(grossVal)} gross / ${r_fmt(net)} net / ${r_fmt(vat)} vat`;
    helper.classList.remove('d-none');
}

// Hidden fields for server (totals, vat_flag, use_vat)
function recomputeTotalsFields() {
    const vatOn = !!document.getElementById('vat_on')?.checked;
    const grossVal = r_num(document.getElementById('amount_gross')?.value);
    const raw = document.getElementById('vatrate')?.value ?? '0.20';
    let rate = parseFloat(String(raw).replace(',', '.'));
    if (isNaN(rate)) rate = 0.20;
    if (rate > 1) rate = rate / 100;
    let net = grossVal;
    let vat = 0;
    if (vatOn) {
        const div = 1 + rate;
        net = +(grossVal / div).toFixed(2);
        vat = +(grossVal - net).toFixed(2);
    }
    const totalsEl = document.getElementById('totals');
    const flagEl = document.getElementById('vat_flag');
    const useEl = document.getElementById('use_vat');
    if (totalsEl) totalsEl.value = (net || 0).toFixed(2) + '|' + vat.toFixed(2);
    if (flagEl) flagEl.value = vatOn ? '1' : '0';
    if (useEl) useEl.value = vatOn ? 'applyvat' : 'novat'; // server expects this
}

// Bind inputs
function bindValueRecalc() {
    const amt = document.getElementById('amount_gross');
    if (amt) {
        amt.addEventListener('input', () => {
            updateVatHelper();
            recomputeTotalsFields();
        });
        amt.addEventListener('blur', () => {
            recomputeTotalsFields();
            updateVatHelper();
        });
    }
    ['vat_on', 'vat_off'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', () => {
            recomputeTotalsFields();
            updateVatHelper();
        });
    });
}

// ---------- Mileage ----------
async function handleMileageCalc() {
    const vReg = document.getElementById('vReg')?.value || '';
    const miles = document.getElementById('vMileage')?.value || '';
    if (!vReg) {
        showResponse('warning', 'YOU MUST SELECT A VEHICLE');
        return;
    }
    if (!miles) {
        showResponse('warning', 'YOU MUST ADD MILEAGE');
        return;
    }
    try {
        const body = new URLSearchParams({
            FUNCTION: 'calcMileage',
            reg: vReg,
            miles,
            tenant: TENANT_URL
        });
        const resp = await fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body
        });
        const html = await resp.text();
        const details = document.getElementById('mileageDetails');
        if (details) details.innerHTML = html;
        const rTotal = document.getElementById('returnTotal')?.value || '';
        const rVat = document.getElementById('returnVat')?.value || '';
        const rNet = document.getElementById('returnNet')?.value || '';
        if (rNet) document.getElementById('net').value = rNet;
        if (rVat) document.getElementById('vat').value = rVat;
        if (rTotal) document.getElementById('amount_gross').value = rTotal;
        recomputeTotalsFields();
        updateVatHelper();
    } catch {
        showResponse('danger', 'Unable to calculate mileage');
    }
}

// ---------- Save / List / Print ----------
async function submitExpense() {
    const form = document.getElementById('expenseForm');
    if (!form) return;
    const amt = document.getElementById('amount_gross');
    const type = document.getElementById('type');

    if (!type || !type.value.trim()) {
        showResponse('warning', 'Expense type is required');
        return;
    }

    if (!amt || !amt.value.trim()) {
        showResponse('warning', 'Amount is required');
        return;
    }
    recomputeTotalsFields();
    const payload = new URLSearchParams(new FormData(form));
    if (!payload.get('tenant')) payload.set('tenant', TENANT_URL);
    try {
        const res = await fetch(ROOT_URL + '/includes/finance/expenses/finance_expense_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: payload
        });
        const txt = (await res.text()).trim().toLowerCase();
        if (txt.includes('success')) {
            showResponse('success', 'Saved');
            form.reset();
            initSearchableSelects();
            wireTypeMileage();
            styleVatButtons();
            recomputeTotalsFields();
            updateVatHelper();
            reloadList();
        } else {
            showResponse('danger', 'Save failed: ' + (txt || 'Unknown error'));
        }
    } catch {
        showResponse('danger', 'Network error');
    }
}

function debounce(fn, ms) {
    let t;
    return function(...args) {
        clearTimeout(t);
        t = setTimeout(() => fn.apply(this, args), ms);
    };
}


function debounce(fn, ms) {
    let t;
    return (...args) => {
        clearTimeout(t);
        t = setTimeout(() => fn(...args), ms);
    };
}

async function loadList(from, to, q) {
    const title = document.getElementById('rangeTitle');
    const term = (q || '').trim();
    if (title) {
        title.textContent = term ? `Showing ${from} to ${to} (search: "${term}")` : `Showing ${from} to ${to}`;
    }

    const qs = new URLSearchParams({
        payment_type: 'Expenses',
        start: from || '',
        end: to || '',
        q: term,
        tenant: TENANT_URL,
        _ts: Date.now()
    }).toString();

    const url = ROOT_URL + '/includes/finance/expenses/finance_exp_data.php?' + qs;
    loadContentAndExecuteScripts(url, 'expenseList');
}

window.reloadList = function() {
    const from = document.getElementById('flt_from')?.value || '01-01-1970';
    const to = document.getElementById('flt_to')?.value || '<?= date('d-m-Y') ?>';
    const q = document.getElementById('txtSearch')?.value || '';
    loadList(from, to, q);
};

// Search + filter bindings
(function bindListControls() {
    const btnFilter = document.getElementById('btnFilter');
    const btnSearch = document.getElementById('btnSearch');
    const txtSearch = document.getElementById('txtSearch');

    btnFilter?.addEventListener('click', () => reloadList());
    btnSearch?.addEventListener('click', () => reloadList());

    if (txtSearch) {
        const handler = debounce(() => reloadList(), 250);
        txtSearch.addEventListener('input', handler);
        txtSearch.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                reloadList();
            }
        });
    }
})();

document.getElementById('btnPrint')?.addEventListener('click', () => {
    const wrap = document.getElementById('expenseData'); // table wrapper id
    const contentHtml = wrap ? wrap.innerHTML : '';

    if (!contentHtml.trim()) {
        showResponse('warning', 'Nothing to print');
        return;
    }

    const header = '<?= htmlspecialchars($paymentType) ?>';

    try {
        printContainer(contentHtml, {
            orientation: 'landscape',
            header: `<p>${header}</p>`,
            footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
            logoUrl: 'images/company/logo.jpg',
            styles: [
                `${ROOT_URL}/src/css/print.css`,
            ],
        });
    } catch (e) {
        showResponse('danger', 'Print unavailable');
    }
});

(function() {
    function pickValue(ids) {
        for (const id of ids) {
            const el = document.getElementById(id);
            if (el && typeof el.value === 'string') return el.value.trim();
        }
        return '';
    }

    function getStartEnd() {
        const start = pickValue(['start', 'date_start', 'date_from', 'from', 'filter_start']);
        const end = pickValue(['end', 'date_end', 'date_to', 'to', 'filter_end']);
        return {
            start,
            end
        };
    }

    function getSearchTerm() {
        return pickValue(['q', 'search', 'term']);
    }

    document.querySelectorAll('.exp-export').forEach(a => {
        a.addEventListener('click', (e) => {
            e.preventDefault();

            const preset = (a.dataset.preset || 'generic').trim();
            const {
                start,
                end
            } = getStartEnd();
            const q = getSearchTerm();

            // Expenses are stored in the same table; defined by payment_type
            const url = ROOT_URL + '/includes/finance/tools/export_outgoings.php' +
                '?preset=' + encodeURIComponent(preset) +
                '&payment_type=' + encodeURIComponent('Expenses') +
                '&start=' + encodeURIComponent(start) +
                '&end=' + encodeURIComponent(end) +
                (q ? '&q=' + encodeURIComponent(q) : '') +
                '&tenant=' + encodeURIComponent(TENANT_URL);

            window.location.href = url;
        });
    });
})();

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item ">Finance - Expenses</li> ';
</script>