<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/WebApp.class.php";

$db = new DBMain();

// Next invoice number
$invoice_res_no  = $db->exec_query('invoices', ['*'], '', '', '', '', '1', "ORDER BY record_id DESC");
$invoice_info_no = $invoice_res_no->fetch_assoc();
$invoice_no      = $invoice_info_no['invoice_no'] + 1;

// Client dropdown options + map of id->details for PDF
$client_res     = $db->exec_query('clients', ['*']);
$options_client = '';
$clients_map    = [];
while ($client = $client_res->fetch_assoc()) {
    $options_client .= "<option value='{$client['record_id']}'>{$client['clients_name']}</option>";
    $clients_map[$client['record_id']] = [
        'name'    => $client['clients_name'],
        'email'   => $client['email'],
        'phone'   => $client['cell'],
        'address' => $client['address'],
    ];
}

// Quote dropdown
$quote_res = $db->exec_query('quotes', ['*']);
$quoto_nos = '';
while ($q = $quote_res->fetch_assoc()) {
    $quoto_nos .= "<option value='{$q['record_id']}'>{$q['quote_no']}</option>";
}

// Company details — embedded for use in client-side PDF
$company_res  = $db->exec_query('company', ['*']);
$company_info = $company_res->fetch_assoc();

$WebApp->pageHeading("NEW INVOICE");
?>

<!-- Embed PHP data for client-side PDF generation -->
<script>
const COMPANY = <?= json_encode([
    'name'    => $company_info['company_name'],
    'email'   => $company_info['email'],
    'address' => $company_info['address'],
    'phone'   => $company_info['phone'],
    'bank'    => $company_info['bank'],
    'acc'     => $company_info['acc'],
    'branch'  => $company_info['branch'],
]) ?>;
const CLIENTS = <?= json_encode($clients_map) ?>;
</script>

<div class='form_container'>
    <form action='save_invoice.php' method='POST' id='invoice_form'>
        <table>
            <tr>
                <td><label>CLIENT</label></td>
                <td><label>DATE</label></td>
                <td><label>DUE DATE</label></td>
            </tr>
            <tr>
                <td>
                    <select name='client_id' class='select' required id='client_id'>
                        <option></option>
                        <?= $options_client ?>
                    </select>
                </td>
                <td>
                    <input type='date' required name='date' id='date' class='input' value='<?= date('Y-m-d') ?>' />
                </td>
                <td>
                    <input type='date' required name='exp_date' id='exp_date' class='input' value='<?= date('Y-m-d', strtotime("+ 5 Days")) ?>' />
                </td>
            </tr>
            <tr>
                <td><label>INVOICE NO</label></td>
                <td><label>QUOTE NO</label></td>
                <td><label>STATUS</label></td>
            </tr>
            <tr>
                <td>
                    <input type='number' required name='invoice_no' id='invoice_no' class='input' value='<?= $invoice_no ?>' readonly />
                </td>
                <td>
                    <select id='quote_no' name='quote_no' class='select'>
                        <option value='0'></option>
                        <?= $quoto_nos ?>
                    </select>
                </td>
                <td>
                    <input type='text' required name='status' id='status' class='input' value='DRAFT' readonly />
                </td>
            </tr>
            <tr><td><label>DESCRIPTION</label></td></tr>
            <tr>
                <td colspan="3">
                    <textarea name='description' id='desciption' class='input' style='width:100%;'></textarea>
                </td>
            </tr>
        </table>
        <br><hr><br>
        <table id='content_table'>
            <tr>
                <td><label class='label'>DESCRIPTION</label></td>
                <td><label class='label'>QUANTITY</label></td>
                <td><label class='label'>AMOUNT (R)</label></td>
                <td><label class='label'>DISCOUNT</label></td>
                <td><label class='label'>SUB TOTAL (R)</label></td>
            </tr>
            <input type='text' id='rows' name='rows' hidden value='2' />
            <tr>
                <td><textarea required name='item_desciption_1' id='item_desciption_1' class='input' style='width:100%;'></textarea></td>
                <td><input type='number' required name='item_quantity_1' id='item_quantity_1' onkeyup='calculations(1)' class='input' value='0' step='0.01' /></td>
                <td><input type='number' required name='item_amount_1' id='item_amount_1' onkeyup='calculations(1)' class='input' value='0' step='0.01' /></td>
                <td><input type='number' name='item_discount_1' id='item_discount_1' onkeyup='calculations(1)' class='input' value='0' step='0.01' /></td>
                <td><input type='number' name='item_total_1' id='item_total_1' class='input' value='0' step='0.01' /></td>
                <td></td>
            </tr>
            <tr>
                <td>TOTAL ITEMS</td>
                <td></td><td></td><td></td>
                <td><label class='label'>TOTAL (R)</label></td>
            </tr>
            <tr>
                <td><input type='number' value='1' id='total_items' name='total_items' readonly class='input' step='0.01'/></td>
                <td></td><td></td><td></td>
                <td><input type='number' value='0' id='total' name='total' readonly class='input' step='0.01' /></td>
            </tr>
        </table>

        <div class='button' onclick="add_new_line()">ADD NEW</div>
        <br><hr><br>

        <!-- SAVE: normal form submit, opens PDF inline -->
        <!-- <button type='submit' class='button' name='save'>SAVE</button> -->

        <!-- SAVE & DOWNLOAD: client-side PDF with Save As dialog -->
        <button type='button' class='button' id='download-btn'
                onclick='saveAndDownload()'>
            SAVE
        </button>
    </form>
</div>

<script>
// ── Line item helpers ────────────────────────────────────────────────────────
function add_new_line() {
    const current_row = document.getElementById('rows').value * 1;
    document.getElementById('total_items').value = current_row;
    const content_table = document.getElementById("content_table");
    const newRow = content_table.insertRow(current_row);
    [0,1,2,3,4,5].forEach(i => newRow.insertCell(i));
    const cells = newRow.cells;
    const r = current_row;
    cells[0].innerHTML = `<textarea name='item_desciption_${r}' id='item_desciption_${r}' class='input' style='width:100%;'></textarea>`;
    cells[1].innerHTML = `<input type='number' name='item_quantity_${r}' onkeyup='calculations(${r})' id='item_quantity_${r}' class='input' value='0' />`;
    cells[2].innerHTML = `<input type='number' name='item_amount_${r}' onkeyup='calculations(${r})' id='item_amount_${r}' class='input' value='0' />`;
    cells[3].innerHTML = `<input type='number' name='item_discount_${r}' onkeyup='calculations(${r})' id='item_discount_${r}' class='input' value='0' />`;
    cells[4].innerHTML = `<input type='number' name='item_total_${r}' id='item_total_${r}' class='input' value='0' />`;
    cells[5].innerHTML = `<div onclick='removeLine(${r})' id='remove_${r}' class='button' style='width:fit-content;padding:0.8vw;margin-bottom:0.7vw;background-color:red'>X</div>`;
    document.getElementById('rows').value = r + 1;
}

function removeLine(r) {
    ['item_desciption_','item_quantity_','item_amount_','item_discount_','item_total_','remove_'].forEach(id => {
        const el = document.getElementById(id + r);
        if (el) el.hidden = true;
    });
    document.getElementById('item_quantity_' + r).value  = 0;
    document.getElementById('item_amount_'   + r).value  = 0;
    document.getElementById('item_discount_' + r).value  = 0;
    document.getElementById('item_total_'    + r).value  = 0;
    document.getElementById('total_items').value = document.getElementById('total_items').value * 1 - 1;
    total_calc();
}

function total_calc() {
    const rows = document.getElementById('rows').value * 1;
    let total = 0;
    for (let i = 1; i < rows; i++) {
        total += document.getElementById('item_total_' + i)?.value * 1 || 0;
    }
    document.getElementById('total').value = Math.round(total * 100) / 100;
}

function calculations(index) {
    const qty      = document.getElementById('item_quantity_' + index).value * 1;
    const amount   = document.getElementById('item_amount_'   + index).value * 1;
    const discount = document.getElementById('item_discount_' + index).value * 1;
    document.getElementById('item_total_' + index).value = (amount * qty) - ((amount * qty) * discount);
    total_calc();
}

// ── PDF libs (lazy load) ─────────────────────────────────────────────────────
const PDF_LIBS = [
    'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js',
];
let _libsLoading = null;
function loadPdfLibs() {
    if (typeof html2canvas !== 'undefined' && typeof window.jspdf !== 'undefined') return Promise.resolve();
    if (_libsLoading) return _libsLoading;
    _libsLoading = Promise.all(PDF_LIBS.map(src => new Promise((res, rej) => {
        const s = document.createElement('script');
        s.src = src; s.onload = res; s.onerror = () => rej(new Error('Failed: ' + src));
        document.head.appendChild(s);
    })));
    return _libsLoading;
}

// ── Collect line items from form ─────────────────────────────────────────────
function collectLineItems() {
    const rows = document.getElementById('rows').value * 1;
    const items = [];
    for (let i = 1; i < rows; i++) {
        const desc = document.getElementById('item_desciption_' + i);
        if (!desc || !desc.value.trim() || desc.hidden) continue;
        items.push({
            description: desc.value,
            quantity:    document.getElementById('item_quantity_' + i).value * 1,
            amount:      document.getElementById('item_amount_'   + i).value * 1,
            discount:    document.getElementById('item_discount_' + i).value * 1,
            total:       document.getElementById('item_total_'    + i).value * 1,
        });
    }
    return items;
}

// ── Format currency ──────────────────────────────────────────────────────────
function formatCurrency(n) {
    return 'R ' + Number(n).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// ── Build invoice HTML for PDF capture ──────────────────────────────────────
function buildInvoiceHtml(invoiceNo, date, dueDate, description, clientId, items, total) {
    const client = CLIENTS[clientId] || {};
    const lineRows = items.map(it => `
        <tr>
            <td style="padding:8px 10px;border-bottom:1px solid #e0e0e0;font-size:12px;white-space:pre-wrap;max-width:280px;">${it.description}</td>
            <td style="padding:8px 10px;border-bottom:1px solid #e0e0e0;font-size:12px;text-align:right;">${it.quantity}</td>
            <td style="padding:8px 10px;border-bottom:1px solid #e0e0e0;font-size:12px;text-align:right;">${formatCurrency(it.amount)}</td>
            <td style="padding:8px 10px;border-bottom:1px solid #e0e0e0;font-size:12px;text-align:right;">${it.discount > 0 ? (it.discount * 100).toFixed(0) + '%' : '—'}</td>
            <td style="padding:8px 10px;border-bottom:1px solid #e0e0e0;font-size:12px;text-align:right;font-weight:600;">${formatCurrency(it.total)}</td>
        </tr>`).join('');

    return `
    <div style="font-family:Arial,sans-serif;background:#fff;padding:32px;width:780px;box-sizing:border-box;color:#111;">

        <!-- Header -->
        <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:24px;">
            <div>
                <img src="/WebApp/Logo.svg" style="width:180px;height:80px;object-fit:contain;display:block;" />
                <div style="margin-top:8px;font-size:11px;color:#555;line-height:1.8;">
                    ${COMPANY.address}<br>
                    ${COMPANY.email} | ${COMPANY.phone}
                </div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:26px;font-weight:700;letter-spacing:1px;">INVOICE</div>
                <div style="font-size:20px;font-weight:700;margin-top:4px;">#${invoiceNo}</div>
                <div style="font-size:11px;color:#555;margin-top:8px;line-height:1.8;">
                    <b>DATE:</b> ${date}<br>
                    <b>DUE:</b> ${dueDate}
                </div>
            </div>
        </div>

        <!-- Bill To -->
        <div style="display:flex;justify-content:space-between;background:#f8f8f8;padding:14px 16px;border-radius:6px;margin-bottom:20px;">
            <div>
                <div style="font-size:10px;text-transform:uppercase;letter-spacing:0.1em;color:#999;margin-bottom:4px;">FROM</div>
                <div style="font-size:13px;font-weight:600;">${COMPANY.name}</div>
                <div style="font-size:11px;color:#555;margin-top:2px;">${COMPANY.email}</div>
                <div style="font-size:11px;color:#555;">${COMPANY.phone}</div>
            </div>
            <div style="text-align:right;">
                <div style="font-size:10px;text-transform:uppercase;letter-spacing:0.1em;color:#999;margin-bottom:4px;">TO</div>
                <div style="font-size:13px;font-weight:600;">${client.name || ''}</div>
                <div style="font-size:11px;color:#555;margin-top:2px;">${client.email || ''}</div>
                <div style="font-size:11px;color:#555;">${client.phone || ''}</div>
                <div style="font-size:11px;color:#555;">${client.address || ''}</div>
            </div>
        </div>

        <!-- Description -->
        ${description ? `<div style="font-size:12px;color:#555;background:#f8f8f8;padding:10px 14px;border-radius:6px;margin-bottom:16px;white-space:pre-wrap;">${description}</div>` : ''}

        <!-- Line items -->
        <table style="width:100%;border-collapse:collapse;margin-bottom:20px;">
            <thead>
                <tr style="background:#f0f0f0;">
                    <th style="padding:8px 10px;font-size:10px;text-transform:uppercase;letter-spacing:0.08em;color:#666;text-align:left;border-bottom:2px solid #ddd;">Description</th>
                    <th style="padding:8px 10px;font-size:10px;text-transform:uppercase;letter-spacing:0.08em;color:#666;text-align:right;border-bottom:2px solid #ddd;">Qty</th>
                    <th style="padding:8px 10px;font-size:10px;text-transform:uppercase;letter-spacing:0.08em;color:#666;text-align:right;border-bottom:2px solid #ddd;">Unit Price</th>
                    <th style="padding:8px 10px;font-size:10px;text-transform:uppercase;letter-spacing:0.08em;color:#666;text-align:right;border-bottom:2px solid #ddd;">Discount</th>
                    <th style="padding:8px 10px;font-size:10px;text-transform:uppercase;letter-spacing:0.08em;color:#666;text-align:right;border-bottom:2px solid #ddd;">Subtotal</th>
                </tr>
            </thead>
            <tbody>${lineRows}</tbody>
        </table>

        <!-- Total -->
        <div style="text-align:right;border-top:2px solid #ddd;padding-top:12px;margin-bottom:24px;">
            <div style="font-size:10px;text-transform:uppercase;letter-spacing:0.1em;color:#999;">Invoice Total</div>
            <div style="font-size:28px;font-weight:700;margin-top:4px;">${formatCurrency(total)}</div>
        </div>

        <!-- Banking details -->
        <div style="display:flex;justify-content:space-between;background:#f8f8f8;padding:14px 16px;border-radius:6px;font-size:11px;color:#555;line-height:1.9;">
            <div>
                <b>BANK:</b> ${COMPANY.bank}<br>
                <b>ACC:</b> ${COMPANY.acc}<br>
                <b>BRANCH:</b> ${COMPANY.branch}<br>
                <b>REFERENCE:</b> ${invoiceNo}<br>
                <b>EMAIL:</b> ${COMPANY.email}
            </div>
            <div style="text-align:right;font-size:12px;color:#333;max-width:320px;">
                70% DEPOSIT WITH ORDERING · 30% ON COLLECTION<br>
                <span style="font-size:10px;color:#888;">Delivery 4–6 weeks per sculpture after order approval.</span>
            </div>
        </div>
    </div>`;
}

// ── Main: SAVE & DOWNLOAD ────────────────────────────────────────────────────
async function saveAndDownload() {
    const btn = document.getElementById('download-btn');
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '⏳ Saving…';

    try {
        // 1. Save invoice via AJAX — returns JSON {success, record_id}
        const formData = new FormData(document.getElementById('invoice_form'));
        const saveRes  = await fetch('save_invoice.php', {
            method:  'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body:    formData,
        });
        const saved = await saveRes.json();
        if (!saved.success) throw new Error(saved.error || 'Could not save invoice');

        // 2. Build invoice HTML from form data
        btn.innerHTML = '⏳ Generating PDF…';
        const invoiceNo   = document.getElementById('invoice_no').value;
        const date        = document.getElementById('date').value;
        const dueDate     = document.getElementById('exp_date').value;
        const description = document.getElementById('desciption').value;
        const clientId    = document.getElementById('client_id').value;
        const total       = document.getElementById('total').value * 1;
        const items       = collectLineItems();

        await loadPdfLibs();

        // 3. Render invoice into an off-screen container for capture
        const container = document.createElement('div');
        container.style.cssText = 'position:fixed;left:-9999px;top:0;z-index:-1;background:#fff;';
        container.innerHTML     = buildInvoiceHtml(invoiceNo, date, dueDate, description, clientId, items, total);
        document.body.appendChild(container);

        // 4. Capture with html2canvas → jsPDF
        const { jsPDF } = window.jspdf;
        const pdf   = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
        const pageW = pdf.internal.pageSize.getWidth();
        const pageH = pdf.internal.pageSize.getHeight();

        const canvas = await html2canvas(container.firstElementChild, {
            scale:           2,
            useCORS:         true,
            backgroundColor: '#ffffff',
        });
        const imgH = (canvas.height * pageW) / canvas.width;
        pdf.addImage(canvas.toDataURL('image/jpeg', 0.95), 'JPEG', 0, 0, pageW, Math.min(imgH, pageH));

        document.body.removeChild(container);

        // 5. Build filename
        const client   = CLIENTS[clientId] || {};
        const slug     = (client.name || '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
        const filename = 'Invoice_' + invoiceNo + (slug ? '_' + slug : '') + '.pdf';
        const blob     = pdf.output('blob');

        // 6. Save As dialog — call from window.top to bypass iframe restriction
        const topWin  = (window.top && window.top !== window) ? window.top : window;
        const pickerFn = topWin.showSaveFilePicker?.bind(topWin);

        if (typeof pickerFn === 'function') {
            try {
                const handle   = await pickerFn({
                    suggestedName: filename,
                    types: [{ description: 'PDF Document', accept: { 'application/pdf': ['.pdf'] } }],
                });
                const writable = await handle.createWritable();
                await writable.write(blob);
                await writable.close();
                alert('✅ PDF saved: ' + handle.name);
            } catch (e) {
                if (e?.name === 'AbortError') return; // user cancelled
                throw e;
            }
        } else {
            // Fallback: standard browser download to Downloads folder
            const url = URL.createObjectURL(blob);
            const a   = document.createElement('a');
            a.href = url; a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 200);
        }

        // 7. Navigate to invoice view
        window.location.href = 'invoice.pdf.php?record_id=' + saved.record_id;

    } catch(e) {
        alert('Error: ' + e.message);
    } finally {
        btn.innerHTML = orig;
        btn.disabled  = false;
    }
}
</script>