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

// Falls back to 0.20 (20%) if not set in company settings
if (!function_exists('getCompanyDetails')) {
    function getCompanyDetails($k){ return '0.20'; }
}
?>
<style>
.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-outline-secondary">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-dark active">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 outgoings to CSV"
                            id="btnExportOutgoings">
                        <i class="fad fa-file-csv me-1"></i> Export CSV
                    </button>

                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item out-export" href="#"
                               data-preset="generic"
                               data-mdb-tooltip-init data-mdb-placement="right" data-mdb-trigger="hover"
                               title="Generic CSV (recommended for mapping)">
                                Generic
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item out-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 out-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 form -->
        <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 <?= htmlspecialchars($paymentType) ?></h5>
                    </div>

                    <form id="outForm" autocomplete="off">
                        <div class="row">
                            <!-- Date -->
                            <div class="date-picker col-12 col-md-6" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                                <label class="control-label" for="exp_date">Date</label>
                                <input type="text" id="exp_date" name="date" class="form-control"
                                       placeholder="dd-mm-yyyy" value="<?= date('d-m-Y') ?>"
                                       data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" />
                            </div>

                            <!-- Type -->
                            <div class="col-12 col-md-6">
                                <label for="type">Type</label>
                                <select class="form-control-sm w-100" id="type" name="type" data-placeholder="Select Type">
                                    <?= listCodes('payee','desc') ?>
                                </select>
                            </div>
                        </div>

                        <!-- Payee + New -->
                        <div class="row g-2 mt-2">
                            <div class="col-5">
                                <label for="payee">Payee</label>
                                <select class="form-control form-control-sm" id="payee" name="payee" data-placeholder="Select Payee">
                                    <?= 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>

                        <!-- Details -->
                        <div class="mt-2">
                            <label for="desc">Details</label>
                            <textarea class="form-control" id="desc" name="desc" placeholder="Details"></textarea>
                        </div>

                        <!-- Amount (Gross) -->
                        <div class="mt-2">
                            <label for="amount_gross">Amount (gross)</label>
                            <input
                                   type="text"
                                   id="amount_gross"
                                   name="amount_gross"
                                   class="form-control form-control-sm"
                                   inputmode="decimal"
                                   placeholder="0.00">
                            <div id="vatHelper" class="form-text text-muted small">
                                VAT will be calculated automatically from the amount using the selected rate. Adjust VAT to override.
                            </div>
                        </div>

                        <!-- VAT mode -->
                        <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" 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">
                                <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>

                        <!-- VAT Amount (visible only when VAT applied) -->
                        <div class="mt-2 d-none" id="vatAmountRow">
                            <label class="control-label" for="vat_amount">VAT Amount</label>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">£</span>
                                <input type="text" id="vat_amount" name="vatAmount" class="form-control" placeholder="0.00" inputmode="decimal" autocomplete="off">
                                <button class="btn btn-secondary" type="button" id="btnResetVat"
                                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Recalculate from net">
                                    <i class="fad fa-sync-alt"></i>
                                </button>
                            </div>
                            <small class="text-muted">Auto-calculated; you may override.</small>
                        </div>

                        <!-- Method + Cheque -->
                        <div class="mt-3 mb-5">
                            <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_bacs_out" value="BACS" checked>
                                <label class="btn btn-info" for="m_bacs_out" 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_out" value="Cheque">
                                <label class="btn btn-secondary" for="m_cheque_out" 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_out" value="Card">
                                <label class="btn btn-secondary" for="m_card_out" 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_out" value="Other">
                                <label class="btn btn-secondary" for="m_other_out" 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_out" 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>

                        <div class="d-flex gap-2 mt-3">
                            <button type="button" id="btnSaveOut" class="btn btn-info"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save outgoing">
                                <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>

                        <!-- Hidden fields -->
                        <input type="hidden" name="FUNCTION" value="register_outgoing">
                        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                        <input type="hidden" name="payment_type" value="<?= htmlspecialchars($paymentType) ?>">
                        <input type="hidden" id="vatrate" name="vatrate" value="<?= htmlspecialchars(getCompanyDetails('vatrate')) ?>">
                        <input type="hidden" id="totals" name="totals" value="0|0"> <!-- net|vat -->
                        <input type="hidden" id="vat_flag" name="vat_flag" value="1"> <!-- 1 apply / 0 off -->
                        <input type="hidden" id="use_vat" name="use_vat" value="applyvat">
                        <input type="hidden" id="vat_standalone" name="vat" value="0.00"> <!-- standalone VAT -->
                    </form>
                </div>
            </div>
        </div>

        <!-- Right pane -->
        <div class="col-12 col-xl-8">
            <div class="card shadow-2-strong">
                <div class="card-body">
                    <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"><?= htmlspecialchars($paymentType) ?></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-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, type, code, details or amount">
                        </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 class="d-flex align-items-center gap-2">
                            <label for="rowsPerPage" class="mb-0 small text-muted">Rows shown</label>
                            <select id="rowsPerPage" class="form-select form-select-sm"
                                    style="width: auto; min-width: 80px;"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    title="Change number of rows shown">
                            </select>
                        </div>
                    </div>


                    <!-- Table container -->
                    <div id="expenseList"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Sidebar hidden by default
document.addEventListener('DOMContentLoaded', () => {
    document.body.classList.add('sidebar-hidden');
});

// 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';
});

let payeeSelect, typeSelect;

function initPayeeTypeSelects() {
    const payeeEl = document.getElementById('payee');
    const typeEl = document.getElementById('type');
    try {
        payeeSelect?.dispose?.();
    } catch {}
    try {
        typeSelect?.dispose?.();
    } catch {}
    if (payeeEl) payeeSelect = new mdb.Select(payeeEl, {
        filter: true,
        container: "body"
    });
    if (typeEl) typeSelect = new mdb.Select(typeEl, {
        filter: true,
        container: "body"
    });
}
document.addEventListener('DOMContentLoaded', initPayeeTypeSelects);
document.getElementById('outForm')?.addEventListener('reset', () => setTimeout(initPayeeTypeSelects, 0));

// Callback from New Payee modal (expected)
window.onNewPayeeSaved = function(newName) {
    const sel = document.getElementById('payee');
    if (!sel || !newName) return;
    let opt = Array.from(sel.options).find(o => o.value === newName);
    if (!opt) {
        opt = document.createElement('option');
        opt.value = newName;
        opt.textContent = newName;
        sel.appendChild(opt);
    }
    sel.value = newName;
    initPayeeTypeSelects();
};

// New Payee modal
document.getElementById('btnNewPayee')?.addEventListener('click', () => {
    const url = ROOT_URL + '/includes/finance/finance_newPayee.php?type=exp&tenant=' + TENANT_URL;
    loadModalContent(url, "popupBox", "modal-md", 1060, "true", "Register New Payee", "", "");
});

// Method radios: cheque toggle + label style
(function wireMethodRadios() {
    const form = document.getElementById('outForm');
    if (!form) return;
    const row = document.getElementById('chequeRow_out');
    const radios = form.querySelectorAll('input[name="payment_method"].btn-check');
    const update = () => {
        let m = 'BACS';
        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 live calculation + override -----
function parseNum(v) {
    const n = parseFloat(String(v || '').replace(/[^0-9.\-]/g, ''));
    return isNaN(n) ? 0 : n;
}

function round2(n) {
    return Math.round((Number(n) + Number.EPSILON) * 100) / 100;
}

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

// Elements
const amountGrossEl = document.getElementById('amount_gross');
const vatOnEl = document.getElementById('vat_on');
const vatOffEl = document.getElementById('vat_off');
const vatrateEl = document.getElementById('vatrate'); // "0.20" or "20" (carried only)
const vatFlagEl = document.getElementById('vat_flag'); // hidden 1/0
const useVatEl = document.getElementById('use_vat'); // applyvat/novat
const totalsEl = document.getElementById('totals'); // "net|vat"
const vatHelperEl = document.getElementById('vatHelper');
const vatAmountRow = document.getElementById('vatAmountRow'); // container row
const vatAmountEl = document.getElementById('vat_amount'); // input for VAT £
const resetVatBtn = document.getElementById('btnResetVat');
const vatStandalone = document.getElementById('vat_standalone'); // hidden name="vat"
let userVatOverride = false;

function getVatRatePercent() {
    let v = (vatrateEl?.value || '0.20').trim().replace(',', '.');
    let f = parseFloat(v);
    if (isNaN(f)) f = 0.20;
    if (f <= 1) f = f * 100; // convert 0.20 => 20
    if (f < 0) f = 0;
    if (f > 100) f = 100;
    return f;
}

function isVatApplied() {
    return !!vatOnEl?.checked;
}

function showVatRow(show) {
    if (!vatAmountRow) return;
    vatAmountRow.classList.toggle('d-none', !show);
}

function syncVatState() {
    const rate = getVatRatePercent();
    if (!amountGrossEl || !totalsEl) return;

    const grossIn = parseNum(amountGrossEl.value);
    let net = grossIn;
    let vat = 0;

    if (isVatApplied()) {
        const div = 1 + (rate / 100);
        if (!userVatOverride) {
            net = round2(grossIn / div);
            vat = round2(grossIn - net);
            if (vatAmountEl) vatAmountEl.value = vat.toFixed(2);
            if (vatStandalone) vatStandalone.value = vat.toFixed(2);
        } else {
            vat = round2(parseNum(vatAmountEl?.value || 0));
            net = round2(grossIn - vat);
            if (vatStandalone) vatStandalone.value = vat.toFixed(2);
        }

        showVatRow(true);
        if (vatFlagEl) vatFlagEl.value = '1';
        if (useVatEl) useVatEl.value = 'applyvat';

        if (vatHelperEl) {
            if (vat > 0.0001) {
                vatHelperEl.textContent =
                    `£${grossIn.toFixed(2)} gross / £${net.toFixed(2)} net / £${vat.toFixed(2)} VAT`;
            } else {
                vatHelperEl.textContent = '';
            }
        }
    } else {
        vat = 0;
        showVatRow(false);
        userVatOverride = false;
        if (vatFlagEl) vatFlagEl.value = '0';
        if (useVatEl) useVatEl.value = 'novat';
        if (vatHelperEl) vatHelperEl.textContent = '';
        if (vatAmountEl) vatAmountEl.value = '';
        if (vatStandalone) vatStandalone.value = '0.00';
    }

    totalsEl.value = `${net.toFixed(2)}|${vat.toFixed(2)}`;
}


if (amountGrossEl) {
    amountGrossEl.addEventListener('input', () => {
        userVatOverride = false;
        syncVatState();
    });
}
if (vatOnEl) vatOnEl.addEventListener('change', () => {
    userVatOverride = false;
    syncVatState();
});
if (vatOffEl) vatOffEl.addEventListener('change', () => {
    userVatOverride = false;
    syncVatState();
});
if (vatAmountEl) {
    vatAmountEl.addEventListener('input', () => {
        userVatOverride = true;
        syncVatState();
    });
}
if (resetVatBtn) {
    resetVatBtn.addEventListener('click', () => {
        userVatOverride = false;
        syncVatState();
    });
}

// Initial VAT sync
syncVatState();

// ----- Rows-per-page handling -----
const outgoingRowsPerPageOptions = [25, 50, 100, 'All'];
window.currentOutgoingRowsLimit = outgoingRowsPerPageOptions[0];

function initRowsPerPageControl() {
    const sel = document.getElementById('rowsPerPage');
    if (!sel) return;

    // Build options from array so it's easy to extend
    sel.innerHTML = '';
    outgoingRowsPerPageOptions.forEach(val => {
        const opt = document.createElement('option');
        opt.value = (val === 'All') ? 'all' : String(val);
        opt.textContent = (val === 'All') ? 'All' : String(val);
        if (
            (val === 'All' && window.currentOutgoingRowsLimit === 'all') ||
            (typeof window.currentOutgoingRowsLimit === 'number' && val === window.currentOutgoingRowsLimit)
        ) {
            opt.selected = true;
        }
        sel.appendChild(opt);
    });

    sel.addEventListener('change', () => {
        const val = sel.value;
        window.currentOutgoingRowsLimit = (val === 'all') ? 'all' : (parseInt(val, 10) || 'all');
        if (typeof window.filterAndLimitOutgoingRows === 'function') {
            window.filterAndLimitOutgoingRows();
        }
    });
}
document.addEventListener('DOMContentLoaded', initRowsPerPageControl);

// ----- Form submit (save outgoing) -----
async function submitOutgoing() {
    const form = document.getElementById('outForm');
    if (!form) return;

    const body = new URLSearchParams(new FormData(form));

    // Ensure required fields
    if (!body.get('FUNCTION')) body.set('FUNCTION', 'register_outgoing');
    if (!body.get('payment_type')) body.set('payment_type', 'Outgoings');
    if (!body.get('tenant')) body.set('tenant', TENANT_URL);

    // Compute net/vat from the UI (Amount is GROSS)
    const gross = parseNum(amountGrossEl?.value || 0);
    const ratePct = getVatRatePercent(); // 20 for 0.20 etc
    const div = 1 + (ratePct / 100);
    let net = gross;
    let vat = 0;

    if (isVatApplied()) {
        if (userVatOverride) {
            vat = round2(parseNum(vatAmountEl?.value || 0));
            net = round2(gross - vat);
        } else {
            net = round2(gross / div);
            vat = round2(gross - net);
        }
    }

    // Match what PHP expects:
    // - amount must be GROSS (because PHP divides by vatrate to get net/vat)
    // - use_vat drives whether VAT is applied
    body.set('use_vat', isVatApplied() ? 'applyvat' : 'novat');
    body.set('vat_flag', isVatApplied() ? '1' : '0');

    body.set('amount', gross.toFixed(2)); // <-- critical fix
    body.set('totals', net.toFixed(2) + '|' + vat.toFixed(2));
    body.set('vat', vat.toFixed(2)); // keeps your standalone VAT field consistent too

    try {
        const res = await fetch(
            ROOT_URL + '/includes/finance/outgoings/finance_outgoing_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body
            }
        );

        const txt = (await res.text()).trim();
        if (txt === 'success' || txt === 's') {
            showResponse('success', 'Saved');
            form.reset();
            userVatOverride = false;
            syncVatState();
            initPayeeTypeSelects();
            reloadList();
        } else {
            showResponse('danger', txt || 'Save failed');
        }
    } catch {
        showResponse('danger', 'Network error');
    }
}
document.getElementById('btnSaveOut')?.addEventListener('click', submitOutgoing);

document.getElementById('btnSaveOut')?.addEventListener('click', submitOutgoing);


// ----- Data load / search / print -----
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: 'Outgoings',
        start: from || '',
        end: to || '',
        q: term,
        tenant: TENANT_URL,
        _ts: Date.now()
    }).toString();

    const url = ROOT_URL + '/includes/finance/outgoings/finance_out_data.php?' + qs;
    loadContentAndExecuteScripts(url, 'expenseList', () => {
        applyOutgoingLimit();
    });
}

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 || '';

    // If searching, show all matches (no client-side row limiting)
    if (q.trim()) {
        window.currentOutgoingRowsLimit = 'all';
        const sel = document.getElementById('rowsPerPage');
        if (sel) sel.value = 'all';
    }

    loadList(from, to, q);
};

function applyOutgoingLimit() {
    const table = document.querySelector('#expenseData table');
    if (!table) return;
    const tbody = table.querySelector('tbody');
    if (!tbody) return;

    const limit = (window.currentOutgoingRowsLimit === undefined) ? 'all' : window.currentOutgoingRowsLimit;

    let shown = 0;
    tbody.querySelectorAll('tr').forEach(tr => {
        // "No records" row
        if (tr.querySelector('td[colspan]')) {
            tr.style.display = '';
            return;
        }

        if (limit === 'all') {
            tr.style.display = '';
            return;
        }

        shown++;
        tr.style.display = (shown <= Number(limit)) ? '' : 'none';
    });
}

(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();
            }
        });
    }

    // Row limiter dropdown still works when not searching
    const rows = document.getElementById('rowsPerPage');
    rows?.addEventListener('change', () => {
        window.currentOutgoingRowsLimit = rows.value;
        applyOutgoingLimit();
    });
})();

document.addEventListener('DOMContentLoaded', reloadList);

// Print
document.getElementById('btnPrint')?.addEventListener('click', () => {
    const wrap = document.getElementById('expenseData');
    const flt_from = document.getElementById('flt_from').value;
    const flt_to = document.getElementById('flt_to').value;
    const contentHtml = wrap ? wrap.innerHTML : '';
    if (!contentHtml.trim()) {
        showResponse('warning', 'Nothing to print');
        return;
    }
    const header = "Report of outgoings: " + flt_from + " to " + flt_to;
    try {
        if (typeof printContainer === 'function') {
            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`,
                ],
            });
        } else {
            window.print();
        }
    } catch {
        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']);
    }

    function getPaymentType(defaultValue) {
        // if you have a selector for this on the page, it will be used; otherwise hard-coded.
        return pickValue(['payment_type', 'paymentType']) || defaultValue;
    }

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

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

            const payment_type = getPaymentType('Outgoings');

            const url = ROOT_URL + '/includes/finance/tools/export_outgoings.php' +
                '?preset=' + encodeURIComponent(preset) +
                '&payment_type=' + encodeURIComponent(payment_type) +
                '&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 - Outgoings</li> ';
</script>