<?php
require_once(ROOT_URL . '/includes/finance/finance_functions.php'); ?>

<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-dark active">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-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>
        </div>
    </div>

    <div class="row g-3">
        <!-- Register Receipt (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 receipt</h5>
                    </div>

                    <form id="receiptForm" autocomplete="off">
                        <!-- Date -->
                        <div class="row g-2">
                            <div class="col-5 date-picker" data-date-type="open" data-mdb-toggle-button="false" data-format="dd-mm-yyyy">
                                <label class="control-label" for="rcp_date">Receipt date</label>
                                <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                       type="text" name="rcp_date" id="rcp_date" value="<?= date('d-m-Y') ?>" />
                            </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('in')?></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 a new payee">
                                    <i class="fad fa-plus me-2"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Details -->
                        <div class="mt-3">
                            <label class="control-label" for="details">Details</label>
                            <textarea id="details" name="details" class="form-control" rows="3" placeholder="Description of receipt"></textarea>
                        </div>

                        <!-- Method + Cheque No -->
                        <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="method" id="m_bacs" value="BACS" autocomplete="off" checked>
                                <label class="btn btn-info" for="m_bacs"
                                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="BACS transfer">
                                    <i class="fad fa-building-columns me-1"></i>BACS
                                </label>

                                <input type="radio" class="btn-check" name="method" id="m_cheque" value="Cheque" autocomplete="off">
                                <label class="btn btn-info" for="m_cheque"
                                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Cheque payment">
                                    <i class="fad fa-money-check-pen me-1"></i>Cheque
                                </label>

                                <input type="radio" class="btn-check" name="method" id="m_card" value="Card" autocomplete="off">
                                <label class="btn btn-info" for="m_card"
                                       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="method" id="m_other" value="Other" autocomplete="off">
                                <label class="btn btn-info" for="m_other"
                                       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" 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 (gross) + VAT mode + helper -->
                        <div class="mt-3">
                            <label class="control-label" for="amount_gross">Amount (gross)</label>
                            <input type="text" id="amount_gross" 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-info" 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>

                        <!-- Commission -->
                        <div class="mt-3">
                            <label class="control-label" for="commission">Commission</label>
                            <input type="text" id="commission" name="commission" class="form-control" placeholder="0.00">
                        </div>

                        <!-- Linked invoice -->
                        <div class="mt-3">
                            <label class="control-label" for="invoiceSelect">Linked invoice</label>
                            <select id="invoiceSelect" class="form-select">
                                <option value="">Select invoice</option>
                                <?php
                                    $rs = mysqli_query($GLOBALS['con'], "SELECT invNo, address FROM invoices WHERE status=1 ORDER BY invNo DESC");
                                    while ($row = mysqli_fetch_assoc($rs)) {
                                        $inv    = (int)$row['invNo'];
                                        $label  = str_pad($inv, 6, '0', STR_PAD_LEFT);
                                        $addr   = $row['address'] ?? '';
                                        $billingName = '';
                                        if ($addr !== '') {
                                            $j = json_decode($addr, true);
                                            if (json_last_error() === JSON_ERROR_NONE && is_array($j)) {
                                                $billingName = $j['billing_name'] ?? ($j['clientname'] ?? '');
                                            } else {
                                                // legacy serialize fallback
                                                $u = @unserialize($addr);
                                                if ($u !== false && is_array($u)) {
                                                    $billingName = $u['billing_name'] ?? ($u['clientname'] ?? '');
                                                }
                                            }
                                        }
                                        if ($billingName === '') $billingName = 'Unknown';

                                        echo '<option value="'.$inv.'">'.$label.' - '.htmlspecialchars($billingName).'</option>';
                                    }
                                    ?>
                            </select>
                            <small class="text-muted">Optional. Only unpaid invoices are listed.</small>
                            <input type="hidden" id="invoiceHidden" name="invoice" value="">
                        </div>


                        <div class="d-flex gap-2 mt-4">
                            <button type="submit" id="btnSave" class="btn btn-info"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save receipt">
                                <i class="fad fa-save me-2"></i>Save
                            </button>
                            <button type="button" id="btnReset" class="btn btn-secondary"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear the form">
                                <i class="fad fa-undo me-2"></i>Reset
                            </button>
                        </div>

                        <!-- Hidden fields for server -->
                        <input type="hidden" name="FUNCTION" value="register_receipts">
                        <input type="hidden" name="pType" value="in">
                        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                        <input type="hidden" id="vatrate" name="vatrate" value="<?= htmlspecialchars(getCompanyDetails('vatrate')) ?>">
                        <input type="hidden" name="use_vat" id="use_vat" value="applyvat">
                        <input type="hidden" name="totals" id="totals">
                        <input type="hidden" name="vat_flag" id="vat_flag" value="1">
                        <input type="hidden" name="date" id="date_unix">
                    </form>
                </div>
            </div>
        </div>

        <!-- List + Filters -->
        <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-receipt fa-lg me-2"></i>
                            <h5 class="mb-0">Receipts</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="date_start">From</label>
                            <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   type="text" id="date_start" 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="date_end">To</label>
                            <input class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                   type="text" id="date_end" 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="receiptSearch">Search</label>
                            <input id="receiptSearch" type="text" class="form-control" placeholder="Search all receipts">
                        </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="rowsPerPageReceipts" class="mb-0 small text-muted">Rows shown</label>
                            <select id="rowsPerPageReceipts" 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>

                    <div id="receiptsList" class="table-responsive"></div>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

// ===== Rows-per-page for RECEIPTS =====
const receiptRowsPerPageOptions = [25, 50, 100, 'All'];
window.currentReceiptRowsLimit = receiptRowsPerPageOptions[0];

function filterAndLimitReceiptRows() {
    const list = document.getElementById('receiptsList'); // container holding the table
    if (!list) return;

    const table = list.querySelector('table');
    if (!table) return;

    const tbody = table.tBodies[0] || table.querySelector('tbody');
    if (!tbody) return;

    const rows = Array.from(tbody.rows);
    const q = ''; // server-side search; client-side limiting only

    let limit = window.currentReceiptRowsLimit;
    if (limit !== 'all') {
        limit = parseInt(limit, 10);
        if (isNaN(limit) || limit <= 0) limit = 'all';
    }

    let shown = 0;
    rows.forEach(tr => {
        const text = (tr.textContent || '').toLowerCase();
        const matches = !q || text.includes(q);

        if (!matches) {
            tr.style.display = 'none';
            return;
        }

        if (limit !== 'all' && shown >= limit) {
            tr.style.display = 'none';
            return;
        }

        tr.style.display = '';
        shown++;
    });

    const titleEl = document.getElementById('rangeTitle');
    if (titleEl) {
        if (rows.length === 0) {
            titleEl.textContent = 'No receipts';
        } else if (limit === 'all') {
            titleEl.textContent = `Showing all ${shown} receipts`;
        } else {
            titleEl.textContent = `Showing ${shown} of ${rows.length} receipts`;
        }
    }
}

function initReceiptRowsPerPageControl() {
    const sel = document.getElementById('rowsPerPageReceipts');
    if (!sel) return;

    // Build options from array so it's easy to extend
    sel.innerHTML = '';
    receiptRowsPerPageOptions.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.currentReceiptRowsLimit === 'all') ||
            (typeof window.currentReceiptRowsLimit === 'number' && val === window.currentReceiptRowsLimit)
        ) {
            opt.selected = true;
        }

        sel.appendChild(opt);
    });

    sel.addEventListener('change', () => {
        const val = sel.value;
        window.currentReceiptRowsLimit = (val === 'all') ? 'all' : (parseInt(val, 10) || 'all');
        filterAndLimitReceiptRows();
    });
}

// Expose for re-use after AJAX reloads if needed
window.filterAndLimitReceiptRows = filterAndLimitReceiptRows;
window.initReceiptRowsPerPageControl = initReceiptRowsPerPageControl;

document.addEventListener('DOMContentLoaded', () => {
    initReceiptRowsPerPageControl();

    // Hook search box to same filter/limit, if you have one
    const searchInput = document.getElementById('receiptSearch');
    if (searchInput) {
        const handler = () => filterAndLimitReceiptRows();
        searchInput.addEventListener('input', handler);
    }

    // Initial apply
    filterAndLimitReceiptRows();
});


// Search binding for receipts table
function attachReceiptsFilter() {
    const input = document.getElementById('receiptSearch');
    const list = document.getElementById('receiptsList');
    if (!input || !list) return;

    const apply = () => {
        const q = (input.value || '').trim().toLowerCase();
        LAST_RECEIPT_QUERY = q;

        // find the first table in receiptsList
        const table = list.querySelector('table');
        if (!table) return;

        // prefer tbody rows, fallback to all rows except thead
        const tbody = table.querySelector('tbody');
        const rows = tbody ? Array.from(tbody.rows) :
            Array.from(table.querySelectorAll('tr:not(thead tr)'));

        rows.forEach(tr => {
            const txt = (tr.textContent || '').toLowerCase();
            tr.style.display = txt.includes(q) ? '' : 'none';
        });
    };

    // rebind safely
    if (input._rcpHandler) input.removeEventListener('input', input._rcpHandler);
    input._rcpHandler = debounce(apply, 120);
    input.addEventListener('input', input._rcpHandler);

    // apply immediately on first bind and after reloads
    apply();
}


// Parse dd-mm-yyyy into Unix timestamp (UTC start of day)
const parseDMY = (s) => {
    const m = String(s || '').trim().match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
    if (!m) return null;
    const d = Number(m[1]),
        mo = Number(m[2]) - 1,
        y = Number(m[3]);
    const dt = new Date(Date.UTC(y, mo, d, 0, 0, 0));
    return Math.floor(dt.getTime() / 1000);
};

// Format as dd/mm/yyyy for title
function formatDMYToNice(dmy) {
    const m = String(dmy || '').match(/^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/);
    if (!m) return '';
    const d = m[1].padStart(2, '0');
    const mo = m[2].padStart(2, '0');
    const y = m[3];
    return `${d}/${mo}/${y}`;
}

// Free-typed money parse/format
function num(val) {
    const cleaned = String(val || '').replace(/[^0-9.\-]/g, '');
    const n = parseFloat(cleaned);
    return isNaN(n) ? 0 : n;
}

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

// VAT preview helper (shown only if VAT on and amount > 0)
function updateVatHelper() {
    const helper = document.getElementById('vatHelper');
    const vatOn = document.getElementById('vat_on').checked;
    const grossVal = num(document.getElementById('amount_gross').value);
    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 = `${fmt(grossVal)} gross / ${fmt(net)} net / ${fmt(vat)} vat`;
    helper.classList.remove('d-none');
}

// Hidden fields expected by server
function recomputeTotalsFields() {
    const vatOn = document.getElementById('vat_on').checked;
    const grossVal = 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);
    }
    document.getElementById('totals').value = (net || 0).toFixed(2) + '|' + vat.toFixed(2);
    document.getElementById('vat_flag').value = vatOn ? '1' : '0';
    const useEl = document.getElementById('use_vat');
    if (useEl) useEl.value = vatOn ? 'applyvat' : 'novat';
}

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

function bindMethodToggle() {
    const radios = document.querySelectorAll('input[name="method"]');
    const chequeRow = document.getElementById('chequeRow');
    radios.forEach(r => r.addEventListener('change', () => {
        chequeRow.style.display = (document.getElementById('m_cheque').checked) ? 'block' : 'none';
    }));
}

// Selected = btn-info, others = btn-secondary
function styleBtnGroupByName(name) {
    const radios = document.querySelectorAll(`input[type="radio"][name="${name}"]`);
    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();
}

// ---- Linked invoice wiring ----
let invoiceMdbSelect = null;

function syncInvoiceHidden() {
    const sel = document.getElementById('invoiceSelect');
    const hidden = document.getElementById('invoiceHidden'); // <input name="invoice">
    if (!sel || !hidden) return;
    hidden.value = sel.value || '';
}

function clearInvoiceSelect() {
    const sel = document.getElementById('invoiceSelect');
    if (!sel) return;
    sel.value = '';
    sel.dispatchEvent(new Event('change')); // refresh MDB UI
    const hidden = document.getElementById('invoiceHidden');
    if (hidden) hidden.value = '';
}

// Load list fragment and set title

// Load list fragment and set title
window.reloadList = function reloadList() {
    const start = document.getElementById('date_start')?.value || '';
    const end = document.getElementById('date_end')?.value || '';
    const q = document.getElementById('receiptSearch')?.value || '';

    const ttl = document.getElementById('rangeTitle');
    const term = q.trim();
    if (ttl) {
        ttl.textContent = term
            ? `Showing: ${formatDMYToNice(start)}  --  ${formatDMYToNice(end)} (search: "${term}")`
            : `Showing: ${formatDMYToNice(start)}  --  ${formatDMYToNice(end)}`;
    }

    // If searching, show all matches (no client-side row limiting)
    if (term) {
        window.currentReceiptRowsLimit = 'all';
        const rowsSel = document.getElementById('rowsPerPageReceipts');
        if (rowsSel) rowsSel.value = 'all';
    }

    const url = ROOT_URL + '/includes/finance/receipts/finance_rcp_data.php' +
        '?start=' + encodeURIComponent(start) +
        '&end=' + encodeURIComponent(end) +
        '&q=' + encodeURIComponent(term) +
        '&tenant=' + encodeURIComponent(TENANT_URL);

    loadContentAndExecuteScripts(url, 'receiptsList', function() {
        filterAndLimitReceiptRows();
    });
};

(function bindReceiptListControls() {
    const btnFilter = document.getElementById('btnFilter');
    const btnSearch = document.getElementById('btnSearch');
    const search = document.getElementById('receiptSearch');

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

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

function bindActions() {
    // Save
    document.getElementById('receiptForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const amt = document.getElementById('amount_gross');
        const type = document.getElementById('payee');
        const det = document.getElementById('details');
        if (!type || !type.value.trim()) {
            showResponse('warning', 'Payee is required');
            return;
        }
        if (!det || !det.value.trim()) {
            showResponse('warning', 'Details are required');
            return;
        }

        if (!amt || !amt.value.trim()) {
            showResponse('warning', 'Amount is required');
            return;
        }
        syncInvoiceHidden();

        // compute totals + date
        recomputeTotalsFields();
        const dmy = document.getElementById('rcp_date').value;
        const unix = parseDMY(dmy);
        if (!unix) {
            showResponse('danger', 'Please select a valid receipt date (dd-mm-yyyy).');
            return;
        }
        document.getElementById('date_unix').value = String(unix);

        const form = e.currentTarget;
        const payload = new URLSearchParams(new FormData(form));

        try {
            const res = await fetch(ROOT_URL + '/includes/finance/receipts/finance_receipts_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: payload
            });
            const txt = (await res.text()).trim();
            if (txt.toLowerCase().includes('success')) {
                showResponse('success', 'Your receipt has been registered successfully');
                form.reset();
                // Defaults
                document.getElementById('rcp_date').value = '<?= date('d-m-Y') ?>';
                document.getElementById('m_bacs').checked = true;
                document.getElementById('vat_on').checked = true;
                document.getElementById('chequeRow').style.display = 'none';
                clearInvoiceSelect();
                recomputeTotalsFields();
                updateVatHelper();
                reloadList();
            } else {
                showResponse('danger', txt || 'Save failed');
            }
        } catch (err) {
            showResponse('danger', 'Network error saving receipt');
        }
    });

    // Reset
    document.getElementById('btnReset').addEventListener('click', () => {
        document.getElementById('receiptForm').reset();
        document.getElementById('rcp_date').value = '<?= date('d-m-Y') ?>';
        document.getElementById('chequeRow').style.display = 'none';
        clearInvoiceSelect();
        recomputeTotalsFields();
        updateVatHelper();
        initSearchableSelects()
    });

    // Print
    document.getElementById('btnPrint')?.addEventListener('click', () => {
        const wrap = document.getElementById('receiptsList');
        const flt_from = document.getElementById('date_start').value;
        const flt_to = document.getElementById('date_end').value;
        const contentHtml = wrap ? wrap.innerHTML : '';
        if (!contentHtml.trim()) {
            showResponse('warning', 'Nothing to print');
            return;
        }
        const header = "Report of receipts: " + 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');
        }
    });

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

// Init
document.addEventListener('DOMContentLoaded', function() {
    // start with sidebar closed
    document.body.classList.add('sidebar-hidden');

    bindMethodToggle();
    bindValueRecalc();
    styleBtnGroupByName('method');
    styleBtnGroupByName('vatMode');
    recomputeTotalsFields();
    updateVatHelper();

    // Initialise MDB Select for linked invoice, keep hidden input in sync
    const invSel = document.getElementById('invoiceSelect');
    if (invSel) {
        invoiceMdbSelect = new mdb.Select(invSel, {
            filter: true,
            container: 'body'
        });
        invSel.addEventListener('change', syncInvoiceHidden);
        syncInvoiceHidden(); // initial hidden value
    }

    // Toggle sidebar button label
    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';
    });

    // Bind actions and initial list
    bindActions();
    const filterBtn = document.getElementById('btnFilter');
    if (filterBtn) filterBtn.addEventListener('click', window.reloadList);
    window.reloadList(); // triggers attachReceiptsFilter() in callback

    const list = document.getElementById('receiptsList');
    if (list) {
        const mo = new MutationObserver(() => {
            // reattach and reapply whenever list content changes
            attachReceiptsFilter();
            if (LAST_RECEIPT_QUERY) {
                const input = document.getElementById('receiptSearch');
                if (input) input.value = LAST_RECEIPT_QUERY;
            }
        });
        mo.observe(list, {
            childList: true,
            subtree: true
        });
    }
});

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


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