<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

// Handle create purchase
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header('Location: purchases.php'); exit;
    }

    $vendorId = (int)$_POST['vendor_id'];
    $purchaseDate = $_POST['purchase_date'];
    $invoiceNo = trim($_POST['invoice_no']);
    $notes = trim($_POST['notes']);
    $itemIds = $_POST['item_id'] ?? [];
    $qtys = $_POST['qty'] ?? [];
    $prices = $_POST['purchase_price'] ?? [];
    $gsts = $_POST['line_gst'] ?? [];

    if (empty($itemIds) || $vendorId <= 0) {
        setFlash('danger', 'Please select a vendor and at least one item.');
        header('Location: purchases.php'); exit;
    }

    try {
        $pdo->beginTransaction();

        $purchaseNo = generateDocNumber('purchases', 'purchase_no', getSetting('purchase_prefix','PUR'));

        $totalAmount = 0; $gstAmount = 0; $grandTotal = 0;
        $lineData = [];

        foreach ($itemIds as $idx => $itemId) {
            $itemId = (int)$itemId;
            $qty = (int)$qtys[$idx];
            $price = (float)$prices[$idx];
            $gstPct = (float)$gsts[$idx];
            if ($itemId <= 0 || $qty <= 0) continue;

            $lineSubtotal = $qty * $price;
            $lineGst = round($lineSubtotal * $gstPct / 100, 2);
            $lineTotal = $lineSubtotal + $lineGst;

            $totalAmount += $lineSubtotal;
            $gstAmount += $lineGst;
            $grandTotal += $lineTotal;

            $lineData[] = [
                'item_id' => $itemId, 'qty' => $qty, 'price' => $price,
                'gst_pct' => $gstPct, 'gst_amt' => $lineGst, 'line_total' => $lineTotal
            ];
        }

        if (empty($lineData)) {
            $pdo->rollBack();
            setFlash('danger', 'No valid items added.');
            header('Location: purchases.php'); exit;
        }

        $stmt = $pdo->prepare("INSERT INTO purchases (purchase_no, vendor_id, purchase_date, invoice_no, total_amount, gst_amount, grand_total, notes, created_by)
                                VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$purchaseNo, $vendorId, $purchaseDate, $invoiceNo, $totalAmount, $gstAmount, $grandTotal, $notes, currentUserId()]);
        $purchaseId = $pdo->lastInsertId();

        foreach ($lineData as $line) {
            $pdo->prepare("INSERT INTO purchase_items (purchase_id, item_id, qty, purchase_price, gst_percent, gst_amount, line_total)
                           VALUES (?,?,?,?,?,?,?)")
                ->execute([$purchaseId, $line['item_id'], $line['qty'], $line['price'], $line['gst_pct'], $line['gst_amt'], $line['line_total']]);

            // Update stock ledger
            addPurchaseStock($line['item_id'], $line['qty'], $line['price'], $purchaseId, currentUserId());
        }

        $pdo->commit();

        // Auto accounting journal: DR Stock/Inventory  CR Accounts Payable
        if (function_exists('createJournalEntry')) {
            try {
                $stockAccId = $pdo->query("SELECT id FROM accounts WHERE account_code='1200' LIMIT 1")->fetchColumn();
                $apAccId    = $pdo->query("SELECT id FROM accounts WHERE account_code='2100' LIMIT 1")->fetchColumn();
                if ($stockAccId && $apAccId) {
                    createJournalEntry($purchaseDate, 'purchase',
                        "Purchase from vendor - $purchaseNo",
                        [
                            ['account_id' => $stockAccId, 'debit'  => $grandTotal, 'credit' => 0,            'narration' => 'Stock purchased'],
                            ['account_id' => $apAccId,    'debit'  => 0,           'credit' => $grandTotal,  'narration' => "Payable for $purchaseNo"],
                        ],
                        'purchase', $purchaseId, currentUserId()
                    );
                }
            } catch (Exception $e) {
                error_log('Journal failed for purchase: ' . $e->getMessage());
            }
        }

        setFlash('success', "Purchase $purchaseNo recorded successfully. Stock updated.");

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
    }

    header('Location: purchases.php');
    exit;
}

// Mark payment status
if (isset($_GET['action']) && $_GET['action'] === 'mark_paid' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT * FROM purchases WHERE id = ?");
    $stmt->execute([$id]);
    $p = $stmt->fetch();
    if ($p) {
        $pdo->prepare("UPDATE purchases SET payment_status='paid', paid_amount=grand_total WHERE id=?")->execute([$id]);
        // Get vendor name
        $vendorStmt = $pdo->prepare("SELECT vendor_name FROM purchase_vendors WHERE id=?");
        $vendorStmt->execute([$p['vendor_id']]);
        $vendorName = $vendorStmt->fetch()['vendor_name'];
        recordPayment('outflow', 'purchase', $id, $vendorName, $p['grand_total'] - $p['paid_amount'], date('Y-m-d H:i:s'), 'manual', 'Purchase payment settled', currentUserId());
        setFlash('success', 'Purchase marked as paid and recorded in cash flow.');
    }
    header('Location: purchases.php'); exit;
}

// Delete purchase (reverses stock)
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    try {
        $pdo->beginTransaction();
        $items = $pdo->prepare("SELECT * FROM purchase_items WHERE purchase_id = ?");
        $items->execute([$id]);
        foreach ($items->fetchAll() as $pi) {
            reversePurchaseStock($pi['item_id'], $pi['qty'], $id, currentUserId());
        }
        $pdo->prepare("DELETE FROM purchases WHERE id = ?")->execute([$id]);
        $pdo->commit();
        setFlash('success', 'Purchase deleted and stock reversed.');
    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
    }
    header('Location: purchases.php'); exit;
}

// Data for form
$vendors = $pdo->query("SELECT * FROM purchase_vendors WHERE status=1 ORDER BY vendor_name")->fetchAll();
$items = $pdo->query("SELECT * FROM items WHERE status=1 ORDER BY item_name")->fetchAll();

// List purchases
$purchases = $pdo->query("SELECT p.*, v.vendor_name FROM purchases p JOIN purchase_vendors v ON v.id=p.vendor_id ORDER BY p.id DESC LIMIT 100")->fetchAll();

$csrf = generateCSRFToken();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Purchase Entry';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Stock</div>
        <h2 class="mb-0">Purchase Entry</h2>
    </div>
    <button class="btn btn-primary" onclick="document.getElementById('purchaseModal').classList.add('show')"><?= icon('plus') ?> New Purchase</button>
</div>

<div class="card">
    <div class="card-title">Purchase History</div>
    <?php if ($purchases): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Purchase #</th><th>Vendor</th><th>Date</th><th>Vendor Invoice#</th>
                    <th class="text-right">Subtotal</th><th class="text-right">GST</th><th class="text-right">Grand Total</th>
                    <th>Payment</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($purchases as $p): ?>
            <tr>
                <td class="mono"><?= sanitize($p['purchase_no']) ?></td>
                <td><?= sanitize($p['vendor_name']) ?></td>
                <td><?= formatDate($p['purchase_date']) ?></td>
                <td><?= sanitize($p['invoice_no']) ?: '-' ?></td>
                <td class="num"><?= formatMoney($p['total_amount']) ?></td>
                <td class="num"><?= formatMoney($p['gst_amount']) ?></td>
                <td class="num"><strong><?= formatMoney($p['grand_total']) ?></strong></td>
                <td><span class="badge badge-<?= $p['payment_status']=='paid'?'success':($p['payment_status']=='partial'?'warning':'danger') ?>"><?= $p['payment_status'] ?></span></td>
                <td>
                    <div class="flex gap-8">
                        <?php if ($p['payment_status'] != 'paid'): ?>
                        <a href="?action=mark_paid&id=<?= $p['id'] ?>" class="btn btn-icon btn-sm btn-success" title="Mark Paid" onclick="return confirm('Mark this purchase as fully paid?')"><?= icon('cash') ?></a>
                        <?php endif; ?>
                        <a href="?action=delete&id=<?= $p['id'] ?>" class="btn btn-icon btn-sm" title="Delete (reverses stock)" onclick="return confirm('Delete this purchase? Stock quantities will be reversed.')"><?= icon('trash') ?></a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('shopping-cart-plus') ?>No purchase records yet.</div>
    <?php endif; ?>
</div>

<!-- New Purchase Modal -->
<div class="modal-backdrop" id="purchaseModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2>New Purchase Entry</h2>
            <button class="btn btn-icon" onclick="document.getElementById('purchaseModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST" id="purchaseForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="create">

            <div class="form-grid">
                <div class="form-group">
                    <label>Purchase Vendor <span class="req">*</span></label>
                    <select name="vendor_id" required>
                        <option value="">-- Select Vendor --</option>
                        <?php foreach ($vendors as $v): ?>
                        <option value="<?= $v['id'] ?>"><?= sanitize($v['vendor_name']) ?> (<?= sanitize($v['vendor_code']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Purchase Date <span class="req">*</span></label>
                    <input type="date" name="purchase_date" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="form-group">
                    <label>Vendor Invoice Number</label>
                    <input type="text" name="invoice_no" placeholder="Vendor's bill number">
                </div>
            </div>

            <fieldset>
                <legend>Items</legend>
                <div class="table-wrap">
                    <table id="lineItemsTable">
                        <thead>
                            <tr><th style="min-width:200px">Item</th><th style="width:90px">Qty</th><th style="width:120px">Purchase Price</th><th style="width:90px">GST%</th><th style="width:120px" class="text-right">Line Total</th><th style="width:40px"></th></tr>
                        </thead>
                        <tbody id="lineItemsBody"></tbody>
                    </table>
                </div>
                <button type="button" class="btn btn-sm mt-8" onclick="addLine()"><?= icon('plus') ?> Add Item</button>

                <div class="divider"></div>
                <div class="flex-end" style="gap:32px;">
                    <div class="text-sm">Subtotal: <strong class="mono" id="sumSubtotal">₹0.00</strong></div>
                    <div class="text-sm">GST: <strong class="mono" id="sumGst">₹0.00</strong></div>
                    <div>Grand Total: <strong class="mono" id="sumTotal" style="font-size:16px;">₹0.00</strong></div>
                </div>
            </fieldset>

            <div class="form-group full">
                <label>Notes</label>
                <textarea name="notes" rows="2"></textarea>
            </div>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('purchaseModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Purchase</button>
            </div>
        </form>
    </div>
</div>

<script>
const ITEMS = <?= json_encode($items) ?>;
let lineIdx = 0;

function addLine() {
    const tbody = document.getElementById('lineItemsBody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td>
            <select name="item_id[]" class="item-select" onchange="onItemChange(this)" required>
                <option value="">-- Select Item --</option>
                ${ITEMS.map(i => `<option value="${i.id}" data-price="${i.sale_price}" data-gst="${i.gst_percent}">${i.item_name} (${i.item_code})</option>`).join('')}
            </select>
        </td>
        <td><input type="number" name="qty[]" value="1" min="1" class="qty-input" oninput="recalcLine(this)"></td>
        <td><input type="number" name="purchase_price[]" step="0.01" value="0" class="price-input" oninput="recalcLine(this)"></td>
        <td><input type="number" name="line_gst[]" step="0.01" value="18" class="gst-input" oninput="recalcLine(this)"></td>
        <td class="num line-total mono">₹0.00</td>
        <td><button type="button" class="btn btn-icon btn-sm" onclick="removeLine(this)"><?= icon('trash') ?></button></td>
    `;
    tbody.appendChild(row);
}

function onItemChange(sel) {
    const opt = sel.options[sel.selectedIndex];
    const row = sel.closest('tr');
    row.querySelector('.price-input').value = opt.dataset.price || 0;
    row.querySelector('.gst-input').value = opt.dataset.gst || 18;
    recalcLine(sel);
}

function removeLine(btn) {
    btn.closest('tr').remove();
    recalcTotals();
}

function recalcLine(el) {
    const row = el.closest('tr');
    const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
    const price = parseFloat(row.querySelector('.price-input').value) || 0;
    const gst = parseFloat(row.querySelector('.gst-input').value) || 0;
    const subtotal = qty * price;
    const gstAmt = subtotal * gst / 100;
    const total = subtotal + gstAmt;
    row.querySelector('.line-total').textContent = '₹' + total.toFixed(2);
    recalcTotals();
}

function recalcTotals() {
    let subtotal = 0, gstTotal = 0;
    document.querySelectorAll('#lineItemsBody tr').forEach(row => {
        const qty = parseFloat(row.querySelector('.qty-input')?.value) || 0;
        const price = parseFloat(row.querySelector('.price-input')?.value) || 0;
        const gst = parseFloat(row.querySelector('.gst-input')?.value) || 0;
        const s = qty * price;
        subtotal += s;
        gstTotal += s * gst / 100;
    });
    document.getElementById('sumSubtotal').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('sumGst').textContent = '₹' + gstTotal.toFixed(2);
    document.getElementById('sumTotal').textContent = '₹' + (subtotal + gstTotal).toFixed(2);
}

// Add first line by default
addLine();
</script>

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