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

$clients  = $conn->query("SELECT id, name, customer_type 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'] ?? '';

$clientList  = [];
while ($c = $clients->fetch_assoc()) $clientList[] = $c;

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

$invoice_no = 'QTY/' . date('YmdHis');

// Copy from cancelled invoice
$copyData = null;
$copy_from = (int)($_GET['copy_from'] ?? 0);
if ($copy_from > 0) {
    $origInv = $conn->query("
        SELECT si.client_id, c.name AS client_name
        FROM sales_invoices si
        JOIN clients c ON c.id = si.client_id
        WHERE si.id = $copy_from AND si.company_id = $cid AND si.status = 'cancelled'
    ")->fetch_assoc();
    if ($origInv) {
        $copyItems = [];
        $itemsRes = $conn->query("
            SELECT si.product_id, p.name AS product_name,
                   si.sold_qty AS qty, si.selling_price_incl,
                   si.discount_type, si.discount_value,
                   si.gst_percent, si.description,
                   COALESCE(pi.mrp, 0) AS mrp
            FROM sales_items si
            JOIN products p ON p.id = si.product_id
            LEFT JOIN purchase_items pi ON pi.id = si.purchase_item_id
            WHERE si.sales_invoice_id = $copy_from
        ");
        while ($r = $itemsRes->fetch_assoc()) $copyItems[] = $r;
        $copyData = ['client_id' => $origInv['client_id'], 'client_name' => $origInv['client_name'], 'items' => $copyItems];
    }
}
?>

<div class="page-header">
    <h2><i class="fas fa-plus-circle" style="color:var(--primary);margin-right:8px;"></i><?= $copyData ? 'Copy Invoice' : 'Create Sales Invoice' ?></h2>
    <div style="display:flex;gap:8px;">
        <a href="create_ai.php" class="btn btn-outline btn-sm btn-ai-outline">
            <i class="fas fa-magic"></i> New Invoice via AI
        </a>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

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

<!-- Header Info -->
<div class="panel" style="margin-bottom:12px;position:relative;z-index:20;">
    <div class="panel-header"><span class="panel-title">Invoice Details</span></div>
    <div class="panel-body" style="padding-bottom:12px;">
        <div class="form-row" style="align-items:flex-end;">

            <!-- Client search -->
            <div class="form-group" style="flex:2;min-width:220px;">
                <label>Client <span style="color:var(--danger)">*</span></label>
                <input type="hidden" name="client_id" id="clientId">
                <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;display:flex;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>

            <div class="form-group">
                <label>Invoice No</label>
                <input type="text" value="<?= htmlspecialchars($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="<?= 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>
            <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"
                    style="color:var(--primary);border-color:var(--primary);"
                    title="Extract data from invoice image or PDF">
                <i class="fas fa-magic"></i> AI Extract
            </button>
        </div>
    </div>
    <!-- Quick Add Bar -->
    <div style="padding:10px 14px;background:#f0f7ff;border-bottom:1px solid #bfdbfe;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
        <div style="position:relative;flex:1;min-width:200px;">
            <i class="fas fa-search" style="position:absolute;left:9px;top:50%;transform:translateY(-50%);color:#93c5fd;font-size:12px;pointer-events:none;z-index:1;"></i>
            <input type="text" id="quickSearch" class="pac-input" placeholder="Search product to add to bill..."
                   autocomplete="off" style="padding-left:32px;width:100%;font-size:13px;">
        </div>
        <input type="number" id="quickQty" min="0.01" step="0.01" value="1" placeholder="Qty"
               style="width:72px;padding:6px 8px;font-size:13px;border:1px solid var(--border);border-radius:6px;">
        <button type="button" id="quickAddBtn" class="btn btn-primary btn-sm">
            <i class="fas fa-plus"></i> Add to Bill
        </button>
        <span id="quickAddMsg" style="font-size:12px;color:var(--danger);display:none;font-weight:500;"></span>
    </div>
    <div class="items-scroll-wrap">
        <table class="list-table compact-sales-table" id="salesTable" style="width:100%;table-layout:fixed;">
            <colgroup>
                <col style="width:32px;">
                <col style="width:62px;">
                <col style="min-width:150px;width:19%;">
                <col style="width:66px;">
                <col style="width:54px;">
                <col style="width:54px;">
                <col style="width:84px;">
                <col style="width:84px;">
                <col style="width:108px;">
                <col style="width:42px;">
                <col style="width:76px;">
                <col style="width:36px;">
            </colgroup>
            <thead>
                <tr>
                    <th style="text-align:center;">#</th>
                    <th style="text-align:center;">Code</th>
                    <th>Product</th>
                    <th style="text-align:right;">MRP</th>
                    <th style="text-align:center;">Avail</th>
                    <th>Qty</th>
                    <th style="text-align:right;">Taxable Rate</th>
                    <th style="text-align:right;">Sell Price</th>
                    <th>Discount</th>
                    <th style="text-align:center;">GST%</th>
                    <th style="text-align:right;">Amount</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <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="Code or name..." 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;">

    <!-- Payment -->
    <div class="panel">
        <div class="panel-header"><span class="panel-title">Payment Details</span></div>
        <div class="panel-body" style="display:flex;flex-direction:column;gap:10px;">
            <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;">
                <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>

    <!-- Totals -->
    <div class="totals-box" style="min-width:280px;">
        <div class="totals-row">
            <span>Gross Total</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">
            <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>
/* ---- Client autocomplete ---- */
const CLIENTS = <?= json_encode($clientList) ?>;

// Portal dropdown — appended to body so it's never clipped by overflow:hidden parents
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';
    const gstin = document.getElementById('nc_gstin').value.trim();
    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(gstin)}`
            + `&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. Try again.'; 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)';
    }
});

const PRODUCT_LIST = <?= json_encode($productList) ?>;
const COMPANY_PREFIX = '<?= addslashes($companyPrefix) ?>';
initProductAC(PRODUCT_LIST);

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

/* ---- Duplicate check & quick-add helpers ---- */
let _quickProduct = null;
let _pdBatches = [];
let _pdCurrentRow = null;

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

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

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

/* ---- Product selected via PAC widget ---- */
document.addEventListener('pac:select', function(e) {
    if (e.target.id === 'quickSearch') {
        _quickProduct = e.detail;
        return;
    }
    if (!e.target.classList.contains('productInput')) return;
    const row = e.target.closest('tr');
    if (!row) return;
    const productId = e.detail.id;
    const dup = checkDuplicateProduct(productId, row);
    if (dup !== null) {
        e.target.value = '';
        row.querySelector('input[name="product_id[]"]').value = '';
        showQuickMsg('Already added in row ' + dup + '.');
        return;
    }
    setRowCode(row, e.detail.code || '', productId);
    fetch('get_product_info.php?product_id=' + productId)
    .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('.sellPrice').value = data.last_price.toFixed(2);
        recalcRow(row, 'sell');
    });
});

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

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

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

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

/* ---- 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') {
        // User typed taxable rate → derive sell price
        taxableRate = Math.max(0, parseFloat(trInput.value || 0));
        finalIncl   = taxableRate * (1 + gstp / 100);
        // Reverse the discount to get pre-discount inclusive sell price
        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 {
        // 'sell', 'qty', or discount changed → derive taxable from sell price
        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);
    }

    // Line Total = taxable rate × qty
    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;

        const gstPerUnit = finalIncl - taxableRate;
        grossTaxable += taxableRate * qty;
        gstTotal     += gstPerUnit  * 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);
    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) {
    if (e.target.closest('.removeRow')) {
        const btn = e.target.closest('.removeRow');
        if (!btn.disabled) {
            btn.closest('.salesRow').remove();
            updateRowNums();
            recalcInvoiceTotals();
        }
    }
});


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

<?php if ($copyData): ?>
/* ---- Pre-fill from copied invoice ---- */
(function() {
    const data = <?= json_encode($copyData) ?>;
    if (!data || !data.items || !data.items.length) return;
    selectClient(data.client_id, data.client_name);
    const tbody = document.querySelector('#salesTable tbody');
    while (tbody.querySelectorAll('.salesRow').length < data.items.length) {
        document.getElementById('addRow').click();
    }
    const allRows = [...tbody.querySelectorAll('.salesRow')];
    for (let i = data.items.length; i < allRows.length; i++) allRows[i].remove();
    const rows = [...tbody.querySelectorAll('.salesRow')];
    data.items.forEach((item, idx) => {
        const row = rows[idx];
        if (!row) return;
        row.querySelector('.productInput').value = item.product_name;
        row.querySelector('input[name="product_id[]"]').value = item.product_id;
        setRowCode(row, COMPANY_PREFIX + '-' + item.product_id, item.product_id);
        if (parseFloat(item.mrp) > 0) row.querySelector('.mrpInput').value = parseFloat(item.mrp).toFixed(2);
        row.querySelector('.gstPercent').innerText = item.gst_percent || 0;
        row.querySelector('.qty').value = item.qty;
        row.querySelector('.sellPrice').value = parseFloat(item.selling_price_incl).toFixed(2);
        if (item.discount_type) row.querySelector('.discType').value = item.discount_type;
        if (parseFloat(item.discount_value) > 0) row.querySelector('.discValue').value = item.discount_value;
        const ta = row.querySelector('textarea[name="description[]"]');
        if (ta && item.description) ta.value = item.description;
        recalcRow(row, 'sell');
    });
    updateRowNums();
    recalcInvoiceTotals();
})();
<?php endif; ?>

/* ---- 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);
                setRowCode(firstRow, '');
                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;
                tbody.appendChild(firstRow);
            }
            tbody.querySelectorAll('.salesRow').forEach((row, idx) => {
                const item = d.items[idx];
                if (!item) return;
                const nameInput = row.querySelector('.productInput');
                if (nameInput) {
                    nameInput.value = item.product_name || '';
                    // Trigger product lookup
                    nameInput.dispatchEvent(new Event('input', {bubbles: true}));
                }
                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, 'sell');
            });
            updateRowNums();
            recalcInvoiceTotals();
        }

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

<!-- AI Extract Modal -->
<div id="aiModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:10px;padding:24px;width:420px;max-width:95vw;box-shadow:0 8px 40px rgba(0,0,0,.2);">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 style="margin:0;font-size:15px;"><i class="fas fa-magic" style="color:var(--primary);margin-right:8px;"></i>AI Extract from Invoice</h3>
            <button onclick="closeAIModal()" style="background:none;border:none;font-size:18px;cursor:pointer;color:var(--text-muted);">&times;</button>
        </div>
        <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px;">
            Upload a photo or PDF of the 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;}
.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>

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

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