<?php

// Company VAT rate for totals calc
$vatRate = getCompanyDetails('vatrate'); // numeric like 0.20
?>
<div class="note note-light mb-3">
    <strong>Blank invoice:</strong> Use this when the invoice is not tied to a registered client. You may optionally
    select a client to prefill billing, then edit as needed.
</div>

<div class="container-fluid" id="invoiceAppBlank">
    <div class="row mb-4 align-items-end">
        <!-- Optional 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 client to prefill billing (optional)">Client</span>
                <select class="form-select filterSelect d-inline-block py-0" id="clientSelect"></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">
            <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>

        <!-- PO Number -->
        <div class="col-md-3">
            <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>

    <!-- Main Blocks -->
    <div class="row mb-3">
        <!-- Billing Information (manual) -->
        <div class="col-12 col-md-4">
            <div class="card">
                <div class="card-header bg-dark text-light">Billing Information</div>
                <div class="card-body">
                    <div class="mb-2">
                        <label class="form-label">Name</label>
                        <input type="text" id="billing_name" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Billing1</label>
                        <input type="text" id="billing1" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Billing2</label>
                        <input type="text" id="billing2" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Town</label>
                        <input type="text" id="billing_town" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">County</label>
                        <input type="text" id="billing_county" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Postcode</label>
                        <input type="text" id="billing_postcode" class="form-control form-control-sm" />
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Contact Email</label>
                        <input type="email" id="billing_email" class="form-control form-control-sm" />
                    </div>
                </div>
            </div>
        </div>

        <!-- Items -->
        <div class="col-12 col-md-8">
            <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" id="addItemBtn" 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 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>
                </div>
            </div>
        </div>
    </div>

    <!-- Totals -->
    <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>
            </div>
        </div>
    </div>

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

<script>
// ===== State =====
let invoiceHasUnsavedChanges = false;
let lastLoadedClientId = 0; // optional client used only to prefill
const VAT_RATE = parseFloat(<?= json_encode($vatRate) ?>) || 0;

// ===== Init =====
document.addEventListener('DOMContentLoaded', () => {
    // Breadcrumb
    const nav = document.getElementById('navBox');
    if (nav) {
        nav.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">Blank Invoice</li>';
    }

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

    // Load optional clients
    populateClientSelect();

    // Fetch next invoice number (optional visual)
    fetchNextInvoiceNumber();

    // Wire add item button
    document.getElementById('addItemBtn').addEventListener('click', openNewItemModal);

    // Unsaved changes tracking
    document.querySelectorAll('#invoiceAppBlank input, #invoiceAppBlank textarea, #invoiceAppBlank select').forEach(el => {
        el.addEventListener('input', () => invoiceHasUnsavedChanges = true);
    });
    const itemsObserver = new MutationObserver(() => invoiceHasUnsavedChanges = true);
    itemsObserver.observe(document.getElementById('invoiceItems'), {
        childList: true,
        subtree: true
    });

    window.addEventListener('beforeunload', (e) => {
        if (invoiceHasUnsavedChanges) {
            e.preventDefault();
            e.returnValue = '';
        }
    });
});

// ===== Client Prefill =====
function populateClientSelect() {
    const sel = document.getElementById('clientSelect');
    sel.innerHTML = '<option value="">Select a Client (optional)</option>';

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

            new mdb.Select(sel, {
                filter: true,
                container: 'body'
            });

            sel.addEventListener('change', () => {
                const id = parseInt(sel.value || '0', 10);
                if (!id) {
                    lastLoadedClientId = 0;

                    clearBillingFields();
                    return;
                }
                prefillFromClient(id);
            });
        })
        .catch(() => {
            /* silent */
        });
}

function prefillFromClient(clientId) {
    const url = `${ROOT_URL}/includes/finance/invoices/load_invoice_data.php?clientnumber=${clientId}&tenant=${TENANT_URL}`;
    fetch(url)
        .then(r => r.json())
        .then(data => {
            lastLoadedClientId = clientId;

            // ---- Helpers ----
            const escapeRe = (s) => s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

            function extractBetween(text, label, nextLabels) {
                const la = escapeRe(label) + '\\s*:\\s*';
                const lookahead = nextLabels.length ?
                    '(?=' + nextLabels.map(l => escapeRe(l) + '\\s*:').join('|') + '|$)' :
                    '(?=$)';
                const re = new RegExp(la + '([\\s\\S]*?)' + lookahead, 'i');
                const m = text.match(re);
                return m ? m[1].trim() : '';
            }
            // Build clean plain text blocks
            const billingText = stripHtmlToText(data.billing || '');
            const accountText = stripHtmlToText(data.account || '');

            // Ordered label lists in the billing block
            const billingLabels = ['Name', 'Billing1', 'Billing2', 'Town', 'County', 'Postcode', 'Post Code', 'Email'];
            const nexts = (label) => billingLabels.filter(l => l !== label);

            // Extract with fallbacks
            const name = extractBetween(billingText, 'Name', nexts('Name'));
            const billing1 = extractBetween(billingText, 'Billing1', nexts('Billing1'));
            const billing2 = extractBetween(billingText, 'Billing2', nexts('Billing2'));
            const town = extractBetween(billingText, 'Town', nexts('Town'));
            const county = extractBetween(billingText, 'County', nexts('County'));
            // Postcode supports both spellings
            const postcode = extractBetween(billingText, 'Postcode', nexts('Postcode')) ||
                extractBetween(billingText, 'Post Code', nexts('Post Code'));
            const email = extractBetween(billingText, 'Email', nexts('Email'));

            // Account: only Contract
            const accountLabels = ['Contract', 'Contract Fee', 'Agent', 'Term', 'Inception Date', 'Renewal Date', 'Active Assets'];
            const contract = extractBetween(accountText, 'Contract', accountLabels.filter(l => l !== 'Contract'));

            // Apply to fields
            document.getElementById('billing_name').value = name;
            document.getElementById('billing1').value = billing1;
            document.getElementById('billing2').value = billing2;
            document.getElementById('billing_town').value = town;
            document.getElementById('billing_county').value = county;
            document.getElementById('billing_postcode').value = postcode;
            document.getElementById('billing_email').value = email || '';
            // Show invoice number if provided
            if (data.invoicenumber) showInvoiceNumber(data.invoicenumber);
        })
        .catch(() => {
            /* ignore */
        });
}

// Minimal HTML→text normaliser
function stripHtmlToText(html) {
    const el = document.createElement('div');
    el.innerHTML = html;
    // Keep labels readable with single spaces
    return (el.innerText || '').replace(/\s+/g, ' ').trim();
}

// ===== Invoice Number =====
function fetchNextInvoiceNumber() {
    const url = `${ROOT_URL}/includes/finance/invoices/next_invoice_number.php?tenant=${TENANT_URL}`;
    fetch(url)
        .then(r => r.ok ? r.json() : Promise.reject())
        .then(j => {
            if (j && j.invoicenumber) showInvoiceNumber(j.invoicenumber);
        })
        .catch(() => {
            // If endpoint not present, we simply leave number hidden. It will show post-save.
        });
}

function showInvoiceNumber(num) {
    const blk = document.getElementById('invoiceNumberBlock');
    const inp = document.getElementById('invoiceNumber');
    inp.value = num;
    blk.style.display = 'block';
}

// ===== Items =====
function openNewItemModal() {
    const clientId = lastLoadedClientId || 0;
    const dest = `${ROOT_URL}/includes/finance/invoices/new_item_modal.php?tenant=${TENANT_URL}&clientnumber=${clientId}`;
    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 feeVal = parseFloat(form.fee?.value || '0');
    const qtyVal = parseInt(form.qty?.value || '1', 10);

    if (!service) {
        showModalToast('Service is required.');
        return;
    }
    if (isNaN(feeVal)) {
        showModalToast('Fee is required.');
        return;
    }
    if (isNaN(qtyVal) || qtyVal < 1) {
        showModalToast('Qty must be at least 1.');
        return;
    }

    const row = document.createElement('tr');
    row.innerHTML = `
        <td class="align-middle service" contenteditable="true" oninput="calculateInvoiceTotal()">${escapeHtml(service)}</td>
        <td class="align-middle notes" contenteditable="true">${escapeHtml(notes)}</td>
        <td class="align-middle fee" contenteditable="true" oninput="calculateInvoiceTotal()">${feeVal.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">${qtyVal}</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 || '1', 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>${escapeHtml(serviceName)}</strong>?</p>`;
    loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Confirm Removal', 'cancelConfirm', () => {
        row.remove();
        calculateInvoiceTotal();
        killModal('popupBox');
    });
}

// ===== Totals =====
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 vat = subtotal * VAT_RATE;
    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);
}

// ===== Save Flow =====
function triggerSaveValidation() {
    // at least one item
    const rows = document.querySelectorAll('#invoiceItems tr');
    if (rows.length === 0) {
        const html = `<p class="text-danger"><i class="fad fa-exclamation-triangle me-2"></i> Add at least one invoice item.</p>`;
        loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Validation Error', 'close');
        return;
    }
    // date present and valid
    const dateStr = document.getElementById('invoiceDate').value.trim();
    if (!/^\d{2}-\d{2}-\d{4}$/.test(dateStr)) {
        const html = `<p class="text-danger">Set a valid invoice date (dd-mm-yyyy).</p>`;
        loadModalContent(html, 'popupBox', 'modal-md', 1060, 'true', 'Validation Error', 'close');
        return;
    }
    // if no client selected, require basic billing
    if (!lastLoadedClientId) {
        const name = document.getElementById('billing_name').value.trim();
        const b1 = document.getElementById('billing1').value.trim();
        const pc = document.getElementById('billing_postcode').value.trim();
        if (!name || !b1 || !pc) {
            const html = `<p class="text-danger">For blank invoices without a client, Name, Billing1, and Postcode are required.</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 = lastLoadedClientId || 0;

    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 invoiceNotes = document.getElementById('invoiceNotes').value;

    const subtotal = parseNumber(document.getElementById('invoiceTotal').value);
    const vat = parseNumber(document.getElementById('vatAmount').value);

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

    // Address JSON
    const addressData = {
        client_name: clientId || 0,
        billing_name: document.getElementById('billing_name').value.trim(),
        billing1: document.getElementById('billing1').value.trim(),
        billing2: document.getElementById('billing2').value.trim(),
        billing_town: document.getElementById('billing_town').value.trim(),
        billing_county: document.getElementById('billing_county').value.trim(),
        billing_postcode: document.getElementById('billing_postcode').value.trim(),
        email: document.getElementById('billing_email').value.trim(),
        commission: '0.00'
    };
    const formData = new FormData();
    formData.append('clientnumber', clientId); // 0 allowed
    formData.append('address', JSON.stringify(addressData));
    formData.append('items', JSON.stringify(items));
    formData.append('totals', `${subtotal}|${vat}`);
    formData.append('vatrate', VAT_RATE);
    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', '0.00');
    formData.append('commission_paid', 0);
    formData.append('filter', 'Blank');
    formData.append('target', 'blank');
    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;
                // Display number if not shown
                if (json.invoice_id) showInvoiceNumber(json.invoice_id);

                // Render PDF
                const invNo = String(json.invoice_id).replace(/^[0|\D]*/, '');
                const postData = new URLSearchParams();
                postData.append('invNo', invNo);
                postData.append('clientnumber', clientId);
                postData.append('rtype', 'blank');
                postData.append('brokerCom', 0);
                postData.append('agentCom', 0);
                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(() => {
                        invoiceHasUnsavedChanges = false;

                        setTimeout(() => {
                            window.location.href = `index.php?t=includes/finance&p=finance_invoices.php`;
                        }, 600);
                    })
                    .catch(err => {
                        showResponse('danger', 'Invoice saved, but render failed: ' + err.message);
                    });
            } else {
                showResponse('danger', `Error saving invoice: ${json.message || 'Unknown error'}`);
            }
        })
        .catch(err => {
            showResponse('danger', `Error saving invoice: ${err.message}`);
        });
}

// ===== Utils =====
function convertDateToTimestamp(dateStr) {
    const [dd, mm, yyyy] = dateStr.split('-').map(s => parseInt(s, 10));
    const d = new Date(yyyy, mm - 1, dd);
    return Math.floor(d.getTime() / 1000);
}

function parseNumber(txt) {
    if (!txt) return 0;
    return parseFloat(String(txt).replace(/[^0-9.-]+/g, '')) || 0;
}

function clearBillingFields() {
    ['billing_name', 'billing1', 'billing2', 'billing_town', 'billing_county', 'billing_postcode', 'billing_email', 'contract_number']
    .forEach(id => {
        const el = document.getElementById(id);
        if (el) el.value = '';
    });
}

function escapeHtml(s) {
    return s.replace(/[&<>"']/g, c => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
    } [c]));
}

// Set page title breadcrumb already above
</script>