<?php
$pageTitle = 'Create Invoice';
require_once '../includes/functions.php';
requireLogin();
$db = getDB();

// Load customers and products for dropdowns
$customers = $db->query("SELECT id, name, address, city, state, gstin FROM customers WHERE status='active' ORDER BY name")->fetchAll();
$products  = $db->query("SELECT id, name, price, gst_percent, stock_quantity FROM products WHERE status='active' ORDER BY name")->fetchAll();

// Clone support
$cloneData  = null;
$cloneItems = [];
if (isset($_GET['clone'])) {
    $cid = (int)$_GET['clone'];
    $stmt = $db->prepare("SELECT * FROM invoices WHERE id=?");
    $stmt->execute([$cid]);
    $cloneData = $stmt->fetch();
    if ($cloneData) {
        $stmt = $db->prepare("SELECT * FROM invoice_items WHERE invoice_id=?");
        $stmt->execute([$cid]);
        $cloneItems = $stmt->fetchAll();
    }
}

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cust_id     = (int)$_POST['customer_id'];
    $inv_date    = trim((string)($_POST['invoice_date'] ?? ''));
    $due_date    = trim((string)($_POST['due_date'] ?? '')) ?: null;
    $notes       = trim($_POST['notes'] ?? '');
    $status      = $_POST['status'] ?? 'draft';
    $disc_pct    = (float)($_POST['discount_percent'] ?? 0);

    $items       = $_POST['items'] ?? [];

    if (!$cust_id || empty($items)) {
        setFlash('error', 'Please select a customer and add at least one item.');
        header('Location: invoice_create.php');
        exit;
    }
    if (empty($inv_date)) {
        setFlash('error', 'Invoice date is required.');
        header('Location: invoice_create.php');
        exit;
    }

    // Calculate totals
    $subtotal    = 0;
    $gst_total   = 0;
    $lineItems   = [];

    foreach ($items as $item) {
        $pid       = (int)($item['product_id'] ?? 0);
        $pname     = trim($item['product_name'] ?? '');
        $qty       = max(1, (int)($item['quantity'] ?? 1));
        $uprice    = (float)($item['unit_price'] ?? 0);
        $margin    = (float)($item['margin_percent'] ?? 0);
        $gst_pct   = (float)($item['gst_percent'] ?? 0);

        if (empty($pname) || $uprice <= 0) continue;

        $priceWithMargin = $uprice * (1 + $margin / 100);
        $lineBase        = $priceWithMargin * $qty;
        $gstAmt          = $lineBase * $gst_pct / 100;
        $lineTotal       = $lineBase + $gstAmt;

        $subtotal  += $lineBase;
        $gst_total += $gstAmt;
        $lineItems[] = [$pid ?: null, $pname, $qty, $uprice, $margin, $gst_pct, $gstAmt, $lineTotal];
    }

    if (count($lineItems) === 0) {
        setFlash('error', 'Please add at least one valid item (select product and provide price).');
        header('Location: invoice_create.php');
        exit;
    }

    $disc_amt    = $subtotal * $disc_pct / 100;
    $total       = $subtotal - $disc_amt + $gst_total;

    try {
        $db->beginTransaction();
        $inv_number  = generateInvoiceNumber();
        $stmt = $db->prepare("INSERT INTO invoices (invoice_number,customer_id,invoice_date,due_date,subtotal,discount_percent,discount_amount,gst_amount,total_amount,notes,status,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$inv_number, $cust_id, $inv_date, $due_date, $subtotal, $disc_pct, $disc_amt, $gst_total, $total, $notes, $status, $_SESSION['user_id']]);
        $inv_id = $db->lastInsertId();

        $itemStmt = $db->prepare("INSERT INTO invoice_items (invoice_id,product_id,product_name,quantity,unit_price,margin_percent,gst_percent,gst_amount,line_total) VALUES (?,?,?,?,?,?,?,?,?)");
        foreach ($lineItems as $li) {
            $itemStmt->execute([$inv_id, ...$li]);
        }

        $db->commit();
        setFlash('success', "Invoice {$inv_number} created successfully!");
        header("Location: invoice_view.php?id={$inv_id}");
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        setFlash('error', 'Failed to create invoice. Please check inputs and try again.');
    }
}

$today = date('Y-m-d');
$due30 = date('Y-m-d', strtotime('+30 days'));
require_once '../includes/header.php';
?>

<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
    <div>
        <h2 class="text-lg font-bold text-slate-800">New Invoice</h2>
        <p class="text-sm text-slate-400">Fill in the details to generate an invoice</p>
    </div>
    <a href="invoices.php" class="btn-outline"><i class="fas fa-arrow-left mr-1"></i>Back</a>
</div>

<form method="POST" id="invoiceForm">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    <!-- Left Column -->
    <div class="lg:col-span-2 space-y-5">

        <!-- Customer & Dates -->
        <div class="card p-6">
            <h3 class="font-bold text-slate-700 mb-4 flex items-center gap-2"><i class="fas fa-user text-brand-500 text-sm"></i> Customer & Date</h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div class="col-span-2 space-y-2">
                    <div class="flex items-center justify-between gap-3">
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Customer *</label>
                        <a href="customers.php?action=add" class="btn-outline text-xs py-1 px-3 whitespace-nowrap">Add Customer</a>
                    </div>
                    <select name="customer_id" id="customerSelect" class="form-input" required>
                        <option value="">— Select Customer —</option>
                        <?php foreach ($customers as $c): ?>
                        <option value="<?= $c['id'] ?>" data-info="<?= htmlspecialchars(json_encode($c)) ?>"
                            <?= ($cloneData && $cloneData['customer_id'] == $c['id']) ? 'selected' : '' ?>>
                            <?= sanitize($c['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div id="customerInfoBox" class="col-span-2 bg-slate-50 rounded-xl p-3 text-xs text-slate-600 hidden"></div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Invoice Date *</label>
                    <input type="date" name="invoice_date" value="<?= $cloneData ? $today : $today ?>" class="form-input" required>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Due Date</label>
                    <input type="date" name="due_date" value="<?= $due30 ?>" class="form-input">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Status</label>
                    <select name="status" class="form-input">
                        <option value="draft">Draft</option>
                        <option value="sent">Sent</option>
                        <option value="paid">Paid</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Discount %</label>
                    <input type="number" step="0.01" name="discount_percent" id="discPct" value="0" min="0" max="100" class="form-input">
                </div>
            </div>
        </div>

        <!-- Line Items -->
        <div class="card p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="font-bold text-slate-700 flex items-center gap-2"><i class="fas fa-list text-brand-500 text-sm"></i> Products / Services</h3>
                <button type="button" id="addRowBtn" class="btn-outline text-xs"><i class="fas fa-plus mr-1"></i>Add Row</button>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-sm" id="itemsTable">
                    <thead>
                        <tr class="border-b border-slate-100">
                            <th class="text-left pb-2 text-slate-400 font-semibold text-xs uppercase pr-2">Product</th>
                            <th class="text-center pb-2 text-slate-400 font-semibold text-xs uppercase w-16">Qty</th>
                            <th class="text-right pb-2 text-slate-400 font-semibold text-xs uppercase w-24">Price (₹)</th>
                            <th class="text-right pb-2 text-slate-400 font-semibold text-xs uppercase w-20">Margin%</th>
                            <th class="text-right pb-2 text-slate-400 font-semibold text-xs uppercase w-16">GST%</th>
                            <th class="text-right pb-2 text-slate-400 font-semibold text-xs uppercase w-24">Total</th>
                            <th class="w-8"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                        <!-- Rows injected by JS -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Notes -->
        <div class="card p-6">
            <h3 class="font-bold text-slate-700 mb-3 flex items-center gap-2"><i class="fas fa-note-sticky text-brand-500 text-sm"></i> Notes</h3>
            <textarea name="notes" class="form-input" rows="3" placeholder="Payment terms, thank you note, bank details..."><?= sanitize($cloneData['notes'] ?? '') ?></textarea>
        </div>
    </div>

    <!-- Right Column: Summary -->
        <div class="space-y-5">
        <div class="card p-6 lg:sticky lg:top-20">
            <h3 class="font-bold text-slate-700 mb-5">Invoice Summary</h3>
            <div class="space-y-3 text-sm">
                <div class="flex justify-between text-slate-600">
                    <span>Subtotal</span>
                    <span id="sumSubtotal" class="font-semibold text-slate-800">₹0.00</span>
                </div>
                <div class="flex justify-between text-slate-600">
                    <span>Discount</span>
                    <span id="sumDiscount" class="font-semibold text-amber-600">- ₹0.00</span>
                </div>
                <div class="flex justify-between text-slate-600">
                    <span>GST</span>
                    <span id="sumGst" class="font-semibold text-slate-800">₹0.00</span>
                </div>
                <div class="border-t border-slate-100 pt-3 flex justify-between">
                    <span class="font-bold text-slate-800 text-base">Total</span>
                    <span id="sumTotal" class="font-bold text-brand-600 text-xl">₹0.00</span>
                </div>
            </div>

            <div class="mt-6 space-y-2.5">
                <button type="submit" class="btn-primary w-full justify-center">
                    <i class="fas fa-check mr-2"></i>Create Invoice
                </button>
                <button type="button" id="previewBtn" class="btn-outline w-full justify-center">
                    <i class="fas fa-eye mr-2"></i>Preview
                </button>
            </div>
        </div>
    </div>
</div>
</form>

<!-- Product data for JS -->
<script>
window.PRODUCTS = <?= json_encode($products) ?>;
window.CLONE_ITEMS = <?= json_encode($cloneItems) ?>;
</script>
<script src="<?= $basePath ?>assets/js/invoice-create.js"></script>

<?php require_once '../includes/footer.php'; ?>
