<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="fw-bold mb-0"><i class="fas fa-file-invoice-dollar me-2 text-primary"></i><?= $invoice ? 'Edit Invoice' : 'New Invoice' ?></h5>
    <a class="btn btn-sm btn-outline-secondary" href="<?= url('/Invoices') ?>"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?php if (!empty($flash)): ?><div class="alert alert-info py-2 small"><?= e($flash) ?></div><?php endif; ?>

<form method="post" action="<?= url('/Invoices/save') ?>" class="rs-card p-3" id="invoice-form">
    <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">
    <input type="hidden" name="invoice_id" value="<?= (int) ($invoice['invoice_id'] ?? 0) ?>">

    <div class="row g-3 mb-3">
        <div class="col-md-5">
            <label class="form-label small fw-bold">Customer <span class="text-danger">*</span></label>
            <div class="input-group">
                <select name="customer_id" id="customer-select" class="form-select" required>
                    <option value="">-- Select Customer --</option>
                    <?php foreach ($customers as $c): ?>
                        <option value="<?= (int) $c['customer_id'] ?>" <?= (int) ($invoice['customer_id'] ?? 0) === (int) $c['customer_id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#quickCustomerModal" title="Quick Add Customer"><i class="fas fa-plus"></i></button>
            </div>
        </div>
        <div class="col-md-3">
            <label class="form-label small fw-bold">Status</label>
            <select name="status" class="form-select">
                <?php foreach (\App\Models\Invoice::STATUSES as $st): ?>
                    <option value="<?= $st ?>" <?= ($invoice['status'] ?? 'draft') === $st ? 'selected' : '' ?>><?= e($st) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <label class="form-label small fw-bold">Due Date</label>
            <input type="date" name="due_date" class="form-control" value="<?= e($invoice['due_date'] ?? '') ?>">
        </div>
    </div>

    <h6 class="fw-bold mb-2">Line Items</h6>
    <div class="row g-2 mb-1 text-muted small fw-bold">
        <div class="col-md-3">Product / Service</div>
        <div class="col-md-3">Description</div>
        <div class="col-md-1">Qty</div>
        <div class="col-md-1">Price</div>
        <div class="col-md-1">Disc %</div>
        <div class="col-md-2">Line Total</div>
        <div class="col-md-1"></div>
    </div>
    <div id="line-items">
        <?php
        $lineItems = $items ?? [];
        if (empty($lineItems)) $lineItems = [['item_product_id' => '', 'item_description' => '', 'item_qty' => 1, 'item_price' => 0, 'item_discount' => 0]];
        ?>
        <datalist id="product-list">
            <?php foreach ($products as $p): ?>
                <option value="<?= e($p['name']) ?>" data-id="<?= (int) $p['item_id'] ?>" data-price="<?= (float) $p['unit_price'] ?>" data-unit="<?= e($p['unit']) ?>" data-type="<?= e($p['type']) ?>">
            <?php endforeach; ?>
        </datalist>

        <?php foreach ($lineItems as $idx => $li):
            $selName = '';
            if (!empty($li['item_id'] ?? $li['item_product_id'] ?? 0)) {
                foreach ($products as $p) {
                    if ((int) $p['item_id'] === (int) ($li['item_id'] ?? $li['item_product_id'] ?? 0)) {
                        $selName = $p['name']; break;
                    }
                }
            }
        ?>
            <div class="row g-2 mb-2 line-row">
                <div class="col-md-3">
                    <input type="text" list="product-list" name="item_product_name[]" class="form-control form-control-sm product-input" placeholder="Search or type custom..." value="<?= e($selName) ?>" onchange="fillProductDetails(this)">
                    <input type="hidden" name="item_product_id[]" class="product-id" value="<?= e($li['item_id'] ?? $li['item_product_id'] ?? '') ?>">
                </div>
                <div class="col-md-3"><input type="text" name="item_description[]" class="form-control form-control-sm" placeholder="Description" value="<?= e($li['item_description'] ?? $li['description'] ?? '') ?>"></div>
                <div class="col-md-1"><input type="number" step="any" name="item_qty[]" class="form-control form-control-sm qty" value="<?= e($li['item_qty'] ?? $li['quantity'] ?? '1') ?>" onchange="calcLine(this)"></div>
                <div class="col-md-1"><input type="number" step="0.01" name="item_price[]" class="form-control form-control-sm price" value="<?= e($li['item_price'] ?? $li['unit_price'] ?? '0') ?>" onchange="calcLine(this)"></div>
                <div class="col-md-1"><input type="number" step="0.01" name="item_discount[]" class="form-control form-control-sm disc" value="<?= e($li['item_discount'] ?? $li['discount_percent'] ?? '0') ?>" onchange="calcLine(this)" placeholder="Disc%"></div>
                <div class="col-md-2"><input type="text" class="form-control form-control-sm line-total" readonly value="<?= number_format((float) ($li['line_total'] ?? 0), 2) ?>"></div>
                <div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('.line-row').remove(); calcTotals();"><i class="fas fa-times"></i></button></div>
            </div>
        <?php endforeach; ?>
    </div>
    <button type="button" class="btn btn-sm btn-outline-secondary mb-3" onclick="addLineItem()"><i class="fas fa-plus me-1"></i>Add Line</button>

    <div class="row g-3 mb-3">
        <div class="col-md-4 offset-md-8">
            <div class="d-flex justify-content-between small mb-1"><span>Subtotal:</span><strong id="calc-subtotal">0.00</strong></div>
            <div class="row g-1 align-items-center mb-1">
                <div class="col-6"><span class="small">Discount %:</span></div>
                <div class="col-6"><input type="number" step="0.01" name="discount_percent" id="discount-percent" class="form-control form-control-sm" value="<?= e($invoice['discount_percent'] ?? '0') ?>" oninput="calcTotals()"></div>
            </div>
            <div class="d-flex justify-content-between small mb-1"><span>Tax Total:</span><strong id="calc-tax">0.00</strong></div>
            <div class="d-flex justify-content-between fw-bold"><span>Grand Total:</span><strong id="calc-grand">0.00</strong></div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label small fw-bold">Notes</label>
            <textarea name="notes" class="form-control" rows="2"><?= e($invoice['notes'] ?? '') ?></textarea>
        </div>
        <div class="col-md-6">
            <label class="form-label small fw-bold">Terms</label>
            <textarea name="terms" class="form-control" rows="2"><?= e($invoice['terms'] ?? '') ?></textarea>
        </div>
    </div>

    <div class="d-flex gap-2 mt-3">
        <button type="submit" class="btn btn-primary"><?= $invoice ? 'Update' : 'Create' ?> Invoice</button>
        <?php if ($invoice): ?>
            <a href="<?= url('/Invoices/delete/' . (int) $invoice['invoice_id']) ?>" class="btn btn-outline-danger" onclick="return confirm('Delete this invoice?')"><i class="fas fa-trash me-1"></i>Delete</a>
        <?php endif; ?>
    </div>
</form>

<!-- Quick-Add Customer Modal -->
<div class="modal fade" id="quickCustomerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <form id="quickCustomerForm" onsubmit="return quickAddCustomer(event)">
                <div class="modal-header py-2"><h6 class="modal-title">Quick Add Customer</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="_csrf" value="<?= e(\Core\Tool::generateCsrf()) ?>" id="quick-cust-csrf">
                    <div class="mb-2"><label class="form-label small">Name <span class="text-danger">*</span></label><input type="text" name="name" class="form-control form-control-sm" required></div>
                    <div class="mb-2"><label class="form-label small">Contact Person</label><input type="text" name="contact_person" class="form-control form-control-sm"></div>
                    <div class="mb-2"><label class="form-label small">Email</label><input type="email" name="email" class="form-control form-control-sm"></div>
                    <div class="mb-2"><label class="form-label small">Phone</label><input type="text" name="phone" class="form-control form-control-sm"></div>
                </div>
                <div class="modal-footer py-1">
                    <button type="submit" class="btn btn-sm btn-primary">Save</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    var productData = {};
    document.querySelectorAll('#product-list option').forEach(function(o) {
        productData[o.value] = { id: o.dataset.id, price: o.dataset.price, unit: o.dataset.unit, type: o.dataset.type };
    });

    function fillProductDetails(input) {
        var row = input.closest('.line-row');
        var pd = productData[input.value.trim()];
        if (pd) {
            row.querySelector('.product-id').value = pd.id;
            row.querySelector('.price').value = pd.price;
            if (!row.querySelector('input[name="item_description[]"]').value) {
                row.querySelector('input[name="item_description[]"]').value = input.value.trim() + ' (' + pd.type + ')';
            }
        } else { row.querySelector('.product-id').value = ''; }
        calcLine(row.querySelector('.price'));
    }

    function calcLine(el) {
        var row = el.closest('.line-row');
        var qty = Math.max(0, parseFloat(row.querySelector('.qty').value) || 0);
        var price = Math.max(0, parseFloat(row.querySelector('.price').value) || 0);
        var disc = Math.min(100, Math.max(0, parseFloat(row.querySelector('.disc').value) || 0));
        row.querySelector('.line-total').value = Math.max(0, qty * price * (1 - disc / 100)).toFixed(2);
        calcTotals();
    }

    function calcTotals() {
        var subtotal = 0;
        document.querySelectorAll('.line-row').forEach(function(r) {
            var qty = Math.max(0, parseFloat(r.querySelector('.qty').value) || 0);
            var price = Math.max(0, parseFloat(r.querySelector('.price').value) || 0);
            var disc = Math.min(100, Math.max(0, parseFloat(r.querySelector('.disc').value) || 0));
            subtotal += qty * price * (1 - disc / 100);
        });
        var discPct = Math.min(100, Math.max(0, parseFloat(document.getElementById('discount-percent').value) || 0));
        document.getElementById('calc-subtotal').textContent = Math.max(0, subtotal).toFixed(2);
        document.getElementById('calc-tax').textContent = '0.00';
        document.getElementById('calc-grand').textContent = Math.max(0, subtotal - subtotal * (discPct / 100)).toFixed(2);
    }

    function addLineItem() {
        var h = '<div class="row g-2 mb-2 line-row">';
        h += '<div class="col-md-3"><input type="text" list="product-list" name="item_product_name[]" class="form-control form-control-sm product-input" placeholder="Search or type custom..." onchange="fillProductDetails(this)"><input type="hidden" name="item_product_id[]" class="product-id" value=""></div>';
        h += '<div class="col-md-3"><input type="text" name="item_description[]" class="form-control form-control-sm" placeholder="Description"></div>';
        h += '<div class="col-md-1"><input type="number" step="any" name="item_qty[]" class="form-control form-control-sm qty" value="1" onchange="calcLine(this)"></div>';
        h += '<div class="col-md-1"><input type="number" step="0.01" name="item_price[]" class="form-control form-control-sm price" value="0" onchange="calcLine(this)"></div>';
        h += '<div class="col-md-1"><input type="number" step="0.01" name="item_discount[]" class="form-control form-control-sm disc" value="0" onchange="calcLine(this)" placeholder="Disc%"></div>';
        h += '<div class="col-md-2"><input type="text" class="form-control form-control-sm line-total" readonly value="0.00"></div>';
        h += '<div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest(\'.line-row\').remove(); calcTotals();"><i class="fas fa-times"></i></button></div>';
        h += '</div>';
        document.getElementById('line-items').insertAdjacentHTML('beforeend', h);
    }

    async function quickAddCustomer(e) {
        e.preventDefault();
        var form = document.getElementById('quickCustomerForm');
        var fd = new FormData(form);
        try {
            var resp = await fetch('<?= url('/Customers/quickSave') ?>', { method: 'POST', body: fd });
            var data = await resp.json();
            if (data.error) { alert(data.error); return; }
            var sel = document.getElementById('customer-select');
            var opt = new Option(data.name, data.customer_id);
            opt.selected = true;
            sel.insertBefore(opt, sel.querySelector('option[value=""]').nextSibling);
            sel.value = data.customer_id;
            form.reset();
            bootstrap.Modal.getInstance(document.getElementById('quickCustomerModal')).hide();
        } catch (err) { alert('Error saving customer.'); }
        return false;
    }

    document.addEventListener('DOMContentLoaded', calcTotals);
</script>