<?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>
        </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 (Net) -->
                        <div class="mt-2">
                            <label for="amount_net">Amount (net)</label>
                            <input
                                   type="text"
                                   id="amount_net"
                                   name="amount_net"
                                   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-4">
                            <label class="control-label" for="txtSearch">Search</label>
                            <input id="txtSearch" type="text" class="form-control" placeholder="Payee, employee or details">
                        </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 amountNetEl = document.getElementById('amount_net');
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 (!amountNetEl || !totalsEl) return;

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

    if (isVatApplied()) {
        if (!userVatOverride) {
            vat = round2(net * (rate / 100));
            if (vatAmountEl) {
                vatAmountEl.value = vat.toFixed(2);
            }
            if (vatStandalone) {
                vatStandalone.value = vat.toFixed(2);
            }
        } else {
            vat = parseNum(vatAmountEl?.value || 0);
        }

        const gross = round2(net + vat);

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

        if (vatHelperEl) {
            if (vat > 0.0001) {
                vatHelperEl.textContent =
                    `£${net.toFixed(2)} net / £${vat.toFixed(2)} VAT / £${gross.toFixed(2)} gross`;
            } 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';
    }

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


if (amountNetEl) {
    amountNetEl.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/gross from the UI
    const net = parseNum(amountNetEl?.value || 0);

    const ratePct = getVatRatePercent(); // 20 for 0.20 etc
    let vat = 0;

    if (isVatApplied()) {
        vat = userVatOverride ? parseNum(vatAmountEl?.value || 0) : round2(net * (ratePct / 100));
    }

    const gross = round2(net + vat);

    // 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 -----
async function loadList(from, to) {
    const title = document.getElementById('rangeTitle');
    if (title) title.textContent = `Showing ${from} to ${to}`;
    const qs = new URLSearchParams({
        payment_type: 'Outgoings',
        start: from || '',
        end: to || '',
        tenant: TENANT_URL,
        _ts: Date.now()
    }).toString();

    const url = ROOT_URL + '/includes/finance/outgoings/finance_out_data.php?' + qs;
    loadContentAndExecuteScripts(url, 'expenseList', () => {
        setupFragmentEnhancements();
    });
}
window.reloadList = function() {
    const from = document.getElementById('flt_from')?.value || '01-01-1970';
    const to = document.getElementById('flt_to')?.value || '<?= date('d-m-Y') ?>';
    loadList(from, to);
};
document.getElementById('btnFilter')?.addEventListener('click', () => reloadList());
document.addEventListener('DOMContentLoaded', reloadList);

// Combined search + row-limit logic
window.filterAndLimitOutgoingRows = function() {
    const search = document.getElementById('txtSearch');
    const table = document.querySelector('#expenseData table');
    if (!search || !table) return;
    const tbody = table.querySelector('tbody');
    const q = search.value.trim().toLowerCase();
    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 = q ? 'none' : '';
            return;
        }

        const matches = !q || tr.textContent.toLowerCase().includes(q);
        if (!matches) {
            tr.style.display = 'none';
            return;
        }

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

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

function setupFragmentEnhancements() {
    const search = document.getElementById('txtSearch');
    if (search) {
        search.oninput = () => {
            window.filterAndLimitOutgoingRows();
        };
    }
    // Apply row limit immediately on load
    window.filterAndLimitOutgoingRows();
}

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

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