<?php require_once __DIR__ . '/_sidebar.php'; ?>
<main class="flex-1 py-16 md:py-0 md:pl-64">
    <div class="max-w-5xl mx-auto px-4 py-8 md:py-16">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-10">
            <div>
                <h1 class="text-4xl font-bold text-slate-950"><?= htmlspecialchars($pageTitle) ?></h1>
                <p class="mt-2 text-slate-600">Create or edit invoices with customer details, due date, paid amount, and itemized billing.</p>
            </div>
            <a href="<?= htmlspecialchars($baseUrl) ?>/admin/invoices" class="inline-flex items-center gap-2 rounded-lg border border-slate-300 bg-white px-5 py-3 text-sm font-medium text-slate-950 hover:bg-slate-100 transition">
                <span class="material-symbols-outlined">arrow_back</span> Back to Invoices
            </a>
        </div>

        <form method="post" action="<?= htmlspecialchars($baseUrl . $formAction) ?>" class="space-y-8 rounded-3xl bg-white p-8 shadow-lg border border-slate-200">
            <?= CSRF::input() ?>
            <?php if (!empty($invoice)): ?>
                <input type="hidden" name="id" value="<?= htmlspecialchars($invoice['id']) ?>">
            <?php endif; ?>

            <div class="grid gap-6 md:grid-cols-2">
                <div>
                    <label class="block text-sm font-medium text-slate-700">Invoice Number</label>
                    <input name="invoice_number" type="text" value="<?= htmlspecialchars($invoice['invoice_number'] ?? '') ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-4 text-sm" placeholder="INV-2025..." />
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Customer</label>
                    <select name="customer_id" class="mt-2 w-full rounded-2xl border border-slate-300 p-4 text-sm">
                        <option value="">Select customer</option>
                        <?php foreach ($customers as $customer): ?>
                            <option value="<?= htmlspecialchars($customer['id']) ?>" <?= !empty($invoice['customer_id']) && $invoice['customer_id'] == $customer['id'] ? 'selected' : '' ?>><?= htmlspecialchars($customer['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Due Date</label>
                    <input name="due_date" type="date" value="<?= htmlspecialchars($invoice['due_date'] ?? '') ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-4 text-sm" />
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Status</label>
                    <select name="status" class="mt-2 w-full rounded-2xl border border-slate-300 p-4 text-sm">
                        <?php foreach (['Outstanding','Partial','Paid'] as $statusOption): ?>
                            <option value="<?= $statusOption ?>" <?= (!empty($invoice['status']) && $invoice['status'] === $statusOption) ? 'selected' : '' ?>><?= $statusOption ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700">Paid Amount</label>
                    <input name="paid_amount" type="number" step="0.01" min="0" value="<?= htmlspecialchars($invoice['paid_amount'] ?? '0.00') ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-4 text-sm" />
                </div>
            </div>

            <div class="rounded-3xl bg-slate-50 p-6">
                <div class="flex items-center justify-between gap-4 mb-6">
                    <div>
                        <h2 class="text-xl font-semibold text-slate-950">Invoice Items</h2>
                        <p class="mt-2 text-sm text-slate-600">Add billing items, quantity, unit price, and totals for each line.</p>
                    </div>
                    <button type="button" id="add-item" class="inline-flex items-center rounded-full btn-primary px-5 py-3 text-sm font-semibold text-white hover:bg-rich-crimson transition">Add Item</button>
                </div>

                <div id="invoice-items" class="space-y-4">
                    <?php if (empty($items)): ?>
                        <?php $items = [['description' => '', 'quantity' => 1, 'unit_price' => 0.00]]; ?>
                    <?php endif; ?>
                    <?php foreach ($items as $index => $item): ?>
                        <div class="grid gap-4 md:grid-cols-[2fr_1fr_1fr_auto] items-end rounded-3xl bg-white p-4 border border-slate-200">
                            <div>
                                <label class="block text-sm font-medium text-slate-700">Description</label>
                                <input name="items[description][]" type="text" value="<?= htmlspecialchars($item['description'] ?? '') ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700">Quantity</label>
                                <input name="items[quantity][]" type="number" min="1" value="<?= htmlspecialchars($item['quantity'] ?? 1) ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700">Unit Price (GHS)</label>
                                <input name="items[unit_price][]" type="number" step="0.01" min="0" value="<?= htmlspecialchars($item['unit_price'] ?? 0.00) ?>" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
                            </div>
                            <button type="button" class="remove-item inline-flex h-12 w-12 items-center justify-center rounded-full bg-red-600 text-white hover:bg-red-700 transition" aria-label="Remove item">
                                <span class="material-symbols-outlined">close</span>
                            </button>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="flex justify-end gap-4">
                <a href="<?= htmlspecialchars($baseUrl) ?>/admin/invoices" class="inline-flex items-center justify-center rounded-full border border-slate-300 bg-white px-8 py-4 text-sm font-semibold text-slate-950 hover:bg-slate-100 transition">Cancel</a>
                <button type="submit" class="inline-flex items-center justify-center rounded-full bg-charcoal px-8 py-4 text-sm font-semibold text-white hover:bg-slate-900 transition">Save Invoice</button>
            </div>
        </form>
    </div>
</main>
</div>
<script>
    const invoiceItems = document.getElementById('invoice-items');
    const addItemButton = document.getElementById('add-item');

    function createItemRow(description = '', quantity = 1, price = 0.00) {
        const row = document.createElement('div');
        row.className = 'grid gap-4 md:grid-cols-[2fr_1fr_1fr_auto] items-end rounded-3xl bg-white p-4 border border-slate-200';
        row.innerHTML = `
            <div>
                <label class="block text-sm font-medium text-slate-700">Description</label>
                <input name="items[description][]" type="text" value="${description.replace(/"/g, '&quot;')}" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700">Quantity</label>
                <input name="items[quantity][]" type="number" min="1" value="${quantity}" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700">Unit Price (GHS)</label>
                <input name="items[unit_price][]" type="number" step="0.01" min="0" value="${price}" class="mt-2 w-full rounded-2xl border border-slate-300 p-3 text-sm" required />
            </div>
            <button type="button" class="remove-item inline-flex h-12 w-12 items-center justify-center rounded-full bg-red-600 text-white hover:bg-red-700 transition" aria-label="Remove item">
                <span class="material-symbols-outlined">close</span>
            </button>
        `;
        row.querySelector('.remove-item').addEventListener('click', () => row.remove());
        return row;
    }

    addItemButton.addEventListener('click', () => {
        invoiceItems.appendChild(createItemRow('', 1, '0.00'));
    });

    invoiceItems.querySelectorAll('.remove-item').forEach(button => {
        button.addEventListener('click', (event) => {
            event.currentTarget.closest('div')?.remove();
        });
    });
</script>
</div>