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

        <!-- 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-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"
                           data-mdb-format="dd-mm-yyyy"
                           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 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-dark" 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;

window.addEventListener("DOMContentLoaded", function() {
    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);
            });
        });
});

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;

    fetch(`${ROOT_URL}/includes/finance/invoices/load_invoice_data.php?clientnumber=${clientId}&tenant=${TENANT_URL}`)
        .then(res => res.json())
        .then(data => {
            document.getElementById('invoiceNumber').value = data.invoicenumber || '';
            document.getElementById('billingInfo').innerHTML = data.billing;
            document.getElementById('accountInfo').innerHTML = data.account;
            document.getElementById('invoiceContainer').style.display = 'block';

            const brokerNum = parseInt(data.broker_number);
            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;
            window.brokerNumber = parseInt(data.broker_number || 0);
            window.agentNumber = parseInt(data.agent_number || 0);
            window.isBroker = data.is_broker === true;
            window.isAgent = data.is_agent === true;
            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 = `<p>Are you sure this invoice is complete and ready to submit?</p>`;
    loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Confirm Invoice Submission', 'cancelConfirm', () => {
        killModal('popupBox');
        applyInvoice();
    });
}

function applyInvoice() {
    const clientId = parseInt(document.getElementById('clientSelect').value);
    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';
    let brokerCom = 0;
    let agentCom = 0;

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


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

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

                // Use the same agent/broker IDs again here
                let rtype = 'client';
                let brokerCom = 0;
                let agentCom = 0;

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

                const postData = new URLSearchParams();
                postData.append('invNo', invNo);
                postData.append('clientnumber', clientId);
                postData.append('rtype', rtype);
                postData.append('brokerCom', brokerCom);
                postData.append('agentCom', agentCom);
                if (window.isBroker) postData.append('broker_number', brokerId);
                if (window.isAgent) postData.append('agent_number', agentId);
                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(response => response.text())
                    .then(() => {
                        //window.location.href = `index.php?t=includes/finance&p=finance_unpaid.php`;
                    })
                    .catch(err => {
                        showResponse('danger', 'Invoice saved, but redirect 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);
}

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);
    if (!notes || isNaN(fee) || isNaN(qty)) {
        showModalToast("Both Fee and Notes 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">1</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);
    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 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) {
        let comAmount = 0;
        if (commissionData.type === 0) {
            comAmount = grand * (commissionData.value / 100);
        } else {
            comAmount = commissionData.value;
        }
        window.calculatedCommissionAmount = comAmount.toFixed(2);
        comInput.value = `${commissionData.label} = ${formatGBP(comAmount)}`;
    } else {
        comInput.value = '';
    }
}

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Finance <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">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>