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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid Invoice");

$inv = $conn->query("SELECT * FROM sales_invoices WHERE id = $id AND company_id = $cid")->fetch_assoc();
if (!$inv) die("Invoice not found");

if ($inv['status'] === 'final') {
    header("Location: view.php?id=" . $id);
    exit;
}

$clients  = $conn->query("SELECT id, name FROM clients WHERE status = 1 AND company_id = $cid ORDER BY name");

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

$productList = [];
$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
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'];
    $productList[] = $p;
}

$clientName = $conn->query("SELECT name FROM clients WHERE id=" . (int)$inv['client_id'])
                   ->fetch_assoc()['name'];

// Group existing items by product (FIFO may have split one product across batches)
$items = $conn->query("
    SELECT
        si.product_id,
        p.name AS product_name,
        SUM(si.sold_qty) AS total_qty,
        MAX(si.selling_price_incl) AS selling_price_incl,
        MAX(si.selling_price_excl) AS selling_price_excl,
        COALESCE(MAX(CASE WHEN si.discount_type IS NOT NULL AND si.discount_type != '' THEN si.discount_type END), '') AS discount_type,
        MAX(si.discount_value) AS discount_value,
        MAX(si.gst_percent) AS gst_percent,
        MAX(si.description) AS description,
        COALESCE((SELECT pi2.mrp FROM purchase_items pi2 WHERE pi2.product_id = si.product_id AND pi2.mrp > 0 LIMIT 1), 0) AS mrp
    FROM sales_items si
    JOIN products p ON p.id = si.product_id
    WHERE si.sales_invoice_id = $id
    GROUP BY si.product_id, p.name
    ORDER BY MIN(si.id)
");
?>

<div class="page-header">
    <h2><i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>
        Edit Invoice <span style="color:var(--text-secondary);font-weight:500;"><?= htmlspecialchars($inv['invoice_no']) ?></span>
    </h2>
    <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>

<?php if (($_GET['error'] ?? '') === 'has_returns'): ?>
<div class="alert alert-danger" style="margin-bottom:16px;">
    <i class="fas fa-exclamation-circle"></i>
    <strong>Cannot save changes.</strong> This invoice has sales returns linked to it.
    Please cancel or reverse the sales return before editing the invoice items.
</div>
<?php endif; ?>
<?php if (($_GET['reverted'] ?? '') === '1'): ?>
<div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#15803d;">
    <i class="fas fa-check-circle"></i>
    <strong>Reverted to Draft.</strong> Stock has been restored. You can now edit and re-finalize this invoice.
</div>
<?php endif; ?>

<form method="post" action="update.php" id="salesForm">
<input type="hidden" name="sales_invoice_id" value="<?= $id ?>">

<!-- Header Info -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title">Invoice Details</span></div>
    <div class="panel-body">
        <div class="form-row">
            <div class="form-group">
                <label>Client <span style="color:var(--danger)">*</span></label>
                <input type="text" id="clientInput" list="client_list"
                       value="<?= htmlspecialchars($clientName) ?>" required>
                <input type="hidden" name="client_id" id="clientId" value="<?= $inv['client_id'] ?>" required>
                <datalist id="client_list">
                    <?php while($c = $clients->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($c['name']) ?>" data-id="<?= $c['id'] ?>"></option>
                    <?php endwhile; ?>
                </datalist>
            </div>
            <div class="form-group">
                <label>Invoice No</label>
                <input type="text" value="<?= htmlspecialchars($inv['invoice_no']) ?>" disabled
                       style="background:#f8fafc;color:var(--text-muted);">
            </div>
            <div class="form-group">
                <label>Invoice Date</label>
                <input type="date" name="invoice_date"
                       value="<?= htmlspecialchars($inv['invoice_date'] ?? date('Y-m-d')) ?>" required>
            </div>
        </div>
    </div>
</div>

<!-- Line Items -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header">
        <span class="panel-title">Line 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="Filter rows..."
                       oninput="filterSalesItems(this.value)"
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:140px;">
            </div>
            <button type="button" id="addRow" 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 btn-ai-outline"
                    title="Extract data from invoice image or PDF">
                <i class="fas fa-magic"></i> AI Extract
            </button>
        </div>
    </div>
    <!-- Quick Add Bar -->
    <div 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="quickSearch" class="pac-input" placeholder="Search product to add to bill..."
                   autocomplete="off" style="padding-left:32px;width:100%;font-size:13px;">
        </div>
        <input type="number" id="quickQty" 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="quickAddBtn" class="btn btn-primary btn-sm">
            <i class="fas fa-plus"></i> Add to Bill
        </button>
        <span id="quickAddMsg" style="font-size:12px;color:var(--danger);display:none;font-weight:500;"></span>
    </div>
    <div class="items-scroll-wrap">
        <table class="list-table compact-sales-table" id="salesTable" style="width:100%;table-layout:fixed;">
            <colgroup>
                <col style="width:32px;">
                <col style="width:62px;">
                <col style="min-width:150px;width:19%;">
                <col style="width:66px;">
                <col style="width:54px;">
                <col style="width:54px;">
                <col style="width:84px;">
                <col style="width:84px;">
                <col style="width:108px;">
                <col style="width:42px;">
                <col style="width:76px;">
                <col style="width:36px;">
            </colgroup>
            <thead>
                <tr>
                    <th style="text-align:center;">#</th>
                    <th style="text-align:center;">Code</th>
                    <th>Product</th>
                    <th style="text-align:right;">MRP</th>
                    <th style="text-align:center;">Avail</th>
                    <th>Qty</th>
                    <th style="text-align:right;">Taxable Rate</th>
                    <th style="text-align:right;">Sell Price</th>
                    <th>Discount</th>
                    <th style="text-align:center;">GST%</th>
                    <th style="text-align:right;">Amount</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php $rowIdx = 0; while($row = $items->fetch_assoc()): $rowIdx++;
                $rowCode = $companyPrefix . '-' . $row['product_id'];
            ?>
            <tr class="salesRow">
                <td class="rowNum" style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $rowIdx ?></td>
                <td class="prodCode" style="text-align:center;">
                    <span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;cursor:pointer;"
                          onclick="showPurchaseDetails(<?= $row['product_id'] ?>, this.closest('tr'))"
                          title="Click to view purchase details"><?= htmlspecialchars($rowCode) ?></span>
                </td>
                <?php $hasDesc = trim($row['description'] ?? '') !== ''; ?>
                <td class="product-cell">
                    <div class="prod-name-wrap">
                        <input type="text" class="productInput pac-input" autocomplete="off"
                               value="<?= htmlspecialchars($row['product_name']) ?>" style="width:100%;min-width:0;">
                        <input type="hidden" name="product_id[]" value="<?= $row['product_id'] ?>">
                    </div>
                    <span class="desc-toggle-btn" onclick="toggleRowDesc(this)"
                          <?= $hasDesc ? 'style="color:var(--danger);"' : '' ?>><?= $hasDesc ? '− note' : '+ note' ?></span>
                    <div class="prod-desc-wrap<?= $hasDesc ? ' open' : '' ?>">
                        <textarea name="description[]" class="item-desc"
                                  placeholder="Note (opt)" rows="1" style="resize:none;font-size:11px;padding:2px 4px;"><?= htmlspecialchars($row['description'] ?? '') ?></textarea>
                    </div>
                </td>
                <td style="padding:3px 5px;"><input type="number" step="0.01" class="mrpInput" name="mrp[]"
                    value="<?= ($row['mrp'] ?? 0) > 0 ? number_format($row['mrp'], 2, '.', '') : '' ?>"
                    placeholder="MRP" style="width:100%;text-align:right;background:#fffdf0;border:1px dashed #d4a800;border-radius:3px;"></td>
                <td class="availQty" style="text-align:center;font-size:11px;color:var(--success);">—</td>
                <td><input type="number" step="0.01" class="qty" name="qty[]"
                           value="<?= number_format($row['total_qty'], 2, '.', '') ?>" style="width:100%;"></td>
                <td><input type="number" step="0.01" class="taxableRate"
                           value="<?= number_format($row['selling_price_excl'] ?? 0, 2, '.', '') ?>"
                           placeholder="0.00" style="width:100%;background:#f8faff;"></td>
                <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]"
                           value="<?= number_format($row['selling_price_incl'], 2, '.', '') ?>" style="width:100%;"></td>
                <td>
                    <div style="display:flex;gap:3px;">
                        <select class="discType" name="disc_type[]" style="width:52px;font-size:12px;">
                            <option value="">—</option>
                            <option value="percent" <?= $row['discount_type'] === 'percent' ? 'selected' : '' ?>>%</option>
                            <option value="amount"  <?= $row['discount_type'] === 'amount'  ? 'selected' : '' ?>>&#8377;</option>
                        </select>
                        <input type="number" step="0.01" class="discValue" name="disc_value[]"
                               value="<?= $row['discount_value'] ?>" placeholder="0" style="flex:1;min-width:0;">
                    </div>
                </td>
                <td class="gstPercent" style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $row['gst_percent'] ?></td>
                <td class="lineTotal" style="text-align:right;font-weight:700;font-size:13px;">0.00</td>
                <td>
                    <button type="button" class="removeRow action-btn delete" title="Remove">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Totals & Payment -->
<div style="display:grid;grid-template-columns:1fr auto;gap:16px;align-items:start;">

    <div class="panel">
        <div class="panel-header"><span class="panel-title">Payment Details</span></div>
        <div class="panel-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Overall Discount Type</label>
                    <select name="overall_discount_type" id="overallDiscType">
                        <option value="">None</option>
                        <option value="percent" <?= $inv['overall_discount_type'] == 'percent' ? 'selected' : '' ?>>Percent (%)</option>
                        <option value="amount"  <?= $inv['overall_discount_type'] == 'amount'  ? 'selected' : '' ?>>Amount (&#8377;)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Discount Value</label>
                    <input type="number" step="0.01" name="overall_discount_value"
                           id="overallDiscValue" value="<?= $inv['overall_discount_value'] ?>">
                </div>
                <div class="form-group">
                    <label>Received Amount</label>
                    <div style="padding:7px 10px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;font-weight:600;color:#15803d;">
                        &#8377; <?= number_format($inv['received_amount'], 2) ?>
                        <span style="font-size:11px;font-weight:400;color:var(--text-muted);margin-left:6px;">(managed via payment ledger)</span>
                    </div>
                </div>
                <div class="form-group">
                    <label>Balance</label>
                    <div style="padding:7px 10px;background:#<?= $inv['balance_amount'] > 0 ? 'fef2f2;border:1px solid #fca5a5;color:#dc2626' : 'f0fdf4;border:1px solid #bbf7d0;color:#15803d' ?>;border-radius:6px;font-weight:600;">
                        &#8377; <?= number_format($inv['balance_amount'], 2) ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="totals-box" style="min-width:280px;">
        <div class="totals-row">
            <span>Gross Total</span>
            <span>&#8377; <span id="grossTotal"><?= number_format($inv['gross_total'], 2) ?></span></span>
        </div>
        <div class="totals-row">
            <span>GST</span>
            <span>&#8377; <span id="gstTotal"><?= number_format($inv['total_gst'], 2) ?></span></span>
        </div>
        <div class="totals-row">
            <span>Sub Total</span>
            <span>&#8377; <span id="subTotal"><?= number_format($inv['net_total'] - ($inv['round_off'] ?? 0), 2) ?></span></span>
        </div>
        <div class="totals-row">
            <span>
                <label style="display:inline-flex;align-items:center;gap:5px;cursor:pointer;font-size:13px;">
                    <input type="checkbox" id="autoRoundChk" checked onchange="toggleRoundOff()">
                    Round Off
                </label>
            </span>
            <span id="roundOffDisplay" style="color:var(--text-muted);font-size:13px;">0.00</span>
            <input type="hidden" name="round_off" id="roundOff" value="<?= number_format($inv['round_off'] ?? 0, 2, '.', '') ?>">
        </div>
        <div class="totals-row grand-total">
            <span>Net Payable</span>
            <span>&#8377; <span id="netTotal"><?= number_format($inv['net_total'], 2) ?></span></span>
        </div>
    </div>

</div>

<div style="display:flex;gap:12px;margin-top:16px;align-items:center;flex-wrap:wrap;">
    <button type="submit" name="action" value="save" class="btn btn-secondary">
        <i class="fas fa-save"></i> Update Draft
    </button>
    <button type="submit" name="action" value="final" class="btn btn-success"
            onclick="return confirm('Finalize invoice and reduce stock?')">
        <i class="fas fa-check-circle"></i> Complete Sale
    </button>
    <a href="cancel.php?id=<?= $id ?>"
       onclick="return confirm('Cancel this quotation/draft? It will be marked as cancelled and cannot be edited again.')"
       class="btn btn-danger" style="margin-left:auto;">
        <i class="fas fa-ban"></i> Cancel Invoice
    </a>
</div>

</form>

<script src="../assets/js/product_ac.js"></script>
<script>
const PRODUCT_LIST = <?= json_encode($productList) ?>;
const COMPANY_PREFIX = '<?= addslashes($companyPrefix) ?>';
initProductAC(PRODUCT_LIST);
/* ---- Client autocomplete ---- */
document.getElementById('clientInput').addEventListener('input', function() {
    document.querySelectorAll('#client_list option').forEach(opt => {
        if (opt.value === this.value) document.getElementById('clientId').value = opt.dataset.id;
    });
});

function setRowCode(row, code, pid) {
    const cell = row.querySelector('.prodCode');
    if (!cell) return;
    if (code && pid) {
        cell.innerHTML = `<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;cursor:pointer;"
            onclick="showPurchaseDetails(${parseInt(pid)}, this.closest('tr'))" title="Click to view purchase details">${code}</span>`;
    } else if (code) {
        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>`;
    } else {
        cell.innerHTML = '—';
    }
}

/* ---- Quick Add helpers ---- */
let _quickProduct = null;
let _pdBatches = [];
let _pdCurrentRow = null;

function checkDuplicateProduct(productId, excludeRow) {
    const rows = document.querySelectorAll('#salesTable .salesRow');
    for (let i = 0; i < rows.length; i++) {
        if (rows[i] === excludeRow) continue;
        const hid = rows[i].querySelector('input[name="product_id[]"]');
        if (hid && hid.value && parseInt(hid.value) === parseInt(productId)) {
            const numCell = rows[i].querySelector('.rowNum');
            return numCell ? numCell.innerText : (i + 1);
        }
    }
    return null;
}

function showQuickMsg(msg) {
    const el = document.getElementById('quickAddMsg');
    el.textContent = msg;
    el.style.display = 'inline';
    clearTimeout(el._t);
    el._t = setTimeout(() => { el.style.display = 'none'; }, 3500);
}

function fillRowFromProduct(targetRow, productId, productName, productCode, qty) {
    targetRow.querySelector('.productInput').value = productName;
    targetRow.querySelector('input[name="product_id[]"]').value = productId;
    setRowCode(targetRow, productCode || '', productId);
    fetch('get_product_info.php?product_id=' + productId)
    .then(r => r.json())
    .then(data => {
        targetRow.querySelector('.availQty').innerText   = data.total_avail;
        targetRow.querySelector('.gstPercent').innerText = data.gst_percent;
        targetRow.querySelector('.mrpInput').value       = data.mrp > 0 ? data.mrp.toFixed(2) : '';
        if (data.last_price > 0) targetRow.querySelector('.sellPrice').value = data.last_price.toFixed(2);
        if (qty) targetRow.querySelector('.qty').value = qty;
        recalcRow(targetRow, 'sell');
    });
}

/* ---- Product selected via PAC widget ---- */
document.addEventListener('pac:select', function(e) {
    if (e.target.id === 'quickSearch') {
        _quickProduct = e.detail;
        return;
    }
    if (!e.target.classList.contains('productInput')) return;
    const row = e.target.closest('tr');
    if (!row) return;
    setRowCode(row, e.detail.code || '', e.detail.id);
    fetch('get_product_info.php?product_id=' + e.detail.id)
    .then(r => r.json())
    .then(data => {
        row.querySelector('.availQty').innerText   = data.total_avail;
        row.querySelector('.gstPercent').innerText = data.gst_percent;
        row.querySelector('.mrpInput').value       = data.mrp > 0 ? data.mrp.toFixed(2) : '';
        if (data.last_price > 0) {
            row.querySelector('.taxableRate').value = data.last_price.toFixed(2);
        }
        recalcRow(row, 'taxable');
    });
});

/* ---- Calculations (same logic as create.php) ---- */
function recalcRow(row, source) {
    source = source || 'sell';
    const qty      = parseFloat(row.querySelector('.qty').value || 0);
    const gstp     = parseFloat(row.querySelector('.gstPercent').innerText || 0);
    const discType = row.querySelector('.discType').value;
    const discVal  = parseFloat(row.querySelector('.discValue').value || 0);
    const spInput  = row.querySelector('.sellPrice');
    const trInput  = row.querySelector('.taxableRate');

    let taxableRate, finalIncl;

    if (source === 'taxable') {
        taxableRate = Math.max(0, parseFloat(trInput.value || 0));
        finalIncl   = taxableRate * (1 + gstp / 100);
        let sellPrice = finalIncl;
        if (discType === 'percent' && discVal > 0 && discVal < 100)
            sellPrice = finalIncl / (1 - discVal / 100);
        else if (discType === 'amount') sellPrice = finalIncl + discVal;
        spInput.value = sellPrice.toFixed(2);
    } else {
        const sellPrice = parseFloat(spInput.value || 0);
        finalIncl = sellPrice;
        if (discType === 'percent') finalIncl = sellPrice - (sellPrice * discVal / 100);
        else if (discType === 'amount') finalIncl = sellPrice - discVal;
        if (finalIncl < 0) finalIncl = 0;
        taxableRate = gstp > 0 ? finalIncl / (1 + gstp / 100) : finalIncl;
        trInput.value = taxableRate.toFixed(2);
    }

    row.querySelector('.lineTotal').innerText = (taxableRate * qty).toFixed(2);
    recalcInvoiceTotals();
}

let _netBeforeRound = 0;

function recalcInvoiceTotals() {
    let grossTaxable = 0, gstTotal = 0;
    document.querySelectorAll('#salesTable .salesRow').forEach(row => {
        const qty         = parseFloat(row.querySelector('.qty').value || 0);
        const taxableRate = parseFloat(row.querySelector('.taxableRate').value || 0);
        const sellPrice   = parseFloat(row.querySelector('.sellPrice').value || 0);
        const discType    = row.querySelector('.discType').value;
        const discVal     = parseFloat(row.querySelector('.discValue').value || 0);

        let finalIncl = sellPrice;
        if (discType === 'percent') finalIncl = sellPrice - (sellPrice * discVal / 100);
        else if (discType === 'amount') finalIncl = sellPrice - discVal;
        if (finalIncl < 0) finalIncl = 0;

        grossTaxable += taxableRate * qty;
        gstTotal     += (finalIncl - taxableRate) * qty;
    });

    const subTotal    = grossTaxable + gstTotal;
    const overallType = document.getElementById('overallDiscType').value;
    const overallVal  = parseFloat(document.getElementById('overallDiscValue').value || 0);
    _netBeforeRound = subTotal;
    if (overallType === 'percent') _netBeforeRound = subTotal - (subTotal * overallVal / 100);
    else if (overallType === 'amount') _netBeforeRound = subTotal - overallVal;
    if (_netBeforeRound < 0) _netBeforeRound = 0;

    const autoRound = document.getElementById('autoRoundChk').checked;
    const roundVal  = autoRound ? (Math.round(_netBeforeRound) - _netBeforeRound) : 0;
    document.getElementById('roundOff').value        = roundVal.toFixed(2);
    document.getElementById('roundOffDisplay').innerText = (roundVal >= 0 ? '+' : '') + roundVal.toFixed(2);

    document.getElementById('grossTotal').innerText = grossTaxable.toFixed(2);
    document.getElementById('gstTotal').innerText   = gstTotal.toFixed(2);
    document.getElementById('subTotal').innerText   = subTotal.toFixed(2);
    document.getElementById('netTotal').innerText   = (_netBeforeRound + roundVal).toFixed(2);
}

function toggleRoundOff() { recalcInvoiceTotals(); }

function toggleRowDesc(btn) {
    const cell = btn.closest('.product-cell');
    const wrap = cell.querySelector('.prod-desc-wrap');
    const open = wrap.classList.toggle('open');
    btn.textContent = open ? '− note' : '+ note';
    btn.style.color = open ? 'var(--danger)' : '';
    if (open) wrap.querySelector('textarea').focus();
}

document.addEventListener('input', function(e) {
    const row = e.target.closest('.salesRow');
    if (e.target.classList.contains('qty') || e.target.classList.contains('discValue')) {
        if (row) recalcRow(row, 'sell');
    } else if (e.target.classList.contains('sellPrice')) {
        if (row) recalcRow(row, 'sell');
    } else if (e.target.classList.contains('taxableRate')) {
        if (row) recalcRow(row, 'taxable');
    } else if (e.target.id === 'overallDiscValue') {
        recalcInvoiceTotals();
    }
});
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('discType') || e.target.id === 'overallDiscType') {
        const row = e.target.closest('.salesRow');
        if (row) recalcRow(row, 'sell'); else recalcInvoiceTotals();
    }
});

/* ---- Row numbering ---- */
function updateRowNums() {
    document.querySelectorAll('#salesTable tbody .salesRow').forEach((row, idx) => {
        const cell = row.querySelector('.rowNum');
        if (cell) cell.innerText = idx + 1;
    });
}

/* ---- Add / Remove rows ---- */
document.getElementById('addRow').onclick = function() {
    const tbody  = document.querySelector('#salesTable tbody');
    const newRow = tbody.querySelector('.salesRow').cloneNode(true);
    newRow.querySelectorAll('input').forEach(i => i.value = '');
    newRow.querySelectorAll('textarea').forEach(t => t.value = '');
    newRow.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
    setRowCode(newRow, '');
    newRow.querySelector('.mrpInput').value       = '';
    newRow.querySelector('.availQty').innerText   = '0';
    newRow.querySelector('.gstPercent').innerText = '0';
    newRow.querySelector('.lineTotal').innerText  = '0.00';
    newRow.querySelector('.taxableRate').value    = '';
    newRow.querySelector('.removeRow').disabled   = false;
    newRow.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
    const dw = newRow.querySelector('.prod-desc-wrap');
    if (dw) dw.classList.remove('open');
    const db = newRow.querySelector('.desc-toggle-btn');
    if (db) { db.textContent = '+ note'; db.style.color = ''; }
    tbody.appendChild(newRow);
    updateRowNums();
};

document.addEventListener('click', function(e) {
    const btn = e.target.closest('.removeRow');
    if (btn && !btn.disabled) {
        btn.closest('.salesRow').remove();
        updateRowNums();
        recalcInvoiceTotals();
    }
});

function filterSalesItems(q) {
    const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
    document.querySelectorAll('#salesTable tbody .salesRow').forEach(tr => {
        const name = (tr.querySelector('.productInput')?.value || '').toLowerCase();
        tr.style.display = (!words.length || words.every(w => name.includes(w))) ? '' : 'none';
    });
}

/* ---- Quick Add to Bill ---- */
document.getElementById('quickAddBtn').addEventListener('click', function() {
    if (!_quickProduct || !_quickProduct.id) {
        showQuickMsg('Please search and select a product first.');
        return;
    }
    const pid = _quickProduct.id;
    const dup = checkDuplicateProduct(pid, null);
    if (dup !== null) {
        showQuickMsg('Product already added in row ' + dup + '.');
        return;
    }
    const qty = parseFloat(document.getElementById('quickQty').value) || 1;

    const rows = document.querySelectorAll('#salesTable .salesRow');
    let targetRow = null;
    if (rows.length > 0) {
        const last = rows[rows.length - 1];
        if (!last.querySelector('input[name="product_id[]"]').value) targetRow = last;
    }
    if (!targetRow) {
        document.getElementById('addRow').click();
        const updated = document.querySelectorAll('#salesTable .salesRow');
        targetRow = updated[updated.length - 1];
    }

    fillRowFromProduct(targetRow, pid, _quickProduct.name, _quickProduct.code, qty);

    _quickProduct = null;
    document.getElementById('quickSearch').value = '';
    document.getElementById('quickQty').value = '1';
    document.getElementById('quickSearch').focus();
});

/* ---- Purchase Details Popup ---- */
function showPurchaseDetails(pid, rowEl) {
    _pdCurrentRow = rowEl || null;
    const modal = document.getElementById('purchaseDetailsModal');
    modal.style.display = 'flex';
    document.getElementById('pdProductName').textContent = '—';
    document.getElementById('pdContent').innerHTML = '<div style="padding:24px;text-align:center;color:var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
    fetch('../includes/get_purchase_details.php?product_id=' + encodeURIComponent(pid))
    .then(r => r.json())
    .then(data => {
        if (data.error) { document.getElementById('pdContent').innerHTML = '<div style="color:var(--danger);padding:12px;">' + data.error + '</div>'; return; }
        document.getElementById('pdProductName').textContent = data.product_name;
        _pdBatches = data.batches || [];
        let html = '';
        if (data.last_selling_price > 0 || data.default_sell_price > 0) {
            html += `<div style="display:flex;gap:16px;margin-bottom:12px;background:#f0fdf4;padding:10px 14px;border-radius:6px;border:1px solid #bbf7d0;flex-wrap:wrap;">`;
            if (data.last_selling_price > 0) html += `<span style="font-size:13px;"><strong>Last Selling Price:</strong> <span style="color:var(--success);font-weight:700;">&#8377;${parseFloat(data.last_selling_price).toFixed(2)}</span></span>`;
            if (data.default_sell_price > 0) html += `<span style="font-size:13px;color:var(--text-muted);">Default Sell Price: &#8377;${parseFloat(data.default_sell_price).toFixed(2)}</span>`;
            html += `</div>`;
        }
        if (!_pdBatches.length) {
            html += '<div style="color:var(--text-muted);font-size:13px;padding:12px;">No purchase records found.</div>';
        } else {
            html += `<table style="width:100%;border-collapse:collapse;font-size:12px;">
                <thead><tr style="background:#f8fafc;text-transform:uppercase;font-size:10px;letter-spacing:.5px;color:var(--text-muted);">
                    <th style="padding:8px 10px;text-align:left;border-bottom:2px solid #e2e8f0;">Date</th>
                    <th style="padding:8px 10px;text-align:left;border-bottom:2px solid #e2e8f0;">Company</th>
                    <th style="padding:8px 10px;text-align:left;border-bottom:2px solid #e2e8f0;">Batch</th>
                    <th style="padding:8px 10px;text-align:right;border-bottom:2px solid #e2e8f0;">Purch Qty</th>
                    <th style="padding:8px 10px;text-align:right;border-bottom:2px solid #e2e8f0;">Avail Qty</th>
                    <th style="padding:8px 10px;text-align:right;border-bottom:2px solid #e2e8f0;">Purchase(Inc Tax)</th>
                    <th style="padding:8px 10px;text-align:right;border-bottom:2px solid #e2e8f0;">Sell(Inc Tax)</th>
                    <th style="padding:8px 10px;text-align:right;border-bottom:2px solid #e2e8f0;">MRP</th>
                    <th style="padding:8px 4px;border-bottom:2px solid #e2e8f0;"></th>
                </tr></thead><tbody>`;
            _pdBatches.forEach((b, idx) => {
                const parts = b.purchase_date.split('-');
                const fmtDate = parts[2] + '-' + parts[1] + '-' + parts[0].slice(-2);
                html += `<tr style="border-bottom:1px solid #f1f5f9;">
                    <td style="padding:7px 10px;">${fmtDate}</td>
                    <td style="padding:7px 10px;font-weight:600;">${b.company_prefix}</td>
                    <td style="padding:7px 10px;">${b.batch_no || '—'}</td>
                    <td style="padding:7px 10px;text-align:right;">${b.quantity}</td>
                    <td style="padding:7px 10px;text-align:right;color:var(--success);font-weight:600;">${b.available_qty}</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377;${parseFloat(b.purchase_price_incl).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:right;color:var(--primary);font-weight:600;">&#8377;${parseFloat(b.selling_price_incl).toFixed(2)}</td>
                    <td style="padding:7px 10px;text-align:right;">&#8377;${parseFloat(b.mrp).toFixed(2)}</td>
                    <td style="padding:7px 4px;text-align:center;"><button type="button" onclick="selectBatchFromPopup(${idx})" style="padding:3px 9px;font-size:11px;background:var(--primary);color:#fff;border:none;border-radius:4px;cursor:pointer;">Select</button></td>
                </tr>`;
            });
            html += '</tbody></table>';
        }
        document.getElementById('pdContent').innerHTML = html;
    })
    .catch(() => { document.getElementById('pdContent').innerHTML = '<div style="color:var(--danger);padding:12px;">Failed to load purchase details.</div>'; });
}
function closePurchaseDetails() {
    document.getElementById('purchaseDetailsModal').style.display = 'none';
    _pdCurrentRow = null;
}
function selectBatchFromPopup(idx) {
    const b = _pdBatches[idx];
    if (!b || !_pdCurrentRow) { closePurchaseDetails(); return; }
    _pdCurrentRow.querySelector('.sellPrice').value = parseFloat(b.selling_price_incl).toFixed(2);
    recalcRow(_pdCurrentRow, 'sell');
    closePurchaseDetails();
}

/* ---- 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', 'sales');

    fetch('get_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;

        if (d.items && d.items.length) {
            const tbody = document.querySelector('#salesTable tbody');
            while (tbody.querySelectorAll('.salesRow').length > d.items.length) {
                const rows = tbody.querySelectorAll('.salesRow');
                if (rows.length <= 1) break;
                rows[rows.length - 1].remove();
            }
            while (tbody.querySelectorAll('.salesRow').length < d.items.length) {
                const firstRow = tbody.querySelector('.salesRow').cloneNode(true);
                firstRow.querySelectorAll('input').forEach(i => i.value = '');
                firstRow.querySelectorAll('textarea').forEach(t => t.value = '');
                firstRow.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
                firstRow.querySelector('.availQty').innerText   = '0';
                firstRow.querySelector('.gstPercent').innerText = '0';
                firstRow.querySelector('.lineTotal').innerText  = '0.00';
                firstRow.querySelector('.removeRow').disabled   = false;
                firstRow.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
                tbody.appendChild(firstRow);
            }
            tbody.querySelectorAll('.salesRow').forEach((row, idx) => {
                const item = d.items[idx];
                if (!item) return;
                const nameInput = row.querySelector('.productInput');
                const hiddenId  = row.querySelector('input[name="product_id[]"]');
                if (nameInput) {
                    nameInput.value = item.product_name || '';
                    const exactMatch = PRODUCT_LIST.find(p =>
                        p.name.toLowerCase() === (item.product_name || '').toLowerCase()
                    );
                    if (exactMatch && hiddenId) {
                        hiddenId.value = exactMatch.id;
                        fetch('get_product_info.php?product_id=' + exactMatch.id)
                        .then(r => r.json())
                        .then(data => {
                            row.querySelector('.availQty').innerText   = data.total_avail;
                            row.querySelector('.gstPercent').innerText = data.gst_percent;
                            if (data.last_price > 0 && !item.sell_price) {
                                row.querySelector('.sellPrice').value = data.last_price.toFixed(2);
                            }
                            recalcRow(row);
                        });
                    } else if (item.product_name) {
                        if (hiddenId) hiddenId.value = '';
                        pacShowResolvePanel(nameInput, item.product_name, null);
                    }
                }
                if (item.quantity)   row.querySelector('.qty').value        = item.quantity;
                if (item.sell_price) row.querySelector('.sellPrice').value  = item.sell_price;
                if (item.gst_percent != null) row.querySelector('.gstPercent').innerText = item.gst_percent;
                recalcRow(row);
            });
            updateRowNums();
            recalcInvoiceTotals();
        }

        statusEl.textContent = 'Extracted! Review and adjust the values.';
        statusEl.style.color = 'var(--success)';
    })
    .catch(() => { statusEl.textContent = 'Request failed. Check API key and internet.'; statusEl.style.color = 'var(--danger)'; });
}

/* ---- Init on load: fetch avail qty, then recalc from saved taxable rate ---- */
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('#salesTable tbody .salesRow').forEach(row => {
        const productId = row.querySelector('input[name="product_id[]"]')?.value;
        if (!productId) return;
        fetch('get_product_info.php?product_id=' + productId)
        .then(r => r.json())
        .then(data => {
            row.querySelector('.availQty').innerText = data.total_avail;
            if (!row.querySelector('.gstPercent').innerText || row.querySelector('.gstPercent').innerText == '0') {
                row.querySelector('.gstPercent').innerText = data.gst_percent;
            }
            // taxableRate is pre-loaded from DB; derive sell price from it
            recalcRow(row, 'taxable');
        });
    });
});
</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 customer's order/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>
.btn-ai-outline{color:var(--primary);border-color:var(--primary);background:#fff;}
.btn-ai-outline:hover{background:var(--primary);color:#fff;}
.compact-sales-table td,
.compact-sales-table th { padding:5px 6px; }
.compact-sales-table input[type="number"],
.compact-sales-table input[type="text"] { padding:4px 6px;font-size:12px; }
.compact-sales-table select { padding:3px 4px;font-size:12px; }
.compact-sales-table .item-desc { width:100%;font-size:11px; }
.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); }
.compact-sales-table .qty,
.compact-sales-table .taxableRate,
.compact-sales-table .sellPrice,
.compact-sales-table .discValue { text-align:right; }
/* Description toggle */
.prod-desc-wrap { display:none; }
.prod-desc-wrap.open { display:block; }
.desc-toggle-btn { display:inline-block;font-size:10px;color:var(--text-muted);cursor:pointer;margin-top:2px;user-select:none;transition:color .15s; }
.desc-toggle-btn:hover { color:var(--primary); }
</style>

<!-- Purchase Details Modal -->
<div id="purchaseDetailsModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:3500;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;padding:0;width:1050px;max-width:98vw;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 8px 40px rgba(0,0,0,.25);">
        <div style="padding:14px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-box-open" style="color:var(--primary);margin-right:8px;"></i>Purchase Details: <span id="pdProductName" style="color:var(--primary);">—</span></h3>
            <button onclick="closePurchaseDetails()" style="background:none;border:none;font-size:20px;cursor:pointer;color:var(--text-muted);line-height:1;">&times;</button>
        </div>
        <div style="padding:14px 16px;overflow-y:auto;flex:1;" id="pdContent">Loading...</div>
    </div>
</div>

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