<div class="note note-light mb-3">
    <strong>Invoices:</strong> Use the client selector to start a new invoice. <small><i>If you need to create an
            invoice that is not for a registered client, then use the <a
               href="index.php?t=includes/finance&p=finance_invoice_blank.php">blank
                invoice</a> system.</i></small>
</div>

<div class="container-fluid" id="invoiceApp">
    <div class="row mb-4 align-items-end">
        <!-- Select Client -->
        <div class="col-md-5">
            <div class="input-group">
                <span for="clientSelect" class="input-group-text text-light bg-info " data-mdb-tooltip-init
                      data-mdb-placement="top" title="Select the client">Client</span>
                <select class="form-select filterSelect d-inline-block py-0" id="clientSelect"
                        onchange="loadClientData()">
                    <option value="">Select a Client</option>
                </select>
            </div>
        </div>

        <!-- Client setup incomplete message -->
        <div class="col-md-10 mt-5" id="clientSetupMsgCol" style="display:none">
            <div class="alert alert-warning d-flex justify-content-between align-items-center mb-0">
                <div>
                    <i class="fad fa-exclamation-triangle me-2"></i>
                    <strong>Client setup incomplete.</strong>
                    Contract fee is not set, so invoice quick-load is unavailable.
                </div>

                <div class="d-flex gap-2">
                    <button
                        type="button"
                        id="btnOverrideNoFee"
                        class="btn btn-sm btn-warning"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Continue without contract fee (manual invoice)">
                        <i class="fad fa-triangle-exclamation me-1"></i> Override
                    </button>

                    <a id="clientEditLink" class="btn btn-sm btn-secondary"
                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                       title="Edit the selected client record"
                       href="#">
                        <i class="fad fa-pen-to-square me-1"></i> Edit client
                    </a>
                </div>
            </div>
        </div>

        <!-- Invoice Number -->
        <div class="col-md-2" id="invoiceNumberBlock" style="display:none">
            <div class="input-group">
                <span for="invoiceNumber" class="input-group-text text-light bg-info " data-mdb-tooltip-init
                      data-mdb-placement="top" title="Invoice number">Invoice No</span>
                <input type="text" id="invoiceNumber" class="form-control d-inline-block w-50" readonly />
            </div>
        </div>

        <!-- Invoice Date -->
        <div class="col-md-2" id="invoiceDateBlock" style="display:none">
            <div class="date-picker d-inline-block w-100" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                <div class="input-group">
                    <span for="invoiceDate" class="input-group-text text-light bg-info " data-mdb-tooltip-init
                          data-mdb-placement="top" title="Date of invoice">Invoice Date</span>
                    <input class="form-control d-inline-block w-50" data-mdb-confirmDateOnSelect
                           data-mdb-toggle="datepicker" type="text" name="invoiceDate"
                           id="invoiceDate" value="<?= date('d-m-Y') ?>" />
                </div>
            </div>
        </div>

        <div class="col-md-3" id="purchaseOrderBlock" style="display:none">
            <div class="input-group">
                <span for="purchaseOrder" class="input-group-text text-light bg-info " data-mdb-tooltip-init
                      data-mdb-placement="top" title="Purchase Order Number">PO Number</span>
                <input type="text" id="purchaseOrder" name="purchaseOrder" class="form-control d-inline-block w-75" />
            </div>
        </div>

    </div>

    <div id="invoiceContainer" style="display:none">
        <div class="row mb-3">
            <div class="col-3">
                <div class="card">
                    <div class="card-header bg-dark text-light">Billing Information</div>
                    <div class="card-body" id="billingInfo"></div>
                </div>
            </div>

            <div class="col-3">
                <div class="card">
                    <div class="card-header bg-dark text-light">Account Information</div>
                    <div class="card-body" id="accountInfo"></div>
                </div>
            </div>

            <div class="col-6">
                <div class="card">
                    <div class="card-header bg-dark text-light d-flex justify-content-between">
                        Invoice Items
                        <button id="btnLoadContractFee" class="btn btn-sm btn-secondary" onclick="loadContractFee()" data-mdb-tooltip-init
                                data-mdb-placement="bottom" data-mdb-trigger="hover" title="Quick load contract fee">Load
                            Contract Fee</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm table-bordered" id="invoiceItemsTable">
                            <thead class="table-dark">
                                <tr>
                                    <th>Service</th>
                                    <th>Notes</th>
                                    <th width="40">Fee</th>
                                    <th width="40">Qty</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="invoiceItems"></tbody>
                        </table>
                        <button class="btn btn-secondary" onclick="openNewItemModal()" data-mdb-tooltip-init
                                data-mdb-placement="bottom" data-mdb-trigger="hover" title="Add new entry"><i
                               class="fad fa-plus"></i></button>
                    </div>
                </div>
            </div>
        </div>

        <div class="row justify-content-end mt-n5">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <div class="mb-2 d-flex justify-content-between align-items-center">
                            <label class="form-label mb-0">Subtotal (ex VAT)</label>
                            <input type="text" class="form-control form-control-sm text-end w-auto" id="invoiceTotal"
                                   readonly />
                        </div>
                        <div class="mb-2 d-flex justify-content-between align-items-center">
                            <label class="form-label mb-0">VAT</label>
                            <input type="text" class="form-control form-control-sm text-end w-auto" id="vatAmount"
                                   readonly />
                        </div>
                        <div class="mb-2 d-flex justify-content-between align-items-center">
                            <label class="form-label mb-0">Grand Total</label>
                            <input type="text" class="form-control form-control-sm text-end w-auto" id="grandTotal"
                                   readonly />
                        </div>
                        <div class="mb-2 justify-content-between align-items-center d-none" id="commissionBlock">

                            <label class="form-label mb-0">Broker Commission</label>
                            <input type="text" class="form-control form-control-sm text-end w-auto" id="commissionValue"
                                   readonly />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row mt-4">
            <div class="col-md-12">
                <label for="invoiceNotes" class="form-label"><strong>Invoice Notes / Comments</strong></label>
                <textarea id="invoiceNotes" class="form-control" rows="3" placeholder="Optional notes..."></textarea>
            </div>
        </div>
    </div>
</div>

<script>
let invoiceHasUnsavedChanges = false;
let lastLoadedClientId = null;
let commissionData = null;

// Override state
let contractFeeOverrideUsed = false;
let noFeeClientId = null;

clearClientSetupIncomplete();

function resetClientTypeGlobals() {
    window.brokerNumber = 0;
    window.agentNumber = 0;
    window.isBroker = false;
    window.isAgent = false;
}

function setClientTypeGlobalsFromData(data) {
    // Always set these as soon as we have client data (including "no fee" clients)
    window.brokerNumber = parseInt(data?.broker_number || 0, 10) || 0;
    window.agentNumber  = parseInt(data?.agent_number  || 0, 10) || 0;
    window.isBroker     = data?.is_broker === true;
    window.isAgent      = data?.is_agent === true;
}

function setClientSetupIncomplete(clientId) {
    noFeeClientId = clientId || null;
    contractFeeOverrideUsed = false;

    // Hide main invoice UI blocks
    const hideIds = ['invoiceNumberBlock', 'invoiceDateBlock', 'purchaseOrderBlock', 'invoiceContainer'];
    hideIds.forEach((id) => {
        const el = document.getElementById(id);
        if (el) el.style.display = 'none';
    });

    // Disable quick-load contract fee button (keep visible while blocked)
    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee) {
        btnFee.disabled = true;
        btnFee.style.display = '';
    }

    // Clear footer controls
    const footerControls = document.getElementById('footerControls');
    if (footerControls) footerControls.innerHTML = '';

    // Show setup message + set edit link
    const msgCol = document.getElementById('clientSetupMsgCol');
    const editLink = document.getElementById('clientEditLink');

    if (editLink && clientId) {
        editLink.href = `index.php?t=includes/master&p=client.php&clientnumber=${encodeURIComponent(clientId)}&view=edit`;
    }

    if (msgCol) msgCol.style.display = 'block';

    lastLoadedClientId = clientId;
    invoiceHasUnsavedChanges = false;

    if (typeof showResponse === 'function') {
        showResponse('warning', 'Client setup incomplete: contract fee is not set.');
    }
}

function clearClientSetupIncomplete() {
    const msgCol = document.getElementById('clientSetupMsgCol');
    if (msgCol) msgCol.style.display = 'none';

    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee) {
        btnFee.disabled = false;
        btnFee.style.display = '';
    }

    contractFeeOverrideUsed = false;
    noFeeClientId = null;
}

function applyNoFeeOverride() {
    if (!noFeeClientId) return;

    contractFeeOverrideUsed = true;

    // Remove the alert (requirement)
    const msgCol = document.getElementById('clientSetupMsgCol');
    if (msgCol) msgCol.style.display = 'none';

    // Keep Load Contract Fee hidden (requirement)
    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee) {
        btnFee.disabled = true;
        btnFee.style.display = 'none';
    }

    // Show invoice UI blocks so user can proceed manually
    ['invoiceNumberBlock', 'invoiceDateBlock', 'purchaseOrderBlock'].forEach((id) => {
        const el = document.getElementById(id);
        if (el) el.style.display = 'block';
    });

    const container = document.getElementById('invoiceContainer');
    if (container) container.style.display = 'block';

    // Restore footer "Create Invoice" button
    const footerControls = document.getElementById('footerControls');
    if (footerControls) {
        footerControls.innerHTML = `
            <button id="commitBtn" class="btn btn-secondary" onclick="triggerSaveValidation()">
                Create Invoice
            </button>`;
    }

    invoiceHasUnsavedChanges = false;

    if (typeof showResponse === 'function') {
        showResponse('warning', 'Continuing without a contract fee. Quick-load remains unavailable.');
    }
}

window.addEventListener("DOMContentLoaded", function() {
    // Wire override button safely
    const overrideBtn = document.getElementById('btnOverrideNoFee');
    if (overrideBtn) {
        overrideBtn.addEventListener('click', applyNoFeeOverride);
    }

    const dest = `${ROOT_URL}/includes/finance/invoices/load_clients.php?tenant=${TENANT_URL}`;
    fetch(dest)
        .then((res) => res.json())
        .then((clients) => {
            const select = document.getElementById("clientSelect");
            clients.forEach((c) => {
                const opt = document.createElement("option");
                opt.value = c.clientnumber;
                opt.textContent = `${c.company} [${c.postcode}]`;
                select.appendChild(opt);
            });
        });

    var mySelect = new mdb.Select(document.getElementById('clientSelect'), {
        filter: true,
        container: "body"
    });
});

function handleBeforeUnload(e) {
    if (invoiceHasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
    }
}

function loadClientData() {
    const clientId = document.getElementById('clientSelect').value;
    if (!clientId) return;

    if (lastLoadedClientId && invoiceHasUnsavedChanges) {
        const html =
            `<p>You have unsaved changes. Switching clients will discard them.<br><br>Do you want to continue?</p>`;
        loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Unsaved Changes Warning', 'cancelConfirm', () => {
            killModal('popupBox');
            actuallyLoadClientData(clientId);
        });
    } else {
        actuallyLoadClientData(clientId);
    }
}

function actuallyLoadClientData(clientId) {
    // Reset UI
    document.getElementById('invoiceNumber').value = '';
    document.getElementById('invoiceItems').innerHTML = '';
    document.getElementById('billingInfo').innerHTML = '';
    document.getElementById('accountInfo').innerHTML = '';
    document.getElementById('invoiceTotal').value = '';
    document.getElementById('vatAmount').value = '';
    document.getElementById('grandTotal').value = '';
    document.getElementById('invoiceNotes').value = '';
    document.getElementById('commissionValue').value = '';
    document.getElementById('commissionBlock').classList.add('d-none');
    document.getElementById('commissionBlock').classList.remove('d-flex');
    document.getElementById('invoiceContainer').style.display = 'none';
    document.getElementById('purchaseOrder').value = '';
    commissionData = null;

    // Reset override for new selection
    contractFeeOverrideUsed = false;
    noFeeClientId = null;

    // IMPORTANT: reset globals so we don't carry over previous client's type
    resetClientTypeGlobals();

    // Ensure Load Contract Fee is visible again for normal clients
    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee) {
        btnFee.disabled = false;
        btnFee.style.display = '';
    }

    fetch(`${ROOT_URL}/includes/finance/invoices/load_invoice_data.php?clientnumber=${clientId}&tenant=${TENANT_URL}`)
        .then(res => res.text())
        .then(raw => {
            let data = null;
            try {
                data = JSON.parse(raw);
            } catch (e) {
                data = null;
            }
            if (!data || typeof data !== 'object') {
                setClientSetupIncomplete(clientId);
                return;
            }

            // FIX: set broker/agent state immediately (even when no contract fee)
            setClientTypeGlobalsFromData(data);

            // Pre-fill basics regardless (so override can proceed cleanly)
            document.getElementById('invoiceNumber').value = data.invoicenumber || '';
            document.getElementById('billingInfo').innerHTML = data.billing || '';
            document.getElementById('accountInfo').innerHTML = data.account || '';

            // If the client has no contract fee, block UI and show setup message + override
            if (data.has_contract_fee !== true) {
                setClientSetupIncomplete(clientId);
                return;
            }

            clearClientSetupIncomplete();

            document.getElementById('invoiceContainer').style.display = 'block';

            const brokerNum = parseInt(data.broker_number, 10);
            const block = document.getElementById('commissionBlock');

            if (!isNaN(brokerNum) && brokerNum > 0) {
                commissionData = data.commission || null;
                block.classList.remove('d-none');
                block.classList.add('d-flex');
            } else {
                commissionData = null;
                block.classList.remove('d-flex');
                block.classList.add('d-none');
            }

            document.getElementById('invoiceNumberBlock').style.display = 'block';
            document.getElementById('invoiceDateBlock').style.display = 'block';
            document.getElementById('purchaseOrderBlock').style.display = 'block';
            lastLoadedClientId = clientId;
            invoiceHasUnsavedChanges = false;

            calculateInvoiceTotal();

            const footerControls = document.getElementById('footerControls');
            if (footerControls) {
                footerControls.innerHTML = `
                    <button id="commitBtn" class="btn btn-secondary" onclick="triggerSaveValidation()">
                        Create Invoice
                    </button>`;
            }

            document.querySelectorAll('#invoiceApp input, #invoiceApp select, #invoiceApp textarea').forEach((el) => {
                el.addEventListener('input', () => {
                    invoiceHasUnsavedChanges = true;
                });
            });

            const itemObserver = new MutationObserver(() => {
                invoiceHasUnsavedChanges = true;
            });
            itemObserver.observe(document.getElementById('invoiceItems'), {
                childList: true,
                subtree: true,
            });
        });

    window.removeEventListener('beforeunload', handleBeforeUnload);
    window.addEventListener('beforeunload', handleBeforeUnload);
}

function triggerSaveValidation() {
    const invoiceItems = document.querySelectorAll('#invoiceItems tr');

    if (invoiceItems.length === 0) {
        const html =
            `<p class="text-danger"><i class="fad fa-exclamation-triangle me-2"></i> You must add at least one invoice item before submitting.</p>`;
        loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Validation Error', 'close');
        return;
    }

    const html = `<h5 class="text-center">Are you sure this invoice is complete and ready to submit?</h5>`;
    loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Confirm Invoice Submission', 'cancelConfirm', () => {
        killModal('popupBox');
        applyInvoice();
    });
}

function applyInvoice() {
    const clientId = parseInt(document.getElementById('clientSelect').value, 10);
    if (!clientId) return;

    const invoiceDate = document.getElementById('invoiceDate').value.trim();
    const dateTimestamp = convertDateToTimestamp(invoiceDate);
    const dueTimestamp = dateTimestamp + 30 * 24 * 60 * 60;
    const poNumber = document.getElementById("purchaseOrder")?.value.trim() || "";
    const subtotal = parseFloat(document.getElementById('invoiceTotal').value.replace(/[^0-9.-]+/g, '')) || 0;
    const vat = parseFloat(document.getElementById('vatAmount').value.replace(/[^0-9.-]+/g, '')) || 0;
    const vatRate = parseFloat(<?= getCompanyDetails('vatrate') ?>);

    const items = [];
    document.querySelectorAll('#invoiceItems tr').forEach(row => {
        const service = row.querySelector('.service')?.textContent.trim() || '';
        const notes = row.querySelector('.notes')?.textContent.trim() || '';
        const rate = row.querySelector('.fee')?.textContent.trim() || '0';
        const quantity = row.querySelector('.qty')?.textContent.trim() || '1';
        if (service) {
            items.push({ service, notes, rate, quantity });
        }
    });

    const invoiceNotes = document.getElementById('invoiceNotes')?.value || '';
    const addressText = document.querySelector('#billingInfo')?.innerText || '';
    const addressData = {
        client_name: clientId,
        billing_name: addressText.match(/Name:\s+(.*)/)?.[1] || '',
        billing1: addressText.match(/Billing1:\s+(.*)/)?.[1] || '',
        billing2: addressText.match(/Billing2:\s+(.*)/)?.[1] || '',
        billing_town: addressText.match(/Town:\s+(.*)/)?.[1] || '',
        billing_county: addressText.match(/County:\s+(.*)/)?.[1] || '',
        billing_postcode: addressText.match(/Postcode:\s+(.*)/)?.[1] || '',
        email: '',
        contract_number: document.querySelector('#accountInfo')?.innerText.match(/Contract:\s+(.*)/)?.[1] || '',
        commission: commissionData?.value?.toString() || '0.00'
    };

    const agentId = window.agentNumber || 0;
    const brokerId = window.brokerNumber || 0;
    let rtype = 'client';

    if (window.isBroker) {
        rtype = 'broker';
    } else if (window.isAgent) {
        rtype = 'agent';
    }

    const formData = new FormData();
    formData.append('clientnumber', clientId);
    if (window.isBroker) formData.append('broker_number', brokerId);
    if (window.isAgent) formData.append('agent_number', agentId);
    formData.append('address', JSON.stringify(addressData));
    formData.append('items', JSON.stringify(items));
    formData.append('totals', `${subtotal}|${vat}`);
    formData.append('vatrate', vatRate);
    formData.append('date', dateTimestamp);
    formData.append('date_due', dueTimestamp);
    formData.append('date_paid', 0);
    formData.append('sent', 0);
    formData.append('status', 0);
    formData.append('payment_type', '');
    formData.append('chequeNo', 0);
    formData.append('commission', window.calculatedCommissionAmount || '0.00');
    formData.append('commission_paid', 0);
    formData.append('filter', 'Contract Renewal');
    formData.append('target', rtype);
    formData.append('invoiceNotes', invoiceNotes);
    formData.append("purchaseOrder", poNumber);
    formData.append('tenant', TENANT_URL);

    fetch(`${ROOT_URL}/includes/finance/invoices/save_invoice.php`, { method: 'POST', body: formData })
        .then(res => res.json())
        .then(json => {
            if (json.status === 'success') {
    showResponse('success', `Invoice #${json.invoice_id} saved successfully.`);
    invoiceHasUnsavedChanges = false;

    // CAPTURE TYPE STATE BEFORE resetInvoiceForm() clears globals
    const isBrokerNow = window.isBroker === true;
    const isAgentNow  = window.isAgent === true;
    const brokerIdNow = window.brokerNumber || 0;
    const agentIdNow  = window.agentNumber || 0;

    const invNo = json.invoice_id.toString().replace(/^[0|\D]*/, '');

    let rtype2 = 'client';
    let brokerCom2 = 0;
    let agentCom2 = 0;

    if (isBrokerNow) {
        rtype2 = 'broker';
        brokerCom2 = 1;
    } else if (isAgentNow) {
        rtype2 = 'agent';
        agentCom2 = 1;
    }

    const postData = new URLSearchParams();
    postData.append('invNo', invNo);
    postData.append('clientnumber', clientId);
    postData.append('rtype', rtype2);
    postData.append('brokerCom', brokerCom2);
    postData.append('agentCom', agentCom2);
    if (isBrokerNow) postData.append('broker_number', brokerIdNow);
    if (isAgentNow)  postData.append('agent_number', agentIdNow);
    postData.append('tenant', TENANT_URL);

    fetch(`${ROOT_URL}/includes/engines/invoice.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: postData.toString()
    })
    .then(() => {
        // reset AFTER engine generation so we don't lose state
        resetInvoiceForm();
        invoiceHasUnsavedChanges = false;
        setTimeout(() => {
            window.location.href = `index.php?t=includes/finance&p=finance_invoices.php`;
        }, 600);
    })
    .catch(err => {
        // still reset the form to avoid stuck UI
        resetInvoiceForm();
        showResponse('danger', 'Invoice saved, but PDF generation failed: ' + err.message);
    });

} else {
    showResponse('danger', `Error saving invoice: ${json.message || 'Unknown error'}`);
}

        })
        .catch(err => {
            showResponse('danger', `Error saving invoice: ${err.message}`);
        });
}

function resetInvoiceForm() {
    document.getElementById('invoiceNumber').value = '';
    document.getElementById('invoiceItems').innerHTML = '';
    document.getElementById('billingInfo').innerHTML = '';
    document.getElementById('accountInfo').innerHTML = '';
    document.getElementById('invoiceTotal').value = '';
    document.getElementById('vatAmount').value = '';
    document.getElementById('grandTotal').value = '';
    document.getElementById('commissionValue').value = '';
    document.getElementById('commissionBlock').classList.remove('d-flex');
    document.getElementById('commissionBlock').classList.add('d-none');
    document.getElementById('invoiceContainer').style.display = 'none';
    document.getElementById('clientSelect').value = '';
    document.getElementById('invoiceNumberBlock').style.display = 'none';
    document.getElementById('invoiceDateBlock').style.display = 'none';
    document.getElementById('purchaseOrderBlock').style.display = 'none';
    invoiceHasUnsavedChanges = false;
    lastLoadedClientId = null;
    window.removeEventListener('beforeunload', handleBeforeUnload);

    // Reset override states
    contractFeeOverrideUsed = false;
    noFeeClientId = null;

    // Reset client type globals
    resetClientTypeGlobals();

    // Ensure contract fee button returns to default state for next invoice
    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee) {
        btnFee.disabled = false;
        btnFee.style.display = '';
    }

    const msgCol = document.getElementById('clientSetupMsgCol');
    if (msgCol) msgCol.style.display = 'none';
}

function convertDateToTimestamp(dateStr) {
    const parts = dateStr.split('-');
    const date = new Date(parts[2], parts[1] - 1, parts[0]);
    return Math.floor(date.getTime() / 1000);
}

function accountInfoInner(label) {
    const match = document.querySelector('#accountInfo')?.innerText.match(new RegExp(label + ':\\s+(.*)'));
    return match ? match[1] : '';
}

function openNewItemModal() {
    const dest =
        `${ROOT_URL}/includes/finance/invoices/new_item_modal.php?tenant=${TENANT_URL}&clientnumber=${lastLoadedClientId}`;
    loadModalContent(dest, 'newItemModal', 'modal-lg', 1060, 'true', 'New Item', 'cancelConfirm', submitNewInvoiceItem);
}

function submitNewInvoiceItem() {
    const form = document.getElementById('newInvoiceItemForm');
    const service = form.service.value.trim();
    const notes = form.notes.value.trim();
    const fee = parseFloat(form.fee.value);
    const qty = parseInt(form.qty.value, 10);
    if (!notes || isNaN(fee) || isNaN(qty) || qty < 1) {
        showModalToast("Fee, Notes and a valid Quantity are required.");
        return;
    }

    const row = document.createElement('tr');
    row.innerHTML = `
        <td class="align-middle service" contenteditable="true" oninput="calculateInvoiceTotal()">${service}</td>
        <td class="align-middle notes" contenteditable="true">${notes}</td>
        <td class="align-middle fee" contenteditable="true" oninput="calculateInvoiceTotal()">${fee.toFixed(2)}</td>
        <td class="align-middle qty-controls">
            <div class="d-flex align-items-center">
                <button type="button" class="btn btn-sm btn-secondary me-1" onclick="adjustQty(this, -1)"><i class="fad fa-minus"></i></button>
                <span class="qty">${qty}</span>
                <button type="button" class="btn btn-sm btn-secondary ms-1" onclick="adjustQty(this, 1)"><i class="fad fa-plus"></i></button>
            </div>
        </td>
        <td class="align-middle text-center">
            <button type="button" class="btn btn-sm btn-danger" onclick="confirmRemoveRow(this)" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="Remove entry">
                <i class="fad fa-trash"></i>
            </button>
        </td>
    `;
    document.getElementById('invoiceItems').appendChild(row);
    calculateInvoiceTotal();
    killModal('newItemModal');
}

function adjustQty(button, delta) {
    const qtySpan = button.parentElement.querySelector('.qty');
    let current = parseInt(qtySpan.textContent, 10);
    current += delta;
    if (current < 1) current = 1;
    qtySpan.textContent = current;
    calculateInvoiceTotal();
}

function confirmRemoveRow(button) {
    const row = button.closest('tr');
    const serviceName = row.querySelector('.service')?.textContent || 'this item';
    const html = `<p>Are you sure you want to remove the entry: <strong>${serviceName}</strong>?</p>`;
    loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Confirm Removal', 'cancelConfirm', () => {
        row.remove();
        calculateInvoiceTotal();
        killModal('popupBox');
    });
}

function loadContractFee() {
    const btnFee = document.getElementById('btnLoadContractFee');
    if (btnFee && (btnFee.disabled || btnFee.style.display === 'none')) {
        if (typeof showResponse === 'function') {
            showResponse('warning', 'This client has no contract fee set. Edit the client record or add invoice items manually.');
        }
        return;
    }
    const clientId = document.getElementById('clientSelect').value;
    const dest =
        `${ROOT_URL}/includes/finance/invoices/load_contract_fee.php?clientnumber=${clientId}&tenant=${TENANT_URL}`;
    fetch(dest)
        .then(res => res.text())
        .then(html => {
            const container = document.getElementById('invoiceItems');
            const temp = document.createElement('tbody');
            temp.innerHTML = html;
            temp.querySelectorAll('tr').forEach(tr => container.appendChild(tr));
            calculateInvoiceTotal();
        });
}

function calculateInvoiceTotal() {
    let subtotal = 0;
    document.querySelectorAll('#invoiceItems tr').forEach(row => {
        const feeText = row.querySelector('.fee')?.textContent || "0";
        const qtyText = row.querySelector('.qty')?.textContent || "1";
        const fee = parseFloat(feeText.replace(/,/g, '').trim()) || 0;
        const qty = parseFloat(qtyText.replace(/,/g, '').trim()) || 1;
        subtotal += fee * qty;
    });

    const vatRate = parseFloat(<?= getCompanyDetails('vatrate') ?>);
    const vat = subtotal * vatRate;
    const grand = subtotal + vat;

    const formatGBP = (val) =>
        `${val.toLocaleString('en-GB', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

    document.getElementById('invoiceTotal').value = formatGBP(subtotal);
    document.getElementById('vatAmount').value = formatGBP(vat);
    document.getElementById('grandTotal').value = formatGBP(grand);

    const comInput = document.getElementById('commissionValue');
    if (commissionData) {
        const val = parseFloat(commissionData.value) || 0;
        let comAmount = 0;

        // type === 0 => percentage; now based on NET subtotal
        if (commissionData.type === 0) {
            comAmount = subtotal * (val / 100);
        } else {
            comAmount = val; // flat amount unchanged
        }

        window.calculatedCommissionAmount = comAmount.toFixed(2);
        comInput.value = `${commissionData.label} = ${formatGBP(comAmount)}`;
    } else {
        comInput.value = '';
        window.calculatedCommissionAmount = '0.00';
    }
}

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">Finance - Invoices</a> <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">New Invoice</li>';
</script>
