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

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

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $supplier_name = trim($_POST['supplier_name'] ?? '');
    $supplier_gstin = trim($_POST['supplier_gstin'] ?? '') ?: null;
    $purchase_date = trim($_POST['purchase_date'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $status = $_POST['status'] ?? 'draft';
    $items = $_POST['items'] ?? [];

    if (!$supplier_name || empty($items)) {
        setFlash('error', 'Please enter supplier name and add at least one item.');
        header('Location: purchase_add.php');
        exit;
    }
    if (empty($purchase_date)) {
        setFlash('error', 'Purchase date is required.');
        header('Location: purchase_add.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);
        $gst_pct = (float)($item['gst_percent'] ?? 0);

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

        $gstAmt = $uprice * $qty * $gst_pct / 100;
        $lineTotal = $uprice * $qty + $gstAmt;

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

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

    $total = $subtotal + $gst_total;

    try {
        $db->beginTransaction();
        $purchase_number = generatePurchaseNumber();
        $stmt = $db->prepare("INSERT INTO purchases (purchase_number, supplier_name, supplier_gstin, purchase_date, subtotal, gst_amount, total_amount, notes, status, created_by) VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$purchase_number, $supplier_name, $supplier_gstin, $purchase_date, $subtotal, $gst_total, $total, $notes, $status, $_SESSION['user_id']]);
        $purchase_id = $db->lastInsertId();

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

        // Update product stock quantities if status is 'received'
        if ($status === 'received') {
            foreach ($lineItems as $li) {
                if ($li[0]) { // product_id exists
                    $db->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?")
                        ->execute([$li[2], $li[0]]); // quantity, product_id
                }
            }
        }

        $db->commit();
        setFlash('success', "Purchase {$purchase_number} added successfully!");
        header("Location: purchases.php");
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        setFlash('error', 'Failed to add purchase. Please check inputs and try again.');
    }
}

$today = date('Y-m-d');
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">Add Purchase</h2>
        <p class="text-sm text-slate-400">Record purchased products and update inventory</p>
    </div>
    <a href="purchases.php" class="btn-outline"><i class="fas fa-arrow-left mr-1"></i>Back</a>
</div>

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

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

        <!-- Supplier & Date -->
        <div class="card p-6">
            <h3 class="font-bold text-slate-700 mb-4 flex items-center gap-2"><i class="fas fa-truck text-brand-500 text-sm"></i> Supplier & Date</h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Supplier Name *</label>
                    <input type="text" name="supplier_name" class="form-input" required>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Supplier GSTIN</label>
                    <input type="text" name="supplier_gstin" class="form-input" maxlength="20">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Purchase Date *</label>
                    <input type="date" name="purchase_date" value="<?= $today ?>" class="form-input" required>
                </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="received">Received</option>
                        <option value="paid">Paid</option>
                    </select>
                </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> Purchased Products</h3>
                <button type="button" onclick="addRow()" 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-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="Purchase terms, supplier details..."></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">Purchase 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>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>Add Purchase
                </button>
            </div>
        </div>
    </div>
</div>
</form>

<!-- Product data for JS -->
<script>
const products = <?= json_encode($products) ?>;

const productMap = {};
products.forEach(p => { productMap[p.id] = p; });

function fmt(n) { return '₹' + parseFloat(n).toFixed(2).replace(/\d(?=(\d{3})+\.)/g,'$&,'); }

function addRow(data = null) {
    const tbody = document.getElementById('itemsBody');
    const idx   = tbody.querySelectorAll('tr').length;
    const d     = data || {};

    const tr = document.createElement('tr');
    tr.className = 'border-b border-slate-50 item-row';
    tr.innerHTML = `
        <td class="py-2 pr-2">
            <input type="hidden" name="items[${idx}][product_id]" class="inp-pid" value="${d.product_id || ''}">
            <select class="form-input text-xs inp-product" onchange="onProductSelect(this, ${idx})">
                <option value="">Custom / Type below</option>
                ${products.map(p => `<option value="${p.id}" ${d.product_id == p.id ? 'selected':''} data-price="${p.price}" data-gst="${p.gst_percent}">${p.name}</option>`).join('')}
            </select>
            <input type="text" name="items[${idx}][product_name]" class="form-input text-xs mt-1 inp-name" placeholder="Product name" value="${escHtml(d.product_name || '')}" required>
        </td>
        <td class="py-2 px-1">
            <input type="number" name="items[${idx}][quantity]" min="1" value="${d.quantity || 1}" class="form-input text-xs text-center inp-qty" oninput="recalcRow(this)">
        </td>
        <td class="py-2 px-1">
            <input type="number" step="0.01" name="items[${idx}][unit_price]" value="${d.unit_price || 0}" class="form-input text-xs text-right inp-price" oninput="recalcRow(this)">
        </td>
        <td class="py-2 px-1">
            <input type="number" step="0.01" name="items[${idx}][gst_percent]" value="${d.gst_percent || 18}" class="form-input text-xs text-right inp-gst" oninput="recalcRow(this)">
        </td>
        <td class="py-2 pl-1 text-right">
            <span class="font-bold text-slate-800 text-xs row-total">₹0.00</span>
        </td>
        <td class="py-2 pl-2">
            <button type="button" onclick="removeRow(this)" class="text-red-400 hover:text-red-600 w-6 h-6 flex items-center justify-center rounded-lg hover:bg-red-50">
                <i class="fas fa-times text-xs"></i>
            </button>
        </td>
    `;
    tbody.appendChild(tr);
    recalcRow(tr.querySelector('.inp-qty'));
}

function escHtml(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

function onProductSelect(sel, idx) {
    const pid = sel.value;
    const tr  = sel.closest('tr');
    tr.querySelector('.inp-pid').value = pid;
    if (pid && productMap[pid]) {
        const p = productMap[pid];
        tr.querySelector('.inp-name').value  = p.name;
        tr.querySelector('.inp-price').value = p.price;
        tr.querySelector('.inp-gst').value   = p.gst_percent;
    }
    recalcRow(tr.querySelector('.inp-qty'));
}

function recalcRow(el) {
    const tr     = el.closest('tr');
    const qty    = parseFloat(tr.querySelector('.inp-qty').value) || 0;
    const price  = parseFloat(tr.querySelector('.inp-price').value) || 0;
    const gst    = parseFloat(tr.querySelector('.inp-gst').value) || 0;
    const gstAmt = price * qty * gst / 100;
    tr.querySelector('.row-total').textContent = fmt(price * qty + gstAmt);
    recalcTotal();
}

function recalcTotal() {
    let subtotal = 0, gstTotal = 0;
    document.querySelectorAll('#itemsBody .item-row').forEach(tr => {
        const qty    = parseFloat(tr.querySelector('.inp-qty').value) || 0;
        const price  = parseFloat(tr.querySelector('.inp-price').value) || 0;
        const gst    = parseFloat(tr.querySelector('.inp-gst').value) || 0;
        const base   = price * qty;
        subtotal += base;
        gstTotal += base * gst / 100;
    });
    const total = subtotal + gstTotal;

    document.getElementById('sumSubtotal').textContent = fmt(subtotal);
    document.getElementById('sumGst').textContent      = fmt(gstTotal);
    document.getElementById('sumTotal').textContent    = fmt(total);
}

function removeRow(btn) {
    btn.closest('tr').remove();
    recalcTotal();
}

// Init: add one empty row
document.addEventListener('DOMContentLoaded', () => {
    addRow();
});
</script>

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