<?php
require_once '../includes/auth.php';
requirePermission('purchases', 'edit');
require_once '../db.php';

/* ==============================
   UPDATE PURCHASE TOTALS
   ============================== */
function updatePurchaseTotals(mysqli $conn, int $purchase_id, float $round_off = 0.0,
                              string $disc_type = '', float $disc_value = 0.0)
{
    $res = $conn->query("
        SELECT purchase_price, quantity, gst_percent, disc_type, disc_value
        FROM purchase_items WHERE purchase_order_id = $purchase_id
    ");
    $total_taxable = 0.0; $total_gst = 0.0;
    while ($r = $res->fetch_assoc()) {
        $pp = (float)$r['purchase_price']; $qty = (float)$r['quantity']; $gst = (float)$r['gst_percent'];
        $dt = $r['disc_type']; $dv = (float)$r['disc_value'];
        $eff = $pp;
        if ($dt === 'percent') $eff = $pp * (1 - $dv / 100);
        elseif ($dt === 'amount') $eff = $pp - $dv;
        $eff = max(0, $eff);
        $total_taxable += $eff * $qty;
        $total_gst     += $eff * $qty * $gst / 100;
    }
    $sub = $total_taxable + $total_gst;
    if ($disc_type === 'percent') $sub = $sub * (1 - $disc_value / 100);
    elseif ($disc_type === 'amount') $sub = $sub - $disc_value;
    $sub  = max(0, $sub);
    $net  = round($sub + $round_off, 2);
    $total_taxable = round($total_taxable, 2);
    $total_gst     = round($total_gst, 2);
    $stmt = $conn->prepare("UPDATE purchase_orders SET total_amount=?, gst_amount=?, net_amount=?, round_off=?, discount_type=?, discount_value=? WHERE id=?");
    $stmt->bind_param("ddddsdi", $total_taxable, $total_gst, $net, $round_off, $disc_type, $disc_value, $purchase_id);
    $stmt->execute();
}

/* ==============================
   SAVE PURCHASE (EDIT MODE)
   ============================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action      = $_POST['action'] ?? 'save';
    $purchase_id = (int)$_GET['id'];
    $round_off   = (float)($_POST['round_off'] ?? 0);

    $product_ids        = $_POST['product_id'];
    $item_ids           = $_POST['purchase_item_id'];
    $descriptions       = $_POST['description'] ?? [];
    $batch_nos          = $_POST['batch_no'];
    $mrps               = $_POST['mrp'];
    $purchase_prices    = $_POST['purchase_price'];
    $quantities         = $_POST['quantity'];
    $gst_percents       = $_POST['gst_percent'];
    $disc_types         = $_POST['disc_type'] ?? [];
    $disc_values        = $_POST['disc_value'] ?? [];
    $overall_disc_type  = $_POST['overall_discount_type'] ?? '';
    $overall_disc_value = (float)($_POST['overall_discount_value'] ?? 0);

    /* Duplicate check */
    $combo = [];
    for ($i = 0; $i < count($product_ids); $i++) {
        if (empty($product_ids[$i])) continue;
        $key = $product_ids[$i] . '|' . trim($batch_nos[$i] ?? '');
        if (isset($combo[$key])) die("Duplicate product with same batch not allowed.");
        $combo[$key] = true;
    }

    $conn->begin_transaction();
    try {
        $existing = [];
        foreach ($item_ids as $iid) { if (!empty($iid)) $existing[] = (int)$iid; }

        if ($existing) {
            $idList = implode(',', $existing);
            $conn->query("DELETE FROM purchase_items WHERE purchase_order_id = $purchase_id AND id NOT IN ($idList)");
        } else {
            $conn->query("DELETE FROM purchase_items WHERE purchase_order_id = $purchase_id");
        }

        $insert = $conn->prepare("
            INSERT INTO purchase_items
            (purchase_order_id, product_id, description, batch_no, mrp, purchase_price, selling_price,
             quantity, available_qty, gst_percent, disc_type, disc_value)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $update = $conn->prepare("
            UPDATE purchase_items SET
                product_id=?, description=?, batch_no=?, mrp=?, purchase_price=?, selling_price=?,
                available_qty=GREATEST(0, available_qty + ? - quantity),
                quantity=?, gst_percent=?, disc_type=?, disc_value=?
            WHERE id=? AND purchase_order_id=?
        ");

        for ($i = 0; $i < count($product_ids); $i++) {
            if (empty($product_ids[$i]) ||
                $quantities[$i] <= 0 || $purchase_prices[$i] <= 0) continue;

            $gst   = (float)$gst_percents[$i];
            $desc  = $descriptions[$i] ?? '';
            $dt    = $disc_types[$i]  ?? '';
            $dv    = (float)($disc_values[$i] ?? 0);
            $batch = !empty($batch_nos[$i]) ? $batch_nos[$i] : date('Ymd');

            $selling_price = 0.0;
            if (!empty($item_ids[$i])) {
                $update->bind_param("issddddddsdii",
                    $product_ids[$i], $desc, $batch, $mrps[$i],
                    $purchase_prices[$i], $selling_price,
                    $quantities[$i], $quantities[$i], $gst, $dt, $dv, $item_ids[$i], $purchase_id);
                $update->execute();
            } else {
                $insert->bind_param("iissddddddsd",
                    $purchase_id, $product_ids[$i], $desc, $batch, $mrps[$i],
                    $purchase_prices[$i], $selling_price,
                    $quantities[$i], $quantities[$i], $gst, $dt, $dv);
                $insert->execute();
            }
        }

        updatePurchaseTotals($conn, $purchase_id, $round_off, $overall_disc_type, $overall_disc_value);

        if ($action === 'final') {
            $conn->query("UPDATE purchase_orders SET status = 'final' WHERE id = $purchase_id");
            $conn->query("DELETE FROM stock_movements WHERE reference_id = $purchase_id AND reference_type = 'purchase'");

            $resMove = $conn->query("SELECT id, product_id, quantity FROM purchase_items WHERE purchase_order_id = $purchase_id");
            while ($m = $resMove->fetch_assoc()) {
                $purchase_item_id = (int)$m['id'];
                $product_id       = (int)$m['product_id'];
                $qty              = (float)$m['quantity'];
                $stmtMove = $conn->prepare("INSERT INTO stock_movements (product_id, purchase_item_id, type, quantity, reference_id, reference_type) VALUES (?, ?, 'IN', ?, ?, 'purchase')");
                $stmtMove->bind_param("iidi", $product_id, $purchase_item_id, $qty, $purchase_id);
                $stmtMove->execute();
            }
        }

        $conn->commit();

        if ($action === 'final') {
            header("Location: view.php?id=$purchase_id");
        } else {
            header("Location: edit.php?id=$purchase_id&saved=1");
        }
        exit;
    } catch (Exception $e) {
        $conn->rollback();
        die("Save failed: " . $e->getMessage());
    }
}

/* ==============================
   LOAD UI
   ============================== */
$id = (int)$_GET['id'];

$purchase = $conn->query("
    SELECT po.*, v.name AS vendor_name
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    WHERE po.id = $id AND po.company_id = $cid
")->fetch_assoc();
if (!$purchase) die('Purchase not found');

$items = [];
$res = $conn->query("
    SELECT pi.*, p.name AS product_name
    FROM purchase_items pi
    JOIN products p ON p.id = pi.product_id
    WHERE pi.purchase_order_id = $id
");
while ($r = $res->fetch_assoc()) {
    $items[] = $r;
}

$readonly = ($purchase['status'] === 'final') ? 'disabled' : '';
$isFinal  = ($purchase['status'] === 'final');

$prefRow = $conn->query("SELECT invoice_prefix FROM company_master WHERE id = $cid LIMIT 1")->fetch_assoc();
$companyPrefix = $prefRow['invoice_prefix'] ?? '';

$products = [];
$pq = $conn->query("SELECT p.id, p.name,
    COALESCE((SELECT SUM(pi.available_qty) FROM purchase_items pi
        JOIN purchase_orders po ON po.id = pi.purchase_order_id
        WHERE pi.product_id = p.id AND pi.available_qty > 0
        AND po.status = 'final' AND po.company_id = $cid), 0) AS available_qty,
    GREATEST(COALESCE(p.selling_price, 0), COALESCE((SELECT si.selling_price_incl
        FROM sales_items si JOIN sales_invoices inv ON inv.id = si.sales_invoice_id
        WHERE si.product_id = p.id AND inv.company_id = $cid
        ORDER BY si.id DESC LIMIT 1), 0)) AS sell_price,
    COALESCE((SELECT pi2.purchase_price FROM purchase_items pi2
        JOIN purchase_orders po2 ON po2.id = pi2.purchase_order_id
        WHERE pi2.product_id = p.id AND po2.company_id = $cid AND po2.status = 'final'
        ORDER BY pi2.id DESC LIMIT 1), 0) AS last_purchase_price,
    COALESCE((SELECT pi2.gst_percent FROM purchase_items pi2
        JOIN purchase_orders po2 ON po2.id = pi2.purchase_order_id
        WHERE pi2.product_id = p.id AND po2.company_id = $cid AND po2.status = 'final'
        ORDER BY pi2.id DESC LIMIT 1), 0) AS last_gst_percent,
    COALESCE((SELECT pi2.mrp FROM purchase_items pi2
        JOIN purchase_orders po2 ON po2.id = pi2.purchase_order_id
        WHERE pi2.product_id = p.id AND po2.company_id = $cid AND po2.status = 'final'
        ORDER BY pi2.id DESC LIMIT 1), 0) AS last_mrp
FROM products p WHERE p.status = 1 AND p.company_id = $cid ORDER BY p.name");
while ($p = $pq->fetch_assoc()) {
    $p['code'] = $companyPrefix . '-' . $p['id'];
    $products[] = $p;
}

$savedRoundOff = (float)($purchase['round_off'] ?? 0);

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="page-header">
    <div>
        <h2><i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>Edit Purchase</h2>
        <div style="display:flex;gap:16px;font-size:13px;color:var(--text-secondary);margin-top:4px;">
            <span><strong>PO:</strong> <?= htmlspecialchars($purchase['po_no']) ?></span>
            <span><strong>Vendor:</strong> <?= htmlspecialchars($purchase['vendor_name']) ?></span>
            <span><strong>Date:</strong> <?= htmlspecialchars($purchase['purchase_date']) ?></span>
            <?php if ($purchase['supplier_invoice_no']): ?>
            <span><strong>Supplier Inv:</strong> <?= htmlspecialchars($purchase['supplier_invoice_no']) ?></span>
            <?php endif; ?>
        </div>
    </div>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<?php if (isset($_GET['saved'])): ?>
<div class="alert alert-success" style="margin-bottom:12px;">
    <i class="fas fa-check-circle"></i> Purchase saved as draft.
</div>
<?php endif; ?>

<?php if ($isFinal): ?>
<div class="alert alert-warning" style="margin-bottom:16px;">
    <i class="fas fa-lock"></i>
    This purchase is <strong>finalized</strong> and cannot be edited.
</div>
<?php endif; ?>


<form method="post" id="purchaseForm">

<!-- Line Items -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header">
        <span class="panel-title">Purchase Items</span>
        <div style="display:flex;gap:8px;align-items:center;">
            <div style="position:relative;">
                <i class="fas fa-search" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:12px;pointer-events:none;"></i>
                <input type="text" id="itemSearch" placeholder="Search product..."
                       oninput="filterItems(this.value)"
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:180px;">
            </div>
            <?php if (!$isFinal): ?>
            <button type="button" id="addRowBtn" class="btn btn-outline btn-sm">
                <i class="fas fa-plus"></i> Add Row
            </button>
            <button type="button" onclick="openAIModal()" class="btn btn-outline btn-sm"
                    style="color:var(--primary);border-color:var(--primary);"
                    title="Extract data from invoice image or PDF">
                <i class="fas fa-magic"></i> AI Extract
            </button>
            <?php endif; ?>
        </div>
    </div>
    <?php if (!$isFinal): ?>
    <div id="quickAddBar" style="padding:10px 14px;background:#f0f7ff;border-bottom:1px solid #bfdbfe;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
        <div style="position:relative;flex:1;min-width:200px;">
            <i class="fas fa-search" style="position:absolute;left:9px;top:50%;transform:translateY(-50%);color:#93c5fd;font-size:12px;pointer-events:none;z-index:1;"></i>
            <input type="text" id="quickSearchPurchase" class="pac-input"
                   placeholder="Search product to add..."
                   autocomplete="off" style="padding:6px 8px 6px 32px;width:100%;font-size:13px;">
        </div>
        <input type="number" id="quickQtyPurchase" min="0.01" step="0.01" value="1" placeholder="Qty"
               style="width:72px;padding:6px 8px;font-size:13px;border:1px solid var(--border);border-radius:6px;">
        <button type="button" id="quickAddPurchaseBtn" class="btn btn-primary btn-sm">
            <i class="fas fa-plus"></i> Add to Purchase
        </button>
        <span id="quickPurchaseMsg" style="font-size:12px;color:var(--danger);display:none;font-weight:500;"></span>
    </div>
    <?php endif; ?>
    <div class="items-scroll-wrap">
        <table id="purchaseTable" style="width:100%;table-layout:fixed;">
            <colgroup>
                <col style="width:32px;">
                <col style="width:68px;">
                <col style="min-width:180px;width:25%;">
                <col style="width:80px;">
                <col style="width:110px;">
                <col style="width:62px;">
                <col style="width:55px;">
                <col style="width:155px;">
                <col style="width:88px;">
                <?php if (!$isFinal): ?><col style="width:40px;"><?php endif; ?>
            </colgroup>
            <thead>
                <tr>
                    <th style="text-align:center;">#</th>
                    <th style="text-align:center;font-size:10px;">Code</th>
                    <th>Product / Description
                        <label style="font-weight:400;text-transform:none;font-size:11px;margin-left:6px;cursor:pointer;">
                            <input type="checkbox" id="descToggle" onchange="toggleDescriptions()" style="margin-right:3px;">Desc
                        </label>
                    </th>
                    <th>MRP</th>
                    <th>Purchase Price<br><small style="font-weight:400;text-transform:none;">(excl GST)</small></th>
                    <th>Qty</th>
                    <th>GST %</th>
                    <th>Discount</th>
                    <th style="text-align:right;">Row Total</th>
                    <?php if (!$isFinal): ?><th></th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
            <?php if ($items): foreach ($items as $i => $it): ?>
            <tr>
                <td class="rowNum" style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $i + 1 ?></td>
                <td class="prodCode" style="text-align:center;">
                    <?php if ($companyPrefix && !empty($it['product_id'])): ?>
                    <span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;"><?= htmlspecialchars($companyPrefix . '-' . $it['product_id']) ?></span>
                    <?php else: ?><span style="color:var(--text-muted);">—</span><?php endif; ?>
                </td>
                <td>
                    <input <?= $readonly ?> type="text" name="product_name[]"
                           class="productInput pac-input" autocomplete="off"
                           value="<?= htmlspecialchars($it['product_name']) ?>"
                           style="width:100%;min-width:0;">
                    <input type="hidden" name="product_id[]" value="<?= $it['product_id'] ?>">
                    <?php if (!$isFinal): ?>
                    <button type="button" class="addProductBtn btn btn-outline btn-sm"
                            style="display:none;margin-top:2px;">+ New</button>
                    <?php endif; ?>
                    <input type="hidden" name="purchase_item_id[]" value="<?= $it['id'] ?>">
                    <div class="prod-desc-wrap"><textarea <?= $readonly ?> name="description[]" rows="1" placeholder="Description (optional)"
                              style="width:100%;margin-top:3px;font-size:11px;padding:2px 4px;resize:none;border:1px solid var(--border);border-radius:4px;"><?= htmlspecialchars($it['description'] ?? '') ?></textarea></div>
                </td>
                <td style="display:none;"><input type="hidden" name="batch_no[]" value="<?= htmlspecialchars($it['batch_no']) ?>"></td>
                <td><input <?= $readonly ?> name="mrp[]" value="<?= $it['mrp'] ?>"></td>
                <td><input <?= $readonly ?> name="purchase_price[]" value="<?= $it['purchase_price'] ?>"></td>
                <td><input <?= $readonly ?> name="quantity[]" value="<?= $it['quantity'] ?>"></td>
                <td><input <?= $readonly ?> name="gst_percent[]" value="<?= $it['gst_percent'] ?>" style="width:50px;"></td>
                <td>
                    <div style="display:flex;gap:3px;align-items:center;">
                        <select <?= $readonly ?> name="disc_type[]" class="discType" style="font-size:11px;padding:3px 4px;border:1px solid var(--border);border-radius:4px;width:72px;">
                            <option value="" <?= ($it['disc_type']??'')=='' ? 'selected':'' ?>>None</option>
                            <option value="percent" <?= ($it['disc_type']??'')==='percent' ? 'selected':'' ?>>%</option>
                            <option value="amount" <?= ($it['disc_type']??'')==='amount' ? 'selected':'' ?>>₹</option>
                        </select>
                        <input <?= $readonly ?> name="disc_value[]" class="discValue" type="number" step="0.01" min="0"
                               value="<?= $it['disc_value'] ?? 0 ?>"
                               style="width:72px;font-size:11px;" placeholder="0">
                    </div>
                </td>
                <td style="text-align:right;font-weight:600;"><span class="rowTotal">0.00</span></td>
                <?php if (!$isFinal): ?>
                <td>
                    <button type="button" class="removeRow action-btn delete" <?= $i == 0 ? 'disabled' : '' ?> title="Remove">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
                <?php endif; ?>
            </tr>
            <?php endforeach; else: ?>
            <tr>
                <td class="rowNum" style="text-align:center;color:var(--text-muted);font-size:12px;">1</td>
                <td class="prodCode" style="text-align:center;color:var(--text-muted);font-size:11px;">—</td>
                <td>
                    <input type="text" name="product_name[]" class="productInput pac-input" autocomplete="off" placeholder="Code or name..." style="width:100%;min-width:0;">
                    <input type="hidden" name="product_id[]">
                    <button type="button" class="addProductBtn btn btn-outline btn-sm" style="display:none;margin-top:2px;">+ New</button>
                    <input type="hidden" name="purchase_item_id[]">
                    <div class="prod-desc-wrap"><textarea name="description[]" rows="1" placeholder="Description (optional)"
                              style="width:100%;margin-top:3px;font-size:11px;padding:2px 4px;resize:none;border:1px solid var(--border);border-radius:4px;"></textarea></div>
                </td>
                <td style="display:none;"><input type="hidden" name="batch_no[]"></td>
                <td><input name="mrp[]" placeholder="0.00"></td>
                <td><input name="purchase_price[]" placeholder="0.00"></td>
                <td><input name="quantity[]" placeholder="0"></td>
                <td><input name="gst_percent[]" placeholder="0" style="width:50px;"></td>
                <td>
                    <div style="display:flex;gap:3px;align-items:center;">
                        <select name="disc_type[]" class="discType" style="font-size:11px;padding:3px 4px;border:1px solid var(--border);border-radius:4px;width:72px;">
                            <option value="">None</option>
                            <option value="percent">%</option>
                            <option value="amount">₹</option>
                        </select>
                        <input name="disc_value[]" class="discValue" type="number" step="0.01" min="0"
                               value="0" style="width:72px;font-size:11px;" placeholder="0">
                    </div>
                </td>
                <td style="text-align:right;"><span class="rowTotal">0.00</span></td>
                <td>
                    <button type="button" class="removeRow action-btn delete" disabled title="Remove">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Totals -->
<div style="display:flex;justify-content:flex-end;margin-bottom:16px;">
    <div class="totals-box" style="min-width:300px;">
        <div class="totals-row">
            <span>Taxable Total</span>
            <span>&#8377; <span id="taxableTotal">0.00</span></span>
        </div>
        <div class="totals-row">
            <span>GST Total</span>
            <span>&#8377; <span id="gstTotal">0.00</span></span>
        </div>
        <div class="totals-row">
            <span>Sub Total</span>
            <span>&#8377; <span id="subTotal">0.00</span></span>
        </div>
        <?php if (!$isFinal): ?>
        <div class="totals-row">
            <span>Overall Discount</span>
            <span style="display:flex;align-items:center;gap:4px;justify-content:flex-end;">
                <select id="overallDiscType" name="overall_discount_type"
                        onchange="recalcTotals()"
                        style="font-size:12px;padding:3px 5px;border:1px solid var(--border);border-radius:4px;">
                    <option value="" <?= ($purchase['discount_type']??'')=='' ? 'selected':'' ?>>None</option>
                    <option value="percent" <?= ($purchase['discount_type']??'')==='percent' ? 'selected':'' ?>>%</option>
                    <option value="amount" <?= ($purchase['discount_type']??'')==='amount' ? 'selected':'' ?>>₹ Amount</option>
                </select>
                <input type="number" step="0.01" min="0" name="overall_discount_value" id="overallDiscValue"
                       value="<?= number_format((float)($purchase['discount_value']??0), 2, '.', '') ?>"
                       oninput="recalcTotals()"
                       style="width:90px;text-align:right;padding:2px 6px;font-size:13px;">
            </span>
        </div>
        <?php else: ?>
        <?php if (($purchase['discount_type']??'') !== '' && (float)($purchase['discount_value']??0) > 0): ?>
        <div class="totals-row">
            <span>Overall Discount</span>
            <span style="color:var(--danger);">
                - &#8377; <?= number_format((float)$purchase['discount_value'], 2) ?>
                <?= $purchase['discount_type'] === 'percent' ? '(' . $purchase['discount_value'] . '%)' : '' ?>
            </span>
        </div>
        <?php endif; ?>
        <?php endif; ?>
        <div class="totals-row">
            <span>Round Off</span>
            <span style="display:flex;align-items:center;gap:4px;justify-content:flex-end;">
                <?php if (!$isFinal): ?>
                <input type="number" step="0.01" name="round_off" id="roundOff"
                       value="<?= number_format($savedRoundOff, 2, '.', '') ?>"
                       style="width:85px;text-align:right;padding:2px 6px;font-size:13px;"
                       oninput="recalcTotals()">
                <button type="button" onclick="autoRound()" class="btn btn-outline btn-sm"
                        style="padding:2px 8px;font-size:11px;" title="Round to nearest rupee">Auto</button>
                <?php else: ?>
                <span>&#8377; <?= number_format($savedRoundOff, 2) ?></span>
                <?php endif; ?>
            </span>
        </div>
        <div class="totals-row grand-total">
            <span>Net Payable</span>
            <span>&#8377; <span id="netTotal">0.00</span></span>
        </div>
    </div>
</div>

<!-- Actions -->
<?php if (!$isFinal): ?>
<div style="display:flex;gap:12px;">
    <button type="submit" name="action" value="save" class="btn btn-secondary">
        <i class="fas fa-save"></i> Save Draft
    </button>
    <button type="submit" name="action" value="final" class="btn btn-success"
            onclick="return confirm('Finalize this purchase? Stock will be updated.')">
        <i class="fas fa-check-circle"></i> Complete Purchase
    </button>
</div>
<?php endif; ?>

</form>

<!-- Add Product Modal -->
<div id="productModal" class="modal-overlay" style="display:none;">
    <div class="modal-box">
        <div class="modal-header">
            <span><i class="fas fa-plus-circle" style="margin-right:8px;"></i>Add New Product</span>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Product Name <span style="color:var(--danger)">*</span></label>
                    <input type="text" id="new_name" placeholder="Product name">
                </div>
                <div class="form-group">
                    <label>Brand</label>
                    <input type="text" id="new_brand" placeholder="Brand">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Category</label>
                    <input type="text" id="new_category" placeholder="Category">
                </div>
                <div class="form-group">
                    <label>Unit</label>
                    <input type="text" id="new_unit" placeholder="e.g. PCS, KG">
                </div>
            </div>
            <div class="form-group">
                <label>HSN Code</label>
                <input type="text" id="new_hsn" placeholder="HSN code">
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
            <button class="btn btn-primary" id="saveProductBtn"><i class="fas fa-save"></i> Save Product</button>
        </div>
    </div>
</div>

<script src="../assets/js/product_ac.js"></script>
<script>
const PRODUCTS = <?= json_encode($products) ?>;
const COMPANY_PREFIX = '<?= addslashes($companyPrefix) ?>';
initProductAC(PRODUCTS);

// Update code cell when a product is selected via the autocomplete
let _quickPurchaseProduct = null;
document.addEventListener('pac:select', function(e) {
    if (e.target.id === 'quickSearchPurchase') {
        // pac:select only carries {id, name, code} — look up full record for last_* fields
        _quickPurchaseProduct = PRODUCTS.find(p => parseInt(p.id) === e.detail.id) || e.detail;
        return;
    }
    const row = e.target.closest('tr');
    if (!row) return;
    const cell = row.querySelector('.prodCode');
    if (!cell) return;
    const code = e.detail.code || (COMPANY_PREFIX + '-' + e.detail.id);
    cell.innerHTML = '<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;">' + code + '</span>';
});

let activeInput = null;
const table = document.getElementById('purchaseTable');

function showQuickPurchaseMsg(msg) {
    const el = document.getElementById('quickPurchaseMsg');
    if (!el) return;
    el.textContent = msg;
    el.style.display = msg ? 'inline' : 'none';
}

const quickAddPurchaseBtn = document.getElementById('quickAddPurchaseBtn');
if (quickAddPurchaseBtn) {
    quickAddPurchaseBtn.addEventListener('click', function() {
        if (!_quickPurchaseProduct) {
            showQuickPurchaseMsg('Please select a product from the list first.');
            return;
        }
        const qty = parseFloat(document.getElementById('quickQtyPurchase').value) || 1;
        if (qty <= 0) { showQuickPurchaseMsg('Quantity must be greater than 0.'); return; }
        showQuickPurchaseMsg('');

        // Reuse the last row if it's blank, otherwise add a new one
        const tbody = table.querySelector('tbody');
        const lastRow = tbody.rows[tbody.rows.length - 1];
        const lastPid  = lastRow.querySelector('input[name="product_id[]"]')?.value || '';
        const lastName = (lastRow.querySelector('input[name="product_name[]"]')?.value || '').trim();
        let newRow;
        if (!lastPid && !lastName) {
            newRow = lastRow;
        } else {
            document.getElementById('addRowBtn').click();
            newRow = tbody.rows[tbody.rows.length - 1];
        }

        // Fill product name & id
        const nameInput = newRow.querySelector('input[name="product_name[]"]');
        const hiddenId  = newRow.querySelector('input[name="product_id[]"]');
        if (nameInput) nameInput.value = _quickPurchaseProduct.name;
        if (hiddenId)  hiddenId.value  = _quickPurchaseProduct.id;

        // Fill code cell
        const codeCell = newRow.querySelector('.prodCode');
        if (codeCell) {
            const code = _quickPurchaseProduct.code || (COMPANY_PREFIX + '-' + _quickPurchaseProduct.id);
            codeCell.innerHTML = '<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;">' + code + '</span>';
        }

        // Fill qty
        const qtyInput = newRow.querySelector('input[name="quantity[]"]');
        if (qtyInput) qtyInput.value = qty;

        // Pre-fill from last purchase history (all fields remain editable)
        const priceInput = newRow.querySelector('input[name="purchase_price[]"]');
        if (priceInput && _quickPurchaseProduct.last_purchase_price > 0)
            priceInput.value = _quickPurchaseProduct.last_purchase_price;

        const gstInput = newRow.querySelector('input[name="gst_percent[]"]');
        if (gstInput && _quickPurchaseProduct.last_gst_percent > 0)
            gstInput.value = _quickPurchaseProduct.last_gst_percent;

        const mrpInput = newRow.querySelector('input[name="mrp[]"]');
        if (mrpInput && _quickPurchaseProduct.last_mrp > 0)
            mrpInput.value = _quickPurchaseProduct.last_mrp;

        recalcTotals();

        // Reset quick-add bar
        _quickPurchaseProduct = null;
        document.getElementById('quickSearchPurchase').value = '';
        document.getElementById('quickQtyPurchase').value = '1';

        // Focus purchase price for user to confirm/edit
        if (priceInput) setTimeout(function() { priceInput.focus(); }, 50);
    });
}

/* "Add New Product" from PAC dropdown */
_pacOnAddNew = function(prefill) {
    activeInput = _pacActiveInput;
    document.getElementById('productModal').style.display = 'flex';
    if (prefill) document.getElementById('new_name').value = prefill;
};

/* addProductBtn (still shown for manual "+" click) */
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('addProductBtn') || e.target.closest('.addProductBtn')) {
        const td = e.target.closest('td');
        activeInput = td ? td.querySelector('.productInput') : null;
        document.getElementById('productModal').style.display = 'flex';
    }
});

document.getElementById('saveProductBtn').onclick = function() {
    const fd = new FormData();
    fd.append('name', document.getElementById('new_name').value);
    fd.append('brand', document.getElementById('new_brand').value);
    fd.append('category', document.getElementById('new_category').value);
    fd.append('unit', document.getElementById('new_unit').value);
    fd.append('hsn', document.getElementById('new_hsn').value);

    fetch('ajax_add_product.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'ok') {
            const newCode = COMPANY_PREFIX + '-' + res.id;
            const newProduct = { id: res.id, name: res.name, code: newCode,
                                 last_purchase_price: 0, last_gst_percent: 0, last_mrp: 0 };
            PRODUCTS.push(newProduct);
            PRODUCTS.sort((a,b) => a.name.localeCompare(b.name));
            initProductAC(PRODUCTS);
            const inp = activeInput || _pacActiveInput;
            if (inp && inp.id === 'quickSearchPurchase') {
                _quickPurchaseProduct = newProduct;
                inp.value = res.name;
            } else if (inp) {
                const td = inp.closest('td');
                inp.value = res.name;
                if (td) td.querySelector('input[name="product_id[]"]').value = res.id;
                if (td && td.querySelector('.addProductBtn'))
                    td.querySelector('.addProductBtn').style.display = 'none';
                const tr = td ? td.closest('tr') : null;
                const codeCell = tr ? tr.querySelector('.prodCode') : null;
                if (codeCell) codeCell.innerHTML = '<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;">' + newCode + '</span>';
            }
            closeModal();
        } else { alert(res.msg); }
    });
};

function closeModal() { document.getElementById('productModal').style.display = 'none'; }

/* Row numbering */
function toggleDescriptions() {
    document.getElementById('purchaseTable').classList.toggle('show-desc',
        document.getElementById('descToggle').checked);
}

function updateRowNums() {
    table.querySelectorAll('tbody tr').forEach((row, idx) => {
        const cell = row.querySelector('.rowNum');
        if (cell) cell.innerText = idx + 1;
    });
}

/* Add / Remove rows */
document.getElementById('addRowBtn') && document.getElementById('addRowBtn').addEventListener('click', function() {
    const tbody = table.querySelector('tbody');
    const firstRow = tbody.rows[0].cloneNode(true);
    firstRow.querySelectorAll('input').forEach(i => { i.value = ''; i.disabled = false; });
    firstRow.querySelectorAll('textarea').forEach(t => { t.value = ''; t.disabled = false; });
    firstRow.querySelectorAll('select').forEach(s => { s.selectedIndex = 0; s.disabled = false; });
    firstRow.querySelector('.removeRow').disabled = false;
    firstRow.querySelector('.rowTotal').innerText = '0.00';
    const addBtn = firstRow.querySelector('.addProductBtn');
    if (addBtn) addBtn.style.display = 'none';
    firstRow.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
    const codeCell = firstRow.querySelector('.prodCode');
    if (codeCell) codeCell.innerHTML = '<span style="color:var(--text-muted);">—</span>';
    tbody.appendChild(firstRow);
    generateBatch();
    updateRowNums();
    setTimeout(recalcTotals, 100);
});

table.addEventListener('click', function(e) {
    const btn = e.target.closest('.removeRow');
    if (btn && !btn.disabled && table.querySelectorAll('tbody tr').length > 1) {
        btn.closest('tr').remove();
        generateBatch();
        updateRowNums();
        recalcTotals();
    }
});

/* Batch auto-generate */
function today() {
    const d = new Date();
    return d.getFullYear() + String(d.getMonth()+1).padStart(2,'0') + String(d.getDate()).padStart(2,'0');
}
function generateBatch() {
    let i = 1;
    table.querySelectorAll('tbody tr').forEach(row => {
        const b = row.querySelector('input[name="batch_no[]"]');
        if (b && b.value === '') b.value = `BATCH-${today()}-${String(i).padStart(3,'0')}`;
        i++;
    });
}
generateBatch();

/* Duplicate check on submit */
document.getElementById('purchaseForm').addEventListener('submit', function(e) {
    const seen = new Set(); let dup = false;
    table.querySelectorAll('tbody tr').forEach(row => {
        const pid   = row.querySelector('input[name="product_id[]"]')?.value;
        const batch = row.querySelector('input[name="batch_no[]"]')?.value.trim();
        if (!pid || !batch) return;
        const key = pid + '|' + batch;
        if (seen.has(key)) { dup = true; row.style.background = '#fff3cd'; }
        else { seen.add(key); row.style.background = ''; }
    });
    if (dup) { e.preventDefault(); alert('Duplicate product with same batch is not allowed.'); }
});

/* Calculations */
function recalcTotals() {
    let taxable = 0, gst = 0;
    table.querySelectorAll('tbody tr').forEach(row => {
        const price = parseFloat(row.querySelector('input[name="purchase_price[]"]')?.value || 0);
        const qty   = parseFloat(row.querySelector('input[name="quantity[]"]')?.value || 0);
        const gstp  = parseFloat(row.querySelector('input[name="gst_percent[]"]')?.value || 0);
        const dt    = row.querySelector('select[name="disc_type[]"]')?.value || '';
        const dv    = parseFloat(row.querySelector('input[name="disc_value[]"]')?.value || 0);
        let eff = price;
        if (dt === 'percent') eff = price * (1 - dv / 100);
        else if (dt === 'amount') eff = price - dv;
        eff = Math.max(0, eff);
        const rowTaxable = eff * qty;
        const rowGst = rowTaxable * gstp / 100;
        taxable += rowTaxable;
        gst += rowGst;
        const span = row.querySelector('.rowTotal');
        if (span) span.innerText = rowTaxable.toFixed(2);
    });
    const sub = taxable + gst;
    const odType  = document.getElementById('overallDiscType')?.value || '';
    const odValue = parseFloat(document.getElementById('overallDiscValue')?.value || 0);
    let discounted = sub;
    if (odType === 'percent') discounted = sub * (1 - odValue / 100);
    else if (odType === 'amount') discounted = sub - odValue;
    discounted = Math.max(0, discounted);
    const autoRO = Math.round(discounted) - discounted;
    const roEl = document.getElementById('roundOff');
    if (roEl) roEl.value = autoRO.toFixed(2);
    document.getElementById('taxableTotal').innerText = taxable.toFixed(2);
    document.getElementById('gstTotal').innerText = gst.toFixed(2);
    document.getElementById('subTotal').innerText = sub.toFixed(2);
    document.getElementById('netTotal').innerText = (discounted + autoRO).toFixed(2);
}

function autoRound() {
    // Compute discounted sub before round-off
    const sub = parseFloat(document.getElementById('subTotal').innerText || 0);
    const odType  = document.getElementById('overallDiscType')?.value || '';
    const odValue = parseFloat(document.getElementById('overallDiscValue')?.value || 0);
    let discounted = sub;
    if (odType === 'percent') discounted = sub * (1 - odValue / 100);
    else if (odType === 'amount') discounted = sub - odValue;
    discounted = Math.max(0, discounted);
    const rounded = Math.round(discounted);
    document.getElementById('roundOff').value = (rounded - discounted).toFixed(2);
    recalcTotals();
}

document.addEventListener('input', function(e) {
    if (['purchase_price[]', 'quantity[]', 'gst_percent[]', 'disc_value[]'].includes(e.target.name)) recalcTotals();
});
document.addEventListener('change', function(e) {
    if (e.target.name === 'disc_type[]') recalcTotals();
});

recalcTotals();

function filterItems(q) {
    const term = q.trim().toLowerCase();
    document.querySelectorAll('#purchaseTable tbody tr').forEach(tr => {
        const name = (tr.querySelector('input[name="product_name[]"]')?.value || '').toLowerCase();
        tr.style.display = (!term || name.includes(term)) ? '' : 'none';
    });
}

/* ---- AI Extract ---- */
function openAIModal() { document.getElementById('aiModal').style.display = 'flex'; }
function closeAIModal() { document.getElementById('aiModal').style.display = 'none'; }

function runAIExtract() {
    const fileInput = document.getElementById('aiFileInput');
    if (!fileInput.files.length) { alert('Please select a file.'); return; }
    const statusEl = document.getElementById('aiStatus');
    statusEl.textContent = 'Extracting... please wait.';
    statusEl.style.color = 'var(--text-muted)';

    const fd = new FormData();
    fd.append('file', fileInput.files[0]);
    fd.append('type', 'purchase');

    fetch('../includes/ai_extract.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(res => {
        if (res.error) { statusEl.textContent = 'Error: ' + res.error; statusEl.style.color = 'var(--danger)'; return; }
        const d = res.data;

        // Fill supplier invoice no if visible on page
        const sinEl = document.querySelector('input[name="supplier_invoice_no"]');
        if (sinEl && d.supplier_invoice_no) sinEl.value = d.supplier_invoice_no;

        // Populate items
        if (d.items && d.items.length) {
            const tbody = table.querySelector('tbody');
            // Keep first row, clear it
            let rows = tbody.querySelectorAll('tr');
            // Remove extra rows
            while (tbody.rows.length > d.items.length) tbody.deleteRow(1);
            // Add missing rows
            while (tbody.rows.length < d.items.length) {
                const nr = tbody.rows[0].cloneNode(true);
                nr.querySelectorAll('input').forEach(i => { i.value = ''; i.disabled = false; });
                nr.querySelectorAll('textarea').forEach(t => { t.value = ''; t.disabled = false; });
                nr.querySelector('.removeRow').disabled = false;
                nr.querySelector('.rowTotal').innerText = '0.00';
                tbody.appendChild(nr);
            }
            tbody.querySelectorAll('tr').forEach((row, idx) => {
                const item = d.items[idx];
                if (!item) return;
                const nameInput = row.querySelector('input[name="product_name[]"]');
                const hiddenId  = row.querySelector('input[name="product_id[]"]');
                if (nameInput) {
                    nameInput.value = item.product_name || '';
                    const exactMatch = PRODUCTS.find(p =>
                        p.name.toLowerCase() === (item.product_name || '').toLowerCase()
                    );
                    if (exactMatch) {
                        if (hiddenId) hiddenId.value = exactMatch.id;
                        const codeCell = row.querySelector('.prodCode');
                        if (codeCell) {
                            const c = exactMatch.code || (COMPANY_PREFIX + '-' + exactMatch.id);
                            codeCell.innerHTML = '<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;">' + c + '</span>';
                        }
                    } else if (item.product_name) {
                        if (hiddenId) hiddenId.value = '';
                        pacShowResolvePanel(nameInput, item.product_name, function(prefill) {
                            activeInput = nameInput;
                            document.getElementById('productModal').style.display = 'flex';
                            document.getElementById('new_name').value = prefill || '';
                        });
                    }
                }
                const set = (name, val) => { const el = row.querySelector(`input[name="${name}"]`); if (el && val != null) el.value = val; };
                if (item.batch_no)       set('batch_no[]',       item.batch_no);
                if (item.mrp)            set('mrp[]',            item.mrp);
                if (item.purchase_price) set('purchase_price[]', item.purchase_price);
                if (item.quantity)       set('quantity[]',       item.quantity);
                if (item.gst_percent != null) set('gst_percent[]', item.gst_percent);
            });
            generateBatch();
            updateRowNums();
            recalcTotals();
        }

        statusEl.textContent = 'Extracted successfully! Review and adjust the values.';
        statusEl.style.color = 'var(--success)';
        if (d.vendor_name) statusEl.textContent += ' Vendor: ' + d.vendor_name;
    })
    .catch(() => { statusEl.textContent = 'Request failed. Check API key and internet.'; statusEl.style.color = 'var(--danger)'; });
}
</script>

<!-- AI Extract Modal -->
<div id="aiModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;padding:24px;width:420px;max-width:95vw;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-magic" style="color:var(--primary);margin-right:8px;"></i>AI Extract from Invoice</h3>
            <button onclick="closeAIModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px;">
            Upload a photo or PDF of the supplier invoice and AI will extract product details automatically.
        </p>
        <div class="form-group">
            <label>Select Invoice File</label>
            <input type="file" id="aiFileInput" accept="image/*,.pdf" style="width:100%;">
        </div>
        <div id="aiStatus" style="font-size:13px;margin:8px 0;min-height:18px;"></div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:12px;">
            <button onclick="closeAIModal()" class="btn btn-secondary">Cancel</button>
            <button onclick="runAIExtract()" class="btn btn-primary"><i class="fas fa-magic"></i> Extract</button>
        </div>
    </div>
</div>

<style>
.items-scroll-wrap { overflow-x:auto; overflow-y:auto; max-height:52vh; }
.items-scroll-wrap thead th { position:sticky; top:0; background:#f1f5f9; z-index:10; box-shadow:0 1px 0 var(--border,#e2e8f0); }
#purchaseTable td { vertical-align: top; }
#purchaseTable .pac-input { display: block !important; width: 100% !important; box-sizing: border-box !important; padding: 3px 26px 3px 8px !important; }
#purchaseTable td textarea { display: block !important; width: 100% !important; box-sizing: border-box !important; margin-top: 3px; }
/* Description toggle */
.prod-desc-wrap { display:none; }
#purchaseTable.show-desc .prod-desc-wrap { display:block; }
</style>
<?php require_once '../includes/footer.php'; ?>
