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

requirePermission('master_sales', 'edit', BASE_URL . '/dashboard.php');

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

$master = $conn->query("
    SELECT mi.*, c.name AS client_name
    FROM master_invoices mi
    JOIN clients c ON c.id = mi.client_id
    WHERE mi.id = $id
")->fetch_assoc();
if (!$master) die('Master invoice not found.');
if ($master['status'] !== 'draft') die('Only draft master invoices can be edited.');

// Load all line items from linked sales_invoices
$editItemsRes = $conn->query("
    SELECT
        si.id            AS sales_item_id,
        si.purchase_item_id,
        si.product_id,
        si.description,
        si.batch_no,
        si.sold_qty,
        si.selling_price_incl,
        si.discount_type,
        si.discount_value,
        si.gst_percent,
        p.name           AS product_name,
        p.unit,
        pi.available_qty,
        pi.mrp,
        po.company_id,
        cm.company_name,
        cm.invoice_prefix
    FROM sales_items si
    JOIN sales_invoices inv ON inv.id = si.sales_invoice_id
    JOIN products p         ON p.id  = si.product_id
    JOIN purchase_items pi  ON pi.id = si.purchase_item_id
    JOIN purchase_orders po ON po.id = pi.purchase_order_id
    JOIN company_master cm  ON cm.id = po.company_id
    WHERE inv.master_invoice_id = $id
    ORDER BY inv.id ASC, si.id ASC
");

$editItems = [];
while ($row = $editItemsRes->fetch_assoc()) {
    // Reconstruct original sell price (before item discount)
    $disc_type = $row['discount_type'];
    $disc_val  = floatval($row['discount_value']);
    $final     = floatval($row['selling_price_incl']);
    if ($disc_type === 'percent' && $disc_val > 0) {
        $orig_price = round($final / (1 - $disc_val / 100), 2);
    } elseif ($disc_type === 'amount') {
        $orig_price = round($final + $disc_val, 2);
    } else {
        $orig_price = $final;
    }
    $row['orig_sell_price'] = $orig_price;
    $row['company_prefix']  = $row['invoice_prefix'] ?: strtoupper(substr($row['company_name'], 0, 3));
    $editItems[] = $row;
}

// All clients across all companies
$clientRes  = $conn->query("SELECT id, name, customer_type FROM clients WHERE status = 1 ORDER BY name");
$clientList = [];
while ($c = $clientRes->fetch_assoc()) $clientList[] = $c;

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

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

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

<!-- Header -->
<div class="panel" style="margin-bottom:12px;">
    <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;">

            <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" value="<?= $master['client_id'] ?>">
                <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%;display:none;">
                    <div id="clientDropdown" 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:200px;overflow-y:auto;z-index:999;box-shadow:0 4px 12px rgba(0,0,0,.12);"></div>
                </div>
                <div id="clientChosen" style="display:flex;margin-top:2px;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"><?= htmlspecialchars($master['client_name']) ?></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>Master Ref</label>
                <input type="text" value="<?= htmlspecialchars($master['master_no']) ?>" disabled style="background:#f8fafc;color:var(--text-muted);">
            </div>
            <div class="form-group">
                <label>Invoice Date</label>
                <input type="date" name="invoice_date" value="<?= htmlspecialchars($master['invoice_date']) ?>" 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 style="font-size:11px;font-weight:400;color:var(--text-muted);margin-left:8px;">(search products across all companies)</span></span>
        <button type="button" id="addRow" class="btn btn-outline btn-sm"><i class="fas fa-plus"></i> Add Row</button>
    </div>
    <div style="overflow-x:auto;">
        <table class="list-table compact-sales-table" id="salesTable" style="width:100%;table-layout:fixed;">
            <colgroup>
                <col style="width:30px;">
                <col style="min-width:200px;width:24%;">
                <col style="width:130px;">
                <col style="width:80px;">
                <col style="width:65px;">
                <col style="width:105px;">
                <col style="width:125px;">
                <col style="width:50px;">
                <col style="width:85px;">
                <col style="width:36px;">
            </colgroup>
            <thead>
                <tr>
                    <th></th>
                    <th>
                        Product
                        <label style="font-size:11px;font-weight:400;margin-left:6px;color:var(--text-muted);cursor:pointer;" title="Show/hide description">
                            <input type="checkbox" id="descToggle" onchange="toggleDescriptions()" style="margin-right:2px;">Desc
                        </label>
                    </th>
                    <th>Batch</th>
                    <th>MRP / Avail</th>
                    <th>Qty</th>
                    <th>Sell Price</th>
                    <th>Discount</th>
                    <th>GST%</th>
                    <th>Total</th>
                    <th></th>
                </tr>
            </thead>
            <tbody id="salesBody">
                <!-- hidden template for new rows -->
                <tr class="salesRow template-row" style="display:none;">
                    <td><span class="co-badge" style="font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:#e0f2fe;color:#0369a1;white-space:nowrap;">—</span></td>
                    <td class="product-cell">
                        <div class="prod-name-wrap">
                            <input type="text" class="productInput" placeholder="Search product..." autocomplete="off" style="width:100%;min-width:0;">
                            <input type="hidden" name="product_id[]">
                            <input type="hidden" name="purchase_item_id[]">
                            <input type="hidden" name="item_company_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;width:100%;"></textarea>
                        </div>
                    </td>
                    <td class="batch-info" style="font-size:11px;color:var(--text-secondary);"></td>
                    <td style="text-align:center;font-size:11px;line-height:1.4;">
                        <span class="mrp" style="color:var(--text-muted);display:block;">0.00</span>
                        <span class="availQty" style="color:var(--success);">0</span>
                    </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="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" title="Remove">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>

                <!-- Pre-filled rows from existing master invoice -->
                <?php foreach ($editItems as $item):
                    $discTypeSelected_pct = ($item['discount_type'] === 'percent') ? 'selected' : '';
                    $discTypeSelected_amt = ($item['discount_type'] === 'amount')  ? 'selected' : '';
                    $lineTotal = $item['orig_sell_price'];
                    $disc_type = $item['discount_type'];
                    $disc_val  = floatval($item['discount_value']);
                    $finalUnit = $item['orig_sell_price'];
                    if ($disc_type === 'percent') $finalUnit -= ($finalUnit * $disc_val / 100);
                    elseif ($disc_type === 'amount') $finalUnit -= $disc_val;
                    $lineTotal = max(0, $finalUnit) * floatval($item['sold_qty']);
                ?>
                <tr class="salesRow" data-co-id="<?= $item['company_id'] ?>" data-co-pfx="<?= htmlspecialchars($item['company_prefix']) ?>">
                    <td><span class="co-badge" style="font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:#f1f5f9;color:#64748b;white-space:nowrap;"><?= htmlspecialchars($item['company_prefix']) ?></span></td>
                    <td class="product-cell">
                        <div class="prod-name-wrap">
                            <input type="text" class="productInput" autocomplete="off" style="width:100%;min-width:0;"
                                   value="<?= htmlspecialchars($item['product_name']) ?>">
                            <input type="hidden" name="product_id[]"       value="<?= $item['product_id'] ?>">
                            <input type="hidden" name="purchase_item_id[]" value="<?= $item['purchase_item_id'] ?>">
                            <input type="hidden" name="item_company_id[]"  value="<?= $item['company_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;width:100%;"><?= htmlspecialchars($item['description']) ?></textarea>
                        </div>
                    </td>
                    <td class="batch-info" style="font-size:11px;color:var(--text-secondary);"><?= htmlspecialchars($item['batch_no']) ?></td>
                    <td style="text-align:center;font-size:11px;line-height:1.4;">
                        <span class="mrp" style="color:var(--text-muted);display:block;"><?= number_format($item['mrp'], 2) ?></span>
                        <span class="availQty" style="color:var(--success);"><?= $item['available_qty'] ?></span>
                    </td>
                    <td><input type="number" step="0.01" class="qty" name="qty[]" min="0"
                               value="<?= $item['sold_qty'] ?>" style="width:100%;"></td>
                    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]"
                               value="<?= $item['orig_sell_price'] ?>" 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" <?= $discTypeSelected_pct ?>>%</option>
                                <option value="amount"  <?= $discTypeSelected_amt ?>>&#8377;</option>
                            </select>
                            <input type="number" step="0.01" class="discValue" name="disc_value[]"
                                   value="<?= $item['discount_value'] ?>" placeholder="0" style="flex:1;min-width:0;">
                        </div>
                    </td>
                    <td class="gstPercent" style="text-align:center;color:var(--text-muted);font-size:12px;"><?= $item['gst_percent'] ?></td>
                    <td class="lineTotal" style="text-align:right;font-weight:700;font-size:13px;"><?= number_format($lineTotal, 2) ?></td>
                    <td>
                        <button type="button" class="removeRow action-btn delete" title="Remove">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Totals & Payment -->
<div style="display:grid;grid-template-columns:1fr auto;gap:16px;align-items:start;">
    <div class="panel">
        <div class="panel-header"><span class="panel-title">Payment Details</span></div>
        <div class="panel-body">
            <div class="form-row">
                <div class="form-group">
                    <label>Overall Discount Type</label>
                    <select name="overall_discount_type" id="overallDiscType">
                        <option value="">None</option>
                        <option value="percent" <?= $master['overall_discount_type']==='percent' ? 'selected':'' ?>>Percent (%)</option>
                        <option value="amount"  <?= $master['overall_discount_type']==='amount'  ? 'selected':'' ?>>Amount (&#8377;)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Discount Value</label>
                    <input type="number" step="0.01" name="overall_discount_value" id="overallDiscValue"
                           value="<?= $master['overall_discount_value'] ?>" placeholder="0.00">
                </div>
                <div class="form-group">
                    <label>Received Amount</label>
                    <input type="number" step="0.01" name="received_amount" id="receivedAmount"
                           value="<?= $master['received_amount'] ?>" placeholder="0.00">
                </div>
                <div class="form-group">
                    <label>Payment Mode</label>
                    <select name="payment_mode">
                        <option value="Cash"  <?= $master['payment_mode']==='Cash' ?'selected':'' ?>>Cash</option>
                        <option value="UPI"   <?= $master['payment_mode']==='UPI'  ?'selected':'' ?>>UPI</option>
                        <option value="Card"  <?= $master['payment_mode']==='Card' ?'selected':'' ?>>Card</option>
                        <option value="Bank"  <?= $master['payment_mode']==='Bank' ?'selected':'' ?>>Bank Transfer</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="totals-box" style="min-width:260px;">
        <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 grand-total"><span>Net Total</span><span>&#8377; <span id="netTotal">0.00</span></span></div>
    </div>
</div>

<div style="display:flex;gap:12px;margin-top:16px;">
    <button type="submit" name="action" value="save" class="btn btn-secondary"><i class="fas fa-save"></i> Save Draft</button>
    <button type="submit" name="action" value="final" class="btn btn-success"
            onclick="return confirm('Finalize invoices and reduce stock for all companies?')">
        <i class="fas fa-check-circle"></i> Complete Sale
    </button>
</div>
</form>

<!-- Global batch dropdown (body-level to avoid overflow clipping) -->
<div id="batchDropdownGlobal" style="display:none;position:fixed;background:#fff;border:1px solid var(--border);border-radius:6px;max-height:280px;overflow-y:auto;z-index:9990;box-shadow:0 4px 18px rgba(0,0,0,.15);min-width:360px;"></div>

<script>
/* ---- Company badge colours ---- */
const CO_COLORS = ['#dbeafe:#1d4ed8','#dcfce7:#15803d','#fef9c3:#854d0e','#fce7f3:#9d174d','#ede9fe:#6d28d9'];
const coColorMap = {};
function getCoColor(coId) {
    if (!coColorMap[coId]) {
        const idx = Object.keys(coColorMap).length % CO_COLORS.length;
        coColorMap[coId] = CO_COLORS[idx];
    }
    return coColorMap[coId];
}

function toggleDescriptions() {
    const show = document.getElementById('descToggle').checked;
    document.getElementById('salesTable').classList.toggle('show-desc', show);
}

// Auto-check if any existing row has a description
(function() {
    const hasDesc = Array.from(document.querySelectorAll('#salesBody .salesRow:not(.template-row) textarea[name="description[]"]'))
        .some(t => t.value.trim() !== '');
    if (hasDesc) {
        document.getElementById('descToggle').checked = true;
        document.getElementById('salesTable').classList.add('show-desc');
    }
})();

/* Apply colours to pre-filled rows */
document.querySelectorAll('#salesBody .salesRow:not(.template-row)').forEach(row => {
    const coId = row.dataset.coId;
    if (coId) {
        const colors = getCoColor(coId).split(':');
        const badge  = row.querySelector('.co-badge');
        badge.style.background = colors[0];
        badge.style.color      = colors[1];
    }
});

/* ---- Client autocomplete ---- */
const CLIENTS = <?= json_encode($clientList) ?>;
function filterClients(q) {
    const dd = document.getElementById('clientDropdown');
    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>`;
    });
    dd.innerHTML = html;
    dd.style.display = 'block';
}
document.getElementById('clientSearch').addEventListener('blur', () =>
    setTimeout(() => document.getElementById('clientDropdown').style.display = 'none', 150));
function selectClient(id, name) {
    document.getElementById('clientId').value = id;
    document.getElementById('clientSearch').style.display = 'none';
    document.getElementById('clientDropdown').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();
}

/* ---- Product search — body-level dropdown ---- */
let searchTimer = null;
let activeProductInput = null;
const gdd = document.getElementById('batchDropdownGlobal');

function positionGlobalDD(input) {
    const rect = input.getBoundingClientRect();
    gdd.style.top   = rect.bottom + 'px';
    gdd.style.left  = rect.left + 'px';
    gdd.style.width = Math.max(360, rect.width) + 'px';
}
function hideGlobalDD() { gdd.style.display = 'none'; activeProductInput = null; }

document.addEventListener('input', function(e) {
    if (!e.target.classList.contains('productInput')) return;
    activeProductInput = e.target;
    const q = e.target.value.trim();
    clearTimeout(searchTimer);
    if (q.length < 1) { hideGlobalDD(); return; }
    searchTimer = setTimeout(() => {
        fetch('ajax_batches.php?q=' + encodeURIComponent(q))
        .then(r => r.json())
        .then(data => {
            if (!activeProductInput) return;
            if (!data.length) {
                gdd.innerHTML = '<div style="padding:10px;color:var(--text-muted);font-size:13px;">No results</div>';
            } else {
                let html = '';
                data.forEach(b => {
                    const colors = getCoColor(b.company_id).split(':');
                    const badge  = `<span style="font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:${colors[0]};color:${colors[1]};">${b.company_prefix}</span>`;
                    html += `<div class="cdd-item batch-item" style="display:flex;align-items:center;gap:8px;"
                        data-pid="${b.product_id}" data-pname="${b.product_name.replace(/"/g,'&quot;')}"
                        data-unit="${b.unit||''}" data-batch="${b.batch_no}"
                        data-piid="${b.purchase_item_id}" data-avail="${b.available_qty}"
                        data-mrp="${b.mrp}" data-price="${b.selling_price_incl}"
                        data-gst="${b.gst_percent}" data-coid="${b.company_id}"
                        data-coname="${b.company_name.replace(/"/g,'&quot;')}" data-copfx="${b.company_prefix}"
                        data-cobg="${getCoColor(b.company_id)}"
                        onmousedown="selectBatch(this, event)">
                        ${badge}
                        <span style="flex:1;font-size:12px;"><strong>${b.product_name}</strong>${b.unit ? ' <em style="color:#94a3b8;font-size:11px;">'+b.unit+'</em>' : ''}</span>
                        <span style="font-size:11px;color:var(--text-secondary);">${b.batch_no}</span>
                        <span style="font-size:11px;color:var(--success);">Qty:${b.available_qty}</span>
                        <span style="font-size:11px;color:var(--text-muted);">&#8377;${b.selling_price_incl.toFixed(2)}</span>
                    </div>`;
                });
                gdd.innerHTML = html;
            }
            positionGlobalDD(activeProductInput);
            gdd.style.display = 'block';
        });
    }, 250);
});

document.addEventListener('blur', function(e) {
    if (e.target.classList.contains('productInput')) setTimeout(hideGlobalDD, 200);
}, true);

document.addEventListener('click', function(e) {
    if (!e.target.classList.contains('productInput') && !gdd.contains(e.target)) hideGlobalDD();
});

function selectBatch(el, e) {
    e.preventDefault();
    if (!activeProductInput) return;
    const row    = activeProductInput.closest('tr');
    const colors = el.dataset.cobg.split(':');

    activeProductInput.value = el.dataset.pname;
    row.querySelector('input[name="product_id[]"]').value       = el.dataset.pid;
    row.querySelector('input[name="purchase_item_id[]"]').value = el.dataset.piid;
    row.querySelector('input[name="item_company_id[]"]').value  = el.dataset.coid;
    row.querySelector('.batch-info').textContent                = el.dataset.batch;
    row.querySelector('.mrp').textContent                        = parseFloat(el.dataset.mrp).toFixed(2);
    row.querySelector('.availQty').textContent                   = el.dataset.avail;
    row.querySelector('.gstPercent').textContent                 = el.dataset.gst;
    row.querySelector('.sellPrice').value                        = parseFloat(el.dataset.price).toFixed(2);

    const badge = row.querySelector('.co-badge');
    badge.textContent      = el.dataset.copfx;
    badge.style.background = colors[0];
    badge.style.color      = colors[1];

    row.dataset.coId  = el.dataset.coid;
    row.dataset.coPfx = el.dataset.copfx;

    hideGlobalDD();
    recalcRow(row);
}

/* ---- Calculations ---- */
function recalcRow(row) {
    const qty      = parseFloat(row.querySelector('.qty').value || 0);
    const price    = parseFloat(row.querySelector('.sellPrice').value || 0);
    const discType = row.querySelector('.discType').value;
    const discVal  = parseFloat(row.querySelector('.discValue').value || 0);
    let finalUnit  = price;
    if (discType === 'percent') finalUnit = price - (price * discVal / 100);
    else if (discType === 'amount') finalUnit = price - discVal;
    if (finalUnit < 0) finalUnit = 0;
    row.querySelector('.lineTotal').textContent = (finalUnit * qty).toFixed(2);
    recalcInvoiceTotals();
}

function recalcInvoiceTotals() {
    let gross = 0, gstTotal = 0;
    document.querySelectorAll('#salesBody .salesRow:not(.template-row)').forEach(row => {
        const qty      = parseFloat(row.querySelector('.qty').value || 0);
        const price    = parseFloat(row.querySelector('.sellPrice').value || 0);
        const discType = row.querySelector('.discType').value;
        const discVal  = parseFloat(row.querySelector('.discValue').value || 0);
        const gstp     = parseFloat(row.querySelector('.gstPercent').textContent || 0);
        let finalUnit  = price;
        if (discType === 'percent') finalUnit = price - (price * discVal / 100);
        else if (discType === 'amount') finalUnit = price - discVal;
        if (finalUnit < 0) finalUnit = 0;
        const line = finalUnit * qty;
        gross += line;
        if (qty > 0 && gstp > 0) gstTotal += (finalUnit - finalUnit / (1 + gstp / 100)) * qty;
    });
    const overallType = document.getElementById('overallDiscType').value;
    const overallVal  = parseFloat(document.getElementById('overallDiscValue').value || 0);
    let net = gross;
    if (overallType === 'percent') net = gross - (gross * overallVal / 100);
    else if (overallType === 'amount') net = gross - overallVal;
    if (net < 0) net = 0;
    document.getElementById('grossTotal').textContent = gross.toFixed(2);
    document.getElementById('gstTotal').textContent   = gstTotal.toFixed(2);
    document.getElementById('netTotal').textContent   = net.toFixed(2);
}

document.addEventListener('input', function(e) {
    if (['qty','sellPrice','discValue'].some(c => e.target.classList.contains(c)) || e.target.id === 'overallDiscValue') {
        const row = e.target.closest('.salesRow');
        if (row) recalcRow(row); else 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); else recalcInvoiceTotals();
    }
});

/* ---- Add / Remove rows ---- */
function addRow() {
    const tmpl   = document.querySelector('.template-row');
    const newRow = tmpl.cloneNode(true);
    newRow.classList.remove('template-row');
    newRow.style.display = '';
    newRow.querySelectorAll('input').forEach(i => i.value = '');
    newRow.querySelectorAll('textarea').forEach(t => t.value = '');
    newRow.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
    newRow.querySelector('.mrp').textContent      = '0.00';
    newRow.querySelector('.availQty').textContent = '0';
    newRow.querySelector('.gstPercent').textContent = '0';
    newRow.querySelector('.lineTotal').textContent  = '0.00';
    newRow.querySelector('.batch-info').textContent = '';
    const badge = newRow.querySelector('.co-badge');
    badge.textContent      = '—';
    badge.style.background = '#f1f5f9';
    badge.style.color      = '#64748b';
    document.getElementById('salesBody').appendChild(newRow);
}
document.getElementById('addRow').addEventListener('click', addRow);

document.addEventListener('click', function(e) {
    const btn = e.target.closest('.removeRow');
    if (btn) {
        const rows = document.querySelectorAll('#salesBody .salesRow:not(.template-row)');
        if (rows.length > 1) { btn.closest('tr').remove(); recalcInvoiceTotals(); }
    }
});

/* ---- Form validation ---- */
document.getElementById('masterForm').addEventListener('submit', function(e) {
    if (!document.getElementById('clientId').value) {
        e.preventDefault();
        alert('Please select a client.');
        return;
    }
    const rows = document.querySelectorAll('#salesBody .salesRow:not(.template-row)');
    let hasItem = false;
    rows.forEach(r => { if (r.querySelector('input[name="purchase_item_id[]"]').value) hasItem = true; });
    if (!hasItem) { e.preventDefault(); alert('Please add at least one product.'); }
});

/* ---- Init totals ---- */
recalcInvoiceTotals();
</script>

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

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