<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$vendors = $conn->query("SELECT id, name FROM vendors WHERE status = 1 AND company_id = $cid ORDER BY name");
$vendorList = [];
while ($v = $vendors->fetch_assoc()) $vendorList[] = $v;

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

<div class="page-header">
    <h2><i class="fas fa-magic" style="color:var(--primary);margin-right:8px;"></i>New Purchase via AI</h2>
    <div style="display:flex;gap:8px;">
        <a href="create.php" class="btn btn-secondary btn-sm"><i class="fas fa-keyboard"></i> Manual Entry</a>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>


<!-- Step 1: Upload Invoice -->
<div class="panel" id="aiUploadPanel" style="margin-bottom:16px;border-left:4px solid var(--primary);">
    <div class="panel-header"><span class="panel-title"><i class="fas fa-magic" style="margin-right:6px;color:var(--primary);"></i>Step 1 — Extract from Invoice Image</span></div>
    <div class="panel-body">
        <!-- Page 1 extract -->
        <div style="display:flex;gap:16px;align-items:flex-end;flex-wrap:wrap;">
            <div class="form-group" style="margin-bottom:0;flex:1;min-width:200px;">
                <label>Page 1 — Invoice Image (JPG / PNG / WEBP)</label>
                <input type="file" id="aiFileInput" accept="image/*" style="width:100%;">
            </div>
            <button type="button" onclick="runAIExtract()" class="btn btn-primary" style="white-space:nowrap;">
                <i class="fas fa-magic"></i> Extract Data
            </button>
        </div>
        <div id="aiStatus" style="font-size:13px;margin-top:10px;min-height:18px;white-space:pre-line;"></div>

        <!-- Add more pages (shown after first extraction) -->
        <div id="aiMorePages" style="display:none;margin-top:12px;border-top:1px dashed var(--border);padding-top:12px;">
            <div style="font-size:12px;font-weight:600;color:var(--text-muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:0.5px;">
                <i class="fas fa-file-image" style="margin-right:5px;"></i>Add More Pages
            </div>
            <div id="aiExtraPages"></div>
            <button type="button" onclick="addPageSlot()" class="btn btn-outline btn-sm" style="margin-top:8px;">
                <i class="fas fa-plus"></i> Add Another Page
            </button>
        </div>
    </div>
</div>

<form method="post" action="save.php" id="purchaseForm">

<!-- Purchase Header -->
<div class="panel" style="margin-bottom:16px;">
    <div class="panel-header"><span class="panel-title"><i class="fas fa-info-circle" style="margin-right:6px;color:var(--primary);"></i>Step 2 — Review & Confirm Details</span></div>
    <div class="panel-body">
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">

            <!-- Vendor -->
            <div class="form-group" style="margin-bottom:0;">
                <label>Vendor <span style="color:var(--danger)">*</span></label>
                <input type="hidden" name="vendor_id" id="vendor_id" required>
                <div style="position:relative;">
                    <input type="text" id="vendorSearch" placeholder="Type to search vendor..."
                           autocomplete="off"
                           oninput="filterVendors(this.value)"
                           onfocus="filterVendors(this.value)"
                           style="width:100%;">
                    <div id="vendorDropdown" style="display:none;position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid var(--border);border-radius:0 0 6px 6px;max-height:220px;overflow-y:auto;z-index:999;box-shadow:0 4px 12px rgba(0,0,0,.12);"></div>
                </div>
                <div id="vendorChosen" style="display:none;margin-top:6px;padding:6px 10px;background:var(--bg-light);border-radius:5px;font-size:13px;align-items:center;gap:8px;">
                    <i class="fas fa-truck" style="color:var(--primary);"></i>
                    <span id="vendorChosenName"></span>
                    <button type="button" onclick="clearVendor()" style="margin-left:auto;background:none;border:none;cursor:pointer;color:var(--danger);font-size:13px;"><i class="fas fa-times"></i></button>
                </div>
            </div>

            <!-- Date -->
            <div class="form-group" style="margin-bottom:0;">
                <label>Purchase Date <span style="color:var(--danger)">*</span></label>
                <input type="date" name="purchase_date" id="purchase_date" value="<?= date('Y-m-d') ?>" required>
            </div>

            <!-- Supplier Invoice No -->
            <div class="form-group" style="margin-bottom:0;">
                <label>Supplier Invoice No</label>
                <input type="text" name="supplier_invoice_no" id="supplier_invoice_no" placeholder="e.g. SUP-001">
            </div>

        </div>
    </div>
</div>

<!-- 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>
            <button type="button" id="addRowBtn" class="btn btn-outline btn-sm">
                <i class="fas fa-plus"></i> Add Row
            </button>
        </div>
    </div>
    <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:26%;">
                <col style="width:80px;">
                <col style="width:120px;">
                <col style="width:70px;">
                <col style="width:90px;">
                <col style="width:155px;">
                <col style="width:90px;">
                <col style="width:40px;">
            </colgroup>
            <thead>
                <tr>
                    <th style="text-align:center;">#</th>
                    <th style="text-align:center;">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>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <tr>
                <td class="rowNum" style="text-align:center;color:var(--text-muted);font-size:12px;">1</td>
                <td class="prodCode" style="text-align:center;font-family:monospace;font-size:11px;color:var(--text-muted);">—</td>
                <td style="white-space:normal;vertical-align:top;">
                    <input type="text" name="product_name[]" class="productInput pac-input" autocomplete="off" placeholder="Code or name..." style="display:block;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>
                    <div class="prod-desc-wrap"><textarea name="description[]" rows="1" placeholder="Description (optional)"
                              style="display:block;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[]" type="number" step="0.01" placeholder="0.00"></td>
                <td><input name="purchase_price[]" type="number" step="0.01" placeholder="0.00" oninput="recalcTotals()"></td>
                <td><input name="quantity[]" type="number" step="0.01" placeholder="0" oninput="recalcTotals()"></td>
                <td><input name="gst_percent[]" type="number" step="0.01" placeholder="0" style="width:100%;" oninput="recalcTotals()"></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;" onchange="recalcTotals()">
                            <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" oninput="recalcTotals()">
                    </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>
            </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>
        <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="">None</option>
                    <option value="percent">%</option>
                    <option value="amount">₹ Amount</option>
                </select>
                <input type="number" step="0.01" min="0" name="overall_discount_value" id="overallDiscValue"
                       value="0.00" oninput="recalcTotals()"
                       style="width:90px;text-align:right;padding:2px 6px;font-size:13px;">
            </span>
        </div>
        <div class="totals-row">
            <span>Round Off</span>
            <span style="display:flex;align-items:center;gap:4px;justify-content:flex-end;">
                <input type="number" step="0.01" name="round_off" id="roundOff" value="0.00"
                       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;">Auto</button>
            </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 -->
<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>

</form>

<!-- Add New Vendor Modal -->
<div id="vendorModal" 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:28px 28px 20px;width:420px;max-width:95vw;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;">
            <h3 style="margin:0;font-size:16px;"><i class="fas fa-truck" style="color:var(--primary);margin-right:8px;"></i>Add New Vendor</h3>
            <button type="button" onclick="closeVendorModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div class="form-group">
            <label>Vendor / Company Name <span style="color:var(--danger)">*</span></label>
            <input type="text" id="mv_name" placeholder="Vendor name" style="width:100%;">
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
            <div class="form-group"><label>Phone</label><input type="text" id="mv_phone" placeholder="Phone"></div>
            <div class="form-group"><label>Mobile</label><input type="text" id="mv_mobile" placeholder="Mobile"></div>
        </div>
        <div class="form-group">
            <label>GSTIN</label>
            <input type="text" id="mv_gstin" placeholder="15-digit GSTIN" maxlength="15" style="text-transform:uppercase;" oninput="this.value=this.value.toUpperCase();">
        </div>
        <div id="mv_error" style="color:var(--danger);font-size:13px;margin-bottom:8px;display:none;"></div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:8px;">
            <button type="button" class="btn btn-secondary" onclick="closeVendorModal()">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="saveNewVendor()"><i class="fas fa-save"></i> Save & Select</button>
        </div>
    </div>
</div>

<!-- 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="closeProductModal()">&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="closeProductModal()">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 VENDORS = <?= json_encode($vendorList) ?>;
const PRODUCTS = <?= json_encode($products) ?>;
const COMPANY_PREFIX = '<?= addslashes($companyPrefix) ?>';
const table   = document.getElementById('purchaseTable');
let activeProductInput = null;

initProductAC(PRODUCTS);
_pacOnAddNew = function(prefill) {
    activeProductInput = _pacActiveInput;
    document.getElementById('productModal').style.display = 'flex';
    if (prefill) document.getElementById('new_name').value = prefill;
};

/* ---- Vendor ---- */
function filterVendors(q) {
    const dd = document.getElementById('vendorDropdown');
    const search = q.trim().toLowerCase();
    const filtered = search ? VENDORS.filter(v => v.name.toLowerCase().includes(search)) : VENDORS;
    let html = '';
    filtered.slice(0, 30).forEach(v => {
        html += `<div class="vdd-item" onmousedown="selectVendor(${v.id},'${v.name.replace(/'/g,"\\'")}')">
            <i class="fas fa-truck" style="color:var(--primary);margin-right:7px;font-size:12px;"></i>${v.name}</div>`;
    });
    html += `<div class="vdd-item vdd-add" onmousedown="openVendorModal('${q.replace(/'/g,"\\'")}')">
        <i class="fas fa-plus-circle" style="color:var(--success);margin-right:7px;"></i>Add New Vendor${q.trim() ? ' "'+q.trim()+'"' : ''}</div>`;
    dd.innerHTML = html; dd.style.display = 'block';
}
document.getElementById('vendorSearch').addEventListener('blur', () => {
    setTimeout(() => document.getElementById('vendorDropdown').style.display = 'none', 150);
});
function selectVendor(id, name) {
    document.getElementById('vendor_id').value = id;
    document.getElementById('vendorSearch').style.display = 'none';
    document.getElementById('vendorDropdown').style.display = 'none';
    const chosen = document.getElementById('vendorChosen');
    chosen.style.display = 'flex';
    document.getElementById('vendorChosenName').textContent = name;
}
function clearVendor() {
    document.getElementById('vendor_id').value = '';
    document.getElementById('vendorSearch').style.display = '';
    document.getElementById('vendorSearch').value = '';
    document.getElementById('vendorChosen').style.display = 'none';
    document.getElementById('vendorSearch').focus();
}
function openVendorModal(prefill) {
    document.getElementById('mv_name').value = prefill || '';
    ['mv_phone','mv_mobile','mv_gstin'].forEach(id => document.getElementById(id).value = '');
    document.getElementById('mv_error').style.display = 'none';
    document.getElementById('vendorModal').style.display = 'flex';
    document.getElementById('mv_name').focus();
}
function closeVendorModal() { document.getElementById('vendorModal').style.display = 'none'; }
function saveNewVendor() {
    const name = document.getElementById('mv_name').value.trim();
    const errEl = document.getElementById('mv_error');
    if (!name) { errEl.textContent = 'Vendor name is required.'; errEl.style.display='block'; return; }
    errEl.style.display = 'none';
    const fd = new FormData();
    fd.append('name', name); fd.append('phone', document.getElementById('mv_phone').value.trim());
    fd.append('mobile', document.getElementById('mv_mobile').value.trim());
    fd.append('gstin', document.getElementById('mv_gstin').value.trim());
    fetch('ajax_add_vendor.php', { method:'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            VENDORS.push({id: data.id, name: data.name});
            VENDORS.sort((a,b) => a.name.localeCompare(b.name));
            closeVendorModal(); selectVendor(data.id, data.name);
        } else { errEl.textContent = data.message || 'Error'; errEl.style.display='block'; }
    })
    .catch(() => { errEl.textContent = 'Server error.'; errEl.style.display='block'; });
}

/* ---- Fuzzy product finder ---- */
function findBestProduct(name) {
    if (!name) return null;
    const q = name.trim().toLowerCase();
    // 1. Exact name
    let m = PRODUCTS.find(p => p.name.toLowerCase() === q);
    if (m) return m;
    // 2. Code match (e.g. AJ-101)
    m = PRODUCTS.find(p => p.code && p.code.toLowerCase() === q);
    if (m) return m;
    // 3. Contains
    m = PRODUCTS.find(p => p.name.toLowerCase().includes(q) || q.includes(p.name.toLowerCase()));
    if (m) return m;
    // 4. All significant words present
    const words = q.split(/\s+/).filter(w => w.length > 2);
    if (words.length) {
        m = PRODUCTS.find(p => words.every(w => p.name.toLowerCase().includes(w)));
        if (m) return m;
        // 5. Best partial: most words matched
        let best = null, bestScore = 0;
        PRODUCTS.forEach(p => {
            const score = words.filter(w => p.name.toLowerCase().includes(w)).length;
            if (score > bestScore && score >= Math.ceil(words.length / 2)) { best = p; bestScore = score; }
        });
        if (best) return best;
    }
    return null;
}

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>'
        : '—';
}

/* ---- PAC selection fills product_id + code ---- */
document.addEventListener('pac:select', function(e) {
    if (!e.target.classList.contains('productInput')) return;
    const row = e.target.closest('tr');
    if (!row) return;
    const hid = row.querySelector('input[name="product_id[]"]');
    if (hid) hid.value = e.detail.id;
    setRowCode(row, e.detail.code || '');
    const ab = row.querySelector('.addProductBtn');
    if (ab) ab.style.display = 'none';
});

/* ---- Product (handled by product_ac.js PAC widget) ---- */
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('addProductBtn')) {
        const td = e.target.closest('td');
        activeProductInput = td.querySelector('.productInput');
        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;
            PRODUCTS.push({ id: res.id, name: res.name, code: newCode });
            PRODUCTS.sort((a,b) => a.name.localeCompare(b.name));
            initProductAC(PRODUCTS);
            const inp = activeProductInput || _pacActiveInput;
            if (inp) {
                const row = inp.closest('tr');
                const td = inp.closest('td');
                inp.value = res.name;
                if (td) td.querySelector('input[name="product_id[]"]').value = res.id;
                const ab = td ? td.querySelector('.addProductBtn') : null;
                if (ab) ab.style.display = 'none';
                if (row) setRowCode(row, COMPANY_PREFIX + '-' + res.id);
            }
            closeProductModal();
        } else { alert(res.msg); }
    });
};
function closeProductModal() { document.getElementById('productModal').style.display = 'none'; }

/* ---- Rows ---- */
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;
    });
}
document.getElementById('addRowBtn').addEventListener('click', function() {
    const tbody = table.querySelector('tbody');
    const nr = tbody.rows[0].cloneNode(true);
    nr.querySelectorAll('input').forEach(i => i.value = '');
    nr.querySelectorAll('textarea').forEach(t => t.value = '');
    nr.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
    nr.querySelector('.removeRow').disabled = false;
    nr.querySelector('.rowTotal').innerText = '0.00';
    setRowCode(nr, '');
    const ab = nr.querySelector('.addProductBtn'); if (ab) ab.style.display = 'none';
    nr.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
    tbody.appendChild(nr); generateBatch(); updateRowNums(); recalcTotals();
});
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 ---- */
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();

/* ---- Totals ---- */
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 rt = eff * qty;
        taxable += rt; gst += rt * gstp / 100;
        const span = row.querySelector('.rowTotal'); if (span) span.innerText = rt.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() {
    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);
    document.getElementById('roundOff').value = (Math.round(discounted) - 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();
});

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

/* ---- Validation ---- */
document.getElementById('purchaseForm').addEventListener('submit', function(e) {
    if (!document.getElementById('vendor_id').value) {
        e.preventDefault();
        document.getElementById('vendorSearch').style.borderColor = 'var(--danger)';
        alert('Please select a vendor.'); return;
    }
    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.'); }
});

/* ---- AI Extract ---- */
function runAIExtract() {
    const fileInput = document.getElementById('aiFileInput');
    if (!fileInput.files.length) { alert('Please select an invoice image.'); return; }
    const statusEl = document.getElementById('aiStatus');
    statusEl.style.color = 'var(--text-muted)';
    statusEl.textContent = 'Extracting data from invoice… please wait.';

    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.style.color = 'var(--danger)';
            statusEl.textContent = 'Error: ' + res.error;
            return;
        }
        const d = res.data;
        const msgs = [];

        // Vendor matching
        if (d.vendor_name) {
            const vname = d.vendor_name.trim().toLowerCase();
            const match = VENDORS.find(v =>
                v.name.toLowerCase().includes(vname) || vname.includes(v.name.toLowerCase())
            );
            if (match) {
                selectVendor(match.id, match.name);
                msgs.push('✓ Vendor matched: ' + match.name);
            } else {
                clearVendor();
                document.getElementById('vendorSearch').value = d.vendor_name;
                filterVendors(d.vendor_name);
                msgs.push('⚠ Vendor "' + d.vendor_name + '" not found — select or add below.');
            }
        }

        // Supplier invoice no
        if (d.invoice_date) {
            document.getElementById('purchase_date').value = d.invoice_date;
            msgs.push('✓ Date: ' + d.invoice_date);
        }
        if (d.supplier_invoice_no) {
            document.getElementById('supplier_invoice_no').value = d.supplier_invoice_no;
            msgs.push('✓ Invoice No: ' + d.supplier_invoice_no);
        }

        // Items
        if (d.items && d.items.length) {
            const tbody = table.querySelector('tbody');
            while (tbody.rows.length < d.items.length) {
                const nr = tbody.rows[0].cloneNode(true);
                nr.querySelectorAll('input').forEach(i => i.value = '');
                nr.querySelectorAll('textarea').forEach(t => t.value = '');
                nr.querySelector('.removeRow').disabled = false;
                nr.querySelector('.rowTotal').innerText = '0.00';
                const ab = nr.querySelector('.addProductBtn'); if (ab) ab.style.display = 'none';
                tbody.appendChild(nr);
            }
            while (tbody.rows.length > d.items.length) tbody.deleteRow(tbody.rows.length - 1);

            tbody.querySelectorAll('tr').forEach((row, idx) => {
                const item = d.items[idx]; if (!item) return;
                const set = (name, val) => { const el = row.querySelector(`input[name="${name}"]`); if (el && val != null) el.value = val; };
                const nameInput = row.querySelector('input[name="product_name[]"]');
                const hiddenId  = row.querySelector('input[name="product_id[]"]');
                if (nameInput) {
                    nameInput.value = item.product_name || '';
                    const matched = findBestProduct(item.product_name);
                    if (matched && hiddenId) {
                        hiddenId.value = matched.id;
                        nameInput.value = matched.name;
                        setRowCode(row, matched.code || '');
                    } else if (item.product_name) {
                        if (hiddenId) hiddenId.value = '';
                        setRowCode(row, '');
                        pacShowResolvePanel(nameInput, item.product_name, function(prefill) {
                            activeProductInput = nameInput;
                            document.getElementById('productModal').style.display = 'flex';
                            document.getElementById('new_name').value = prefill || '';
                        });
                    }
                }
                set('batch_no[]',       item.batch_no || '');
                set('mrp[]',            item.mrp);
                set('purchase_price[]', item.purchase_price);
                set('quantity[]',       item.quantity);
                set('gst_percent[]',    item.gst_percent);
            });
            generateBatch(); updateRowNums(); recalcTotals();
            msgs.push('✓ ' + d.items.length + ' item(s) extracted — verify product names and match if needed.');
        }

        statusEl.style.color = 'var(--success)';
        statusEl.textContent = msgs.join('\n');
        document.getElementById('aiMorePages').style.display = 'block';
        if (!document.getElementById('aiExtraPages').children.length) addPageSlot();
    })
    .catch(() => {
        statusEl.style.color = 'var(--danger)';
        statusEl.textContent = 'Request failed. Check API key and internet connection.';
    });
}

/* ---- Add extra page slot ---- */
let pageSlotCount = 1;
function addPageSlot() {
    pageSlotCount++;
    const num = pageSlotCount;
    const container = document.getElementById('aiExtraPages');
    const div = document.createElement('div');
    div.id = 'pageSlot' + num;
    div.style.cssText = 'display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;margin-bottom:10px;padding:10px;background:var(--bg-light);border-radius:6px;border:1px solid var(--border);';
    div.innerHTML = `
        <div class="form-group" style="margin-bottom:0;flex:1;min-width:180px;">
            <label style="font-size:12px;">Page ${num} Image</label>
            <input type="file" id="aiPage${num}File" accept="image/*" style="width:100%;">
        </div>
        <button type="button" onclick="runAIAppend(${num})" class="btn btn-outline btn-sm" style="white-space:nowrap;color:var(--primary);border-color:var(--primary);">
            <i class="fas fa-magic"></i> Extract &amp; Append
        </button>
        <div id="aiPage${num}Status" style="font-size:12px;min-height:16px;width:100%;white-space:pre-line;"></div>
    `;
    container.appendChild(div);
}

/* ---- Append items from extra page ---- */
function runAIAppend(num) {
    const fileInput = document.getElementById('aiPage' + num + 'File');
    const statusEl  = document.getElementById('aiPage' + num + 'Status');
    if (!fileInput.files.length) { statusEl.style.color='var(--danger)'; statusEl.textContent='Please select a page image.'; return; }
    statusEl.style.color = 'var(--text-muted)';
    statusEl.textContent = 'Extracting… please wait.';

    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.style.color='var(--danger)'; statusEl.textContent='Error: ' + res.error; return; }
        const d = res.data;
        if (!d.items || !d.items.length) { statusEl.style.color='var(--text-muted)'; statusEl.textContent='No items found on this page.'; return; }

        const tbody = table.querySelector('tbody');
        // Check if table has only the blank default row
        const existingRows = Array.from(tbody.rows);
        const hasRealData = existingRows.some(row => {
            const nm = row.querySelector('input[name="product_name[]"]');
            return nm && nm.value.trim() !== '';
        });
        if (!hasRealData) {
            // Remove blank rows before appending
            while (tbody.rows.length > 0) tbody.deleteRow(0);
        }

        d.items.forEach(item => {
            const template = document.createElement('tr');
            const firstRow = document.querySelector('#purchaseTable tbody tr');
            const nr = firstRow ? firstRow.cloneNode(true) : tbody.rows[0].cloneNode(true);
            nr.querySelectorAll('input').forEach(i => i.value = '');
            nr.querySelectorAll('textarea').forEach(t => t.value = '');
            nr.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
            if (nr.querySelector('.removeRow')) nr.querySelector('.removeRow').disabled = false;
            if (nr.querySelector('.rowTotal')) nr.querySelector('.rowTotal').innerText = '0.00';
            const ab = nr.querySelector('.addProductBtn'); if (ab) ab.style.display = 'none';
            nr.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());

            const nameInput = nr.querySelector('input[name="product_name[]"]');
            const hiddenId  = nr.querySelector('input[name="product_id[]"]');
            if (nameInput) {
                nameInput.value = item.product_name || '';
                const matched = findBestProduct(item.product_name);
                if (matched && hiddenId) {
                    hiddenId.value = matched.id;
                    nameInput.value = matched.name;
                    setRowCode(nr, matched.code || '');
                } else if (item.product_name) {
                    if (hiddenId) hiddenId.value = '';
                    setRowCode(nr, '');
                    pacShowResolvePanel(nameInput, item.product_name, function(prefill) {
                        activeProductInput = nameInput;
                        document.getElementById('productModal').style.display = 'flex';
                        document.getElementById('new_name').value = prefill || '';
                    });
                }
            }
            const set = (name, val) => { const el = nr.querySelector(`input[name="${name}"]`); if (el && val != null) el.value = val; };
            set('batch_no[]',       item.batch_no || '');
            set('mrp[]',            item.mrp);
            set('purchase_price[]', item.purchase_price);
            set('quantity[]',       item.quantity);
            set('gst_percent[]',    item.gst_percent);
            tbody.appendChild(nr);
        });

        generateBatch(); updateRowNums(); recalcTotals();
        statusEl.style.color = 'var(--success)';
        statusEl.textContent = '✓ ' + d.items.length + ' item(s) appended from page ' + num + '.';
    })
    .catch(() => { statusEl.style.color='var(--danger)'; statusEl.textContent='Request failed.'; });
}
</script>

<style>
.vdd-item { padding:8px 12px;cursor:pointer;font-size:13px;border-bottom:1px solid #f0f0f0; }
.vdd-item:hover { background:var(--bg-light); }
.vdd-add { color:var(--success);font-weight:500;border-top:2px solid #f0f0f0;border-bottom:none; }
.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); }
/* Description toggle */
.prod-desc-wrap { display:none; }
#purchaseTable.show-desc .prod-desc-wrap { display:block; }
</style>

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