<?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; ?>

<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;">
            <label style="display:inline-flex;align-items:center;gap:4px;font-size:12px;cursor:pointer;color:var(--text-muted);font-weight:500;">
                <input type="checkbox" id="descToggle" onchange="toggleDescriptions()">
                Desc
            </label>
            <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="filterSalesItems(this.value)"
                       style="padding:5px 8px 5px 28px;font-size:12px;border:1px solid var(--border);border-radius:6px;width:180px;">
            </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>
    <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;font-family:monospace;font-size:11px;color:var(--text-muted);">
                    <span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;"><?= htmlspecialchars($rowCode) ?></span>
                </td>
                <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>
                    <div class="prod-desc-wrap">
                        <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>
                    <input type="number" step="0.01" name="received_amount"
                           id="receivedAmount" value="<?= $inv['received_amount'] ?>">
                </div>
                <div class="form-group">
                    <label>Payment Mode</label>
                    <select name="payment_mode">
                        <option value="Cash" <?= $inv['payment_mode'] == 'Cash' ? 'selected' : '' ?>>Cash</option>
                        <option value="UPI"  <?= $inv['payment_mode'] == 'UPI'  ? 'selected' : '' ?>>UPI</option>
                        <option value="Card" <?= $inv['payment_mode'] == 'Card' ? 'selected' : '' ?>>Card</option>
                        <option value="Bank" <?= $inv['payment_mode'] == 'Bank' ? 'selected' : '' ?>>Bank Transfer</option>
                    </select>
                </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;">
    <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>
</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) {
    const cell = row.querySelector('.prodCode');
    if (!cell) return;
    cell.innerHTML = code
        ? '<span style="font-family:monospace;font-size:11px;font-weight:600;background:#eff6ff;color:#2563eb;padding:2px 5px;border-radius:3px;">' + code + '</span>'
        : '—';
}

/* ---- Product input: fetch info on PAC selection ---- */
document.addEventListener('pac:select', function(e) {
    if (!e.target.classList.contains('productInput')) return;
    const row = e.target.closest('tr');
    if (!row) return;
    setRowCode(row, e.detail.code || '');
    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 toggleDescriptions() {
    document.getElementById('salesTable').classList.toggle('show-desc',
        document.getElementById('descToggle').checked);
}

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());
    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';
    });
}

/* ---- 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; }
.prod-desc-wrap { display:none; }
#salesTable.show-desc .prod-desc-wrap { display:block; }
</style>

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