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

$clients  = $conn->query("SELECT id, name, customer_type FROM clients WHERE status = 1 AND company_id = $cid ORDER BY name");
$clientList = [];
while ($c = $clients->fetch_assoc()) $clientList[] = $c;

$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 Invoice 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">
        <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>Select 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>
    </div>
</div>

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

<!-- Invoice Header -->
<div class="panel" style="margin-bottom:16px;position:relative;z-index:20;">
    <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" style="padding-bottom:12px;">
        <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;">

            <!-- Client -->
            <div class="form-group" style="margin-bottom:0;">
                <label>Client <span style="color:var(--danger)">*</span></label>
                <input type="hidden" name="client_id" id="clientId" required>
                <div style="position:relative;">
                    <input type="text" id="clientSearch" placeholder="Type to search client..."
                           autocomplete="off"
                           oninput="filterClients(this.value)"
                           onfocus="filterClients(this.value)"
                           style="width:100%;">
                </div>
                <div id="clientChosen" style="display:none;margin-top:5px;padding:5px 10px;background:var(--bg-light);border-radius:5px;font-size:13px;align-items:center;gap:8px;">
                    <i class="fas fa-user" style="color:var(--primary);"></i>
                    <span id="clientChosenName"></span>
                    <button type="button" onclick="clearClient()" 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>Invoice Date <span style="color:var(--danger)">*</span></label>
                <input type="date" name="invoice_date" id="invoice_date" value="<?= date('Y-m-d') ?>" required>
            </div>

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

<!-- Line Items -->
<div class="panel" style="margin-bottom:12px;">
    <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>
        </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:64px;">
                <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>
                <tr class="salesRow">
                    <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 class="product-cell">
                        <div class="prod-name-wrap">
                            <input type="text" class="productInput pac-input" autocomplete="off" placeholder="Search product..." style="width:100%;min-width:0;">
                            <input type="hidden" name="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;"></textarea>
                        </div>
                    </td>
                    <td style="padding:3px 5px;"><input type="number" step="0.01" class="mrpInput" name="mrp[]" 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);">0</td>
                    <td><input type="number" step="0.01" class="qty" name="qty[]" min="0" placeholder="0" style="width:100%;"></td>
                    <td><input type="number" step="0.01" class="taxableRate" placeholder="0.00" style="width:100%;background:#f8faff;"></td>
                    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]" placeholder="0.00" 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">%</option>
                                <option value="amount">&#8377;</option>
                            </select>
                            <input type="number" step="0.01" class="discValue" name="disc_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;">0</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" disabled title="Remove">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            </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 style="background:#fffbeb;border:1px solid #fcd34d;border-radius:7px;padding:10px 14px;">
                <div style="font-size:11px;font-weight:600;color:#92400e;margin-bottom:8px;text-transform:uppercase;letter-spacing:.4px;"><i class="fas fa-tag" style="margin-right:5px;"></i>Discount</div>
                <div class="form-row" style="margin:0;gap:10px;">
                    <div class="form-group" style="margin:0;flex:1;">
                        <label>Type</label>
                        <select name="overall_discount_type" id="overallDiscType">
                            <option value="">None</option>
                            <option value="percent">Percent (%)</option>
                            <option value="amount">Amount (&#8377;)</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;flex:1;">
                        <label>Value</label>
                        <input type="number" step="0.01" name="overall_discount_value" id="overallDiscValue" placeholder="0.00">
                    </div>
                </div>
            </div>
            <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:7px;padding:10px 14px;margin-top:10px;">
                <div style="font-size:11px;font-weight:600;color:#166534;margin-bottom:8px;text-transform:uppercase;letter-spacing:.4px;"><i class="fas fa-rupee-sign" style="margin-right:5px;"></i>Payment Received</div>
                <div class="form-row" style="margin:0;gap:10px;">
                    <div class="form-group" style="margin:0;flex:1;">
                        <label>Received Amount</label>
                        <input type="number" step="0.01" name="received_amount" id="receivedAmount" placeholder="0.00">
                    </div>
                    <div class="form-group" style="margin:0;flex:1;">
                        <label>Payment Mode</label>
                        <select name="payment_mode" id="paymentMode">
                            <option value="Cash">Cash</option>
                            <option value="UPI">UPI</option>
                            <option value="Card">Card</option>
                            <option value="Bank">Bank Transfer</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="totals-box" style="min-width:280px;">
        <div class="totals-row"><span>Taxable Amount</span><span>&#8377; <span id="grossTotal">0.00</span></span></div>
        <div class="totals-row"><span>GST</span><span>&#8377; <span id="gstTotal">0.00</span></span></div>
        <div class="totals-row" style="border-top:1px solid var(--border);padding-top:6px;"><span>Sub Total</span><span>&#8377; <span id="subTotal">0.00</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="0.00">
        </div>
        <div class="totals-row grand-total">
            <span>Net Payable</span>
            <span>&#8377; <span id="netTotal">0.00</span></span>
        </div>
    </div>

</div>

<!-- Action Buttons -->
<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> Save 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>

<!-- Add Client Modal -->
<div id="clientModal" 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:460px;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-user-plus" style="color:var(--primary);margin-right:8px;"></i>Add New Client</h3>
            <button type="button" onclick="closeClientModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
            <div class="form-group" style="grid-column:1/-1;">
                <label>Client Name <span style="color:var(--danger)">*</span></label>
                <input type="text" id="nc_name" placeholder="Client or company name" style="width:100%;">
            </div>
            <div class="form-group"><label>Phone</label><input type="text" id="nc_phone" placeholder="Phone number"></div>
            <div class="form-group"><label>Email</label><input type="email" id="nc_email" placeholder="Email address"></div>
            <div class="form-group">
                <label>Customer Type</label>
                <select id="nc_type" onchange="toggleModalGST()">
                    <option value="B2C">B2C (Individual)</option>
                    <option value="B2B">B2B (Business)</option>
                </select>
            </div>
            <div class="form-group" id="nc_gstin_wrap" style="display:none;">
                <label>GSTIN</label>
                <input type="text" id="nc_gstin" placeholder="15-digit GSTIN" maxlength="15" style="text-transform:uppercase;" oninput="this.value=this.value.toUpperCase();">
            </div>
        </div>
        <div class="form-group">
            <label>Address</label>
            <textarea id="nc_address" rows="2" placeholder="Full address" style="width:100%;"></textarea>
        </div>
        <div id="nc_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="closeClientModal()">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="saveNewClient()"><i class="fas fa-save"></i> Save & Select</button>
        </div>
    </div>
</div>

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

/* ---- Fuzzy product finder ---- */
function findBestProduct(name) {
    if (!name) return null;
    const q = name.trim().toLowerCase();
    let m = PRODUCTS.find(p => p.name.toLowerCase() === q);
    if (m) return m;
    m = PRODUCTS.find(p => p.code && p.code.toLowerCase() === q);
    if (m) return m;
    m = PRODUCTS.find(p => p.name.toLowerCase().includes(q) || q.includes(p.name.toLowerCase()));
    if (m) return m;
    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;
        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>'
        : '—';
}

/* ---- Client autocomplete (portal dropdown, never clipped by overflow) ---- */
const _cddEl = document.createElement('div');
_cddEl.id = 'clientDropdown';
_cddEl.style.cssText = 'display:none;position:fixed;background:#fff;border:1px solid var(--border);border-radius:0 0 6px 6px;max-height:200px;overflow-y:auto;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,.12);';
document.body.appendChild(_cddEl);

function positionClientDropdown() {
    const inp = document.getElementById('clientSearch');
    const rect = inp.getBoundingClientRect();
    _cddEl.style.left  = rect.left + 'px';
    _cddEl.style.top   = rect.bottom + 'px';
    _cddEl.style.width = rect.width + 'px';
}

function filterClients(q) {
    const dd = _cddEl;
    const search = q.trim().toLowerCase();
    const filtered = search ? CLIENTS.filter(c => c.name.toLowerCase().includes(search)) : CLIENTS;
    let html = '';
    filtered.slice(0, 30).forEach(c => {
        const badge = c.customer_type === 'B2B'
            ? '<span style="font-size:10px;background:#e0f2fe;color:#0369a1;padding:1px 5px;border-radius:3px;margin-left:6px;">B2B</span>'
            : '';
        html += `<div class="cdd-item" onmousedown="selectClient(${c.id}, '${c.name.replace(/'/g,"\\'")}')">
            <i class="fas fa-user" style="color:var(--primary);margin-right:7px;font-size:12px;"></i>${c.name}${badge}</div>`;
    });
    html += `<div class="cdd-item cdd-add" onmousedown="openClientModal('${q.replace(/'/g,"\\'")}')">
        <i class="fas fa-plus-circle" style="color:var(--success);margin-right:7px;"></i>Add New Client${q.trim() ? ' "'+q.trim()+'"' : ''}</div>`;
    dd.innerHTML = html;
    positionClientDropdown();
    dd.style.display = 'block';
}
document.getElementById('clientSearch').addEventListener('blur', function() {
    setTimeout(() => _cddEl.style.display = 'none', 150);
});
function selectClient(id, name) {
    document.getElementById('clientId').value = id;
    document.getElementById('clientSearch').style.display = 'none';
    _cddEl.style.display = 'none';
    const chosen = document.getElementById('clientChosen');
    chosen.style.display = 'flex';
    document.getElementById('clientChosenName').textContent = name;
}
function clearClient() {
    document.getElementById('clientId').value = '';
    document.getElementById('clientSearch').style.display = '';
    document.getElementById('clientSearch').value = '';
    document.getElementById('clientChosen').style.display = 'none';
    document.getElementById('clientSearch').focus();
}
function openClientModal(prefill) {
    document.getElementById('nc_name').value    = prefill || '';
    document.getElementById('nc_phone').value   = '';
    document.getElementById('nc_email').value   = '';
    document.getElementById('nc_type').value    = 'B2C';
    document.getElementById('nc_gstin').value   = '';
    document.getElementById('nc_address').value = '';
    document.getElementById('nc_error').style.display = 'none';
    toggleModalGST();
    document.getElementById('clientModal').style.display = 'flex';
    document.getElementById('nc_name').focus();
}
function closeClientModal() { document.getElementById('clientModal').style.display = 'none'; }
function toggleModalGST() {
    document.getElementById('nc_gstin_wrap').style.display =
        document.getElementById('nc_type').value === 'B2B' ? 'block' : 'none';
}
function saveNewClient() {
    const name  = document.getElementById('nc_name').value.trim();
    const errEl = document.getElementById('nc_error');
    if (!name) { errEl.textContent = 'Client name is required.'; errEl.style.display='block'; return; }
    errEl.style.display = 'none';
    fetch('ajax_add_client.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: `name=${encodeURIComponent(name)}`
            + `&phone=${encodeURIComponent(document.getElementById('nc_phone').value.trim())}`
            + `&email=${encodeURIComponent(document.getElementById('nc_email').value.trim())}`
            + `&customer_type=${encodeURIComponent(document.getElementById('nc_type').value)}`
            + `&gstin=${encodeURIComponent(document.getElementById('nc_gstin').value.trim())}`
            + `&address=${encodeURIComponent(document.getElementById('nc_address').value.trim())}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            CLIENTS.push({id: data.id, name: data.name, customer_type: document.getElementById('nc_type').value});
            CLIENTS.sort((a,b) => a.name.localeCompare(b.name));
            closeClientModal();
            selectClient(data.id, data.name);
        } else { errEl.textContent = data.msg || 'Error saving client.'; errEl.style.display='block'; }
    })
    .catch(() => { errEl.textContent = 'Server error.'; errEl.style.display='block'; });
}

/* ---- Form validation ---- */
document.getElementById('salesForm').addEventListener('submit', function(e) {
    if (!document.getElementById('clientId').value) {
        e.preventDefault();
        document.getElementById('clientSearch').focus();
        document.getElementById('clientSearch').style.borderColor = 'var(--danger)';
    }
});

/* ---- 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) : '';
        const sp = row.querySelector('.sellPrice');
        if (data.last_price > 0 && !sp.value) {
            sp.value = data.last_price.toFixed(2);
        }
        recalcRow(row, 'sell');
    });
});

/* ---- Calculations ---- */
// Sell price is GST-inclusive; taxable rate is GST-exclusive.
// Editing either one updates the other. Discount anchors to sell price.
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() {
    const show = document.getElementById('descToggle').checked;
    document.getElementById('salesTable').classList.toggle('show-desc', show);
}

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);
    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;
    setRowCode(newRow, '');
    newRow.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
    tbody.appendChild(newRow);
    updateRowNums();
};

document.addEventListener('click', function(e) {
    if (e.target.closest('.removeRow')) {
        const btn = e.target.closest('.removeRow');
        if (!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 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', 'sales');

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

        // Client matching
        if (d.client_name) {
            const cname = d.client_name.trim().toLowerCase();
            const match = CLIENTS.find(c =>
                c.name.toLowerCase().includes(cname) || cname.includes(c.name.toLowerCase())
            );
            if (match) {
                selectClient(match.id, match.name);
                msgs.push('✓ Client matched: ' + match.name);
            } else {
                clearClient();
                document.getElementById('clientSearch').value = d.client_name;
                filterClients(d.client_name);
                msgs.push('⚠ Client "' + d.client_name + '" not found — select or add below.');
            }
        }

        // Invoice date
        if (d.invoice_date) {
            const dateInput = document.getElementById('invoice_date');
            if (dateInput) dateInput.value = d.invoice_date;
            msgs.push('✓ Date: ' + d.invoice_date);
        }

        // Items
        if (d.items && d.items.length) {
            const tbody = document.querySelector('#salesTable tbody');
            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('.mrpInput').value        = '';
                firstRow.querySelector('.availQty').innerText    = '0';
                firstRow.querySelector('.gstPercent').innerText  = '0';
                firstRow.querySelector('.lineTotal').innerText   = '0.00';
                firstRow.querySelector('.taxableRate').value     = '';
                firstRow.querySelector('.removeRow').disabled    = false;
                firstRow.querySelectorAll('._pac_unmatched, ._pac_resolve').forEach(el => el.remove());
                tbody.appendChild(firstRow);
            }
            while (tbody.querySelectorAll('.salesRow').length > d.items.length) {
                const rows = tbody.querySelectorAll('.salesRow');
                if (rows.length <= 1) break;
                rows[rows.length - 1].remove();
            }

            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 matched = findBestProduct(item.product_name);
                    if (matched && hiddenId) {
                        hiddenId.value = matched.id;
                        nameInput.value = matched.name;
                        setRowCode(row, matched.code || '');
                        fetch('get_product_info.php?product_id=' + matched.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 && !item.sell_price) {
                                row.querySelector('.taxableRate').value = data.last_price.toFixed(2);
                            }
                            recalcRow(row, 'taxable');
                        });
                    } else if (item.product_name) {
                        if (hiddenId) hiddenId.value = '';
                        setRowCode(row, '');
                        pacShowResolvePanel(nameInput, item.product_name, null);
                    }
                }
                if (item.quantity)   row.querySelector('.qty').value = item.quantity;
                if (item.gst_percent != null) row.querySelector('.gstPercent').innerText = item.gst_percent;
                // AI rate goes into Taxable Rate; sell price is derived from it
                if (item.sell_price) {
                    row.querySelector('.taxableRate').value = parseFloat(item.sell_price).toFixed(2);
                    recalcRow(row, 'taxable');
                } else {
                    recalcRow(row, 'sell');
                }
            });
            updateRowNums();
            recalcInvoiceTotals();
            msgs.push('✓ ' + d.items.length + ' item(s) extracted — verify product names and adjust if needed.');
        }

        statusEl.style.color = 'var(--success)';
        statusEl.textContent = msgs.join('\n');
    })
    .catch(() => {
        statusEl.style.color = 'var(--danger)';
        statusEl.textContent = 'Request failed. Check API key and internet connection.';
    });
}
</script>

<style>
.cdd-item { padding:8px 12px;cursor:pointer;font-size:13px;border-bottom:1px solid #f0f0f0; }
.cdd-item:hover { background:var(--bg-light); }
.cdd-add { color:var(--success);font-weight:500;border-top:2px solid #f0f0f0;border-bottom:none; }
.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 — hidden by default, shown when #salesTable has .show-desc */
.prod-desc-wrap { display:none; }
#salesTable.show-desc .prod-desc-wrap { display:block; }
</style>

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