<?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>
    <!-- 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="quickSearchMasterEdit" class="productInput" placeholder="Search product to add to bill..."
                   autocomplete="off" style="padding:6px 8px 6px 32px;width:100%;font-size:13px;border:1px solid #bfdbfe;border-radius:6px;background:#fff;">
        </div>
        <input type="number" id="quickQtyMasterEdit" 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="quickAddBtnMasterEdit" class="btn btn-primary btn-sm">
            <i class="fas fa-plus"></i> Add to Bill
        </button>
        <span id="masterEditQuickMsg" style="font-size:12px;color:var(--danger);display:none;font-weight:500;"></span>
    </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="width:76px;">
                <col style="min-width:180px;width:22%;">
                <col style="width:110px;">
                <col style="width:76px;">
                <col style="width:60px;">
                <col style="width:88px;">
                <col style="width:88px;">
                <col style="width:110px;">
                <col style="width:46px;">
                <col style="width:80px;">
                <col style="width:36px;">
            </colgroup>
            <thead>
                <tr>
                    <th></th>
                    <th style="text-align:center;">Code</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 style="text-align:right;">Taxable Rate</th>
                    <th style="text-align:right;">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 style="text-align:center;"><span class="co-badge" style="font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:#e0f2fe;color:#0369a1;white-space:nowrap;cursor:default;">—</span></td>
                    <td style="text-align:center;"><span class="co-code" style="font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:#f1f5f9;color:#64748b;white-space:nowrap;cursor:default;">—</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="taxableRate" placeholder="0.00" style="width:100%;background:#f8faff;text-align:right;"></td>
                    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]" placeholder="0.00" style="width:100%;text-align:right;"></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' : '';
                    $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']);
                    $gst = floatval($item['gst_percent']);
                    $taxableRate = $gst > 0
                        ? round($item['orig_sell_price'] / (1 + $gst / 100), 2)
                        : $item['orig_sell_price'];
                    $rowCode = htmlspecialchars($item['company_prefix'] . '-' . $item['product_id']);
                ?>
                <tr class="salesRow" data-co-id="<?= $item['company_id'] ?>" data-co-pfx="<?= htmlspecialchars($item['company_prefix']) ?>">
                    <td style="text-align:center;"><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 style="text-align:center;">
                        <span class="co-code" style="font-family:monospace;font-size:10px;font-weight:700;padding:2px 5px;border-radius:3px;background:#eff6ff;color:#2563eb;white-space:nowrap;cursor:pointer;"
                              onclick="showPurchaseDetails(<?= $item['product_id'] ?>, this.closest('tr'))"
                              title="Click to view purchase details"><?= $rowCode ?></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="taxableRate"
                               value="<?= number_format($taxableRate, 2, '.', '') ?>"
                               placeholder="0.00" style="width:100%;background:#f8faff;text-align:right;"></td>
                    <td><input type="number" step="0.01" class="sellPrice" name="sell_price[]"
                               value="<?= $item['orig_sell_price'] ?>" style="width:100%;text-align:right;"></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 {
                const isQuick = activeProductInput.id === 'quickSearchMasterEdit';
                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>`;
                    if (isQuick) {
                        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(--success);">Avail: ${b.available_qty}</span>
                            <span style="font-size:11px;color:var(--text-muted);">&#8377;${b.selling_price_incl.toFixed(2)}</span>
                        </div>`;
                    } else {
                        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();
});

let _editQuickBatch = null;

function showEditQuickMsg(msg) {
    const el = document.getElementById('masterEditQuickMsg');
    if (!el) return;
    el.textContent = msg;
    el.style.display = 'inline';
    clearTimeout(el._t);
    el._t = setTimeout(() => { el.style.display = 'none'; }, 3500);
}

function checkDuplicateMasterEdit(pid, excludeRow) {
    const rows = document.querySelectorAll('#salesBody .salesRow:not(.template-row)');
    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(pid)) {
            return i + 1;
        }
    }
    return null;
}

function selectBatch(el, e) {
    e.preventDefault();

    // Quick-add bar
    if (activeProductInput && activeProductInput.id === 'quickSearchMasterEdit') {
        _editQuickBatch = Object.assign({}, el.dataset);
        activeProductInput.value = el.dataset.pname;
        hideGlobalDD();
        document.getElementById('quickQtyMasterEdit').focus();
        return;
    }

    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;
    const batchCell = row.querySelector('.batch-info');
    batchCell.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];

    const codeSpan = row.querySelector('.co-code');
    if (codeSpan) {
        const code = el.dataset.copfx + '-' + el.dataset.pid;
        codeSpan.textContent  = code;
        codeSpan.style.background = '#eff6ff';
        codeSpan.style.color      = '#2563eb';
        codeSpan.style.cursor     = 'pointer';
        codeSpan.title            = 'Click to view purchase details';
        codeSpan.onclick          = () => showPurchaseDetails(el.dataset.pid, row);
    }

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

    hideGlobalDD();
    recalcRow(row, 'sell');
}

/* ---- Calculations ---- */
function recalcRow(row, source) {
    source = source || 'sell';
    const qty      = parseFloat(row.querySelector('.qty').value || 0);
    const gstp     = parseFloat(row.querySelector('.gstPercent').textContent || 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').textContent = (taxableRate * qty).toFixed(2);
    recalcInvoiceTotals();
}

function recalcInvoiceTotals() {
    let grossTaxable = 0, gstTotal = 0;
    document.querySelectorAll('#salesBody .salesRow:not(.template-row)').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);
    let net = subTotal;
    if (overallType === 'percent') net = subTotal - (subTotal * overallVal / 100);
    else if (overallType === 'amount') net = subTotal - overallVal;
    if (net < 0) net = 0;
    document.getElementById('grossTotal').textContent = grossTaxable.toFixed(2);
    document.getElementById('gstTotal').textContent   = gstTotal.toFixed(2);
    document.getElementById('netTotal').textContent   = net.toFixed(2);
}

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

/* ---- 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';
    if (newRow.querySelector('.taxableRate')) newRow.querySelector('.taxableRate').value = '';
    newRow.querySelector('.batch-info').textContent = '';
    const badge = newRow.querySelector('.co-badge');
    badge.textContent      = '—';
    badge.style.background = '#f1f5f9';
    badge.style.color      = '#64748b';
    const codeSpanNew = newRow.querySelector('.co-code');
    if (codeSpanNew) {
        codeSpanNew.textContent  = '—';
        codeSpanNew.style.background = '#f1f5f9';
        codeSpanNew.style.color      = '#64748b';
        codeSpanNew.style.cursor     = 'default';
        codeSpanNew.title            = '';
        codeSpanNew.onclick          = null;
    }
    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(); }
    }
});

/* ---- Quick Add to Bill (edit page) ---- */
document.getElementById('quickAddBtnMasterEdit').addEventListener('click', function() {
    if (!_editQuickBatch || !_editQuickBatch.pid) {
        showEditQuickMsg('Please search and select a product first.');
        return;
    }
    const pid = parseInt(_editQuickBatch.pid);
    const dup = checkDuplicateMasterEdit(pid, null);
    if (dup !== null) {
        showEditQuickMsg('Product already added in row ' + dup + '.');
        return;
    }
    const qty = parseFloat(document.getElementById('quickQtyMasterEdit').value) || 1;

    const allRows = document.querySelectorAll('#salesBody .salesRow:not(.template-row)');
    let newRow = null;
    for (const r of allRows) {
        if (!r.querySelector('input[name="product_id[]"]').value) { newRow = r; break; }
    }
    if (!newRow) {
        addRow();
        const rows = document.querySelectorAll('#salesBody .salesRow:not(.template-row)');
        newRow = rows[rows.length - 1];
    }

    const colors = _editQuickBatch.cobg.split(':');
    newRow.querySelector('.productInput').value                    = _editQuickBatch.pname;
    newRow.querySelector('input[name="product_id[]"]').value       = _editQuickBatch.pid;
    newRow.querySelector('input[name="purchase_item_id[]"]').value = _editQuickBatch.piid;
    newRow.querySelector('input[name="item_company_id[]"]').value  = _editQuickBatch.coid;

    const batchCell = newRow.querySelector('.batch-info');
    batchCell.textContent = _editQuickBatch.batch;

    newRow.querySelector('.mrp').textContent        = parseFloat(_editQuickBatch.mrp).toFixed(2);
    newRow.querySelector('.availQty').textContent   = _editQuickBatch.avail;
    newRow.querySelector('.gstPercent').textContent = _editQuickBatch.gst;
    newRow.querySelector('.sellPrice').value        = parseFloat(_editQuickBatch.price).toFixed(2);
    newRow.querySelector('.qty').value              = qty;

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

    const codeSpan = newRow.querySelector('.co-code');
    if (codeSpan) {
        const code = _editQuickBatch.copfx + '-' + _editQuickBatch.pid;
        codeSpan.textContent  = code;
        codeSpan.style.background = '#eff6ff';
        codeSpan.style.color      = '#2563eb';
        codeSpan.style.cursor     = 'pointer';
        codeSpan.title            = 'Click to view purchase details';
        codeSpan.onclick          = () => showPurchaseDetails(_editQuickBatch.pid, newRow);
    }

    recalcRow(newRow, 'sell');

    _editQuickBatch = null;
    document.getElementById('quickSearchMasterEdit').value = '';
    document.getElementById('quickQtyMasterEdit').value    = '1';
    document.getElementById('quickSearchMasterEdit').focus();
});

/* ---- Purchase Details Popup ---- */
let _pdBatches = [];
let _pdCurrentRow = null;

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; }
    const row = _pdCurrentRow;
    const pid = row.querySelector('input[name="product_id[]"]').value;
    row.querySelector('input[name="purchase_item_id[]"]').value = b.purchase_item_id;
    row.querySelector('input[name="item_company_id[]"]').value  = b.company_id;
    const batchCell = row.querySelector('.batch-info');
    batchCell.innerHTML = (b.batch_no || '—') + ' <i class="fas fa-pen" style="font-size:9px;color:var(--text-muted);margin-left:3px;opacity:.7;"></i>';
    batchCell.dataset.pid  = pid;
    batchCell.style.cursor = 'pointer';
    batchCell.title        = 'Click to change batch';
    row.querySelector('.mrp').textContent        = parseFloat(b.mrp).toFixed(2);
    row.querySelector('.availQty').textContent   = b.available_qty;
    row.querySelector('.gstPercent').textContent = b.gst_percent;
    row.querySelector('.sellPrice').value        = parseFloat(b.selling_price_incl).toFixed(2);
    const badge = row.querySelector('.co-badge');
    const colors = getCoColor(b.company_id).split(':');
    badge.textContent      = b.company_prefix;
    badge.style.background = colors[0];
    badge.style.color      = colors[1];
    const codeSpan = row.querySelector('.co-code');
    if (codeSpan) {
        const code = b.company_prefix + '-' + pid;
        codeSpan.textContent      = code;
        codeSpan.style.background = '#eff6ff';
        codeSpan.style.color      = '#2563eb';
        codeSpan.style.cursor     = 'pointer';
        codeSpan.title            = 'Click to view purchase details';
        codeSpan.onclick          = () => showPurchaseDetails(pid, row);
    }
    row.dataset.coId  = b.company_id;
    row.dataset.coPfx = b.company_prefix;
    recalcRow(row, 'sell');
    closePurchaseDetails();
}

/* ---- 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 ---- */
document.querySelectorAll('#salesBody .salesRow:not(.template-row)').forEach(row => recalcRow(row, 'sell'));
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; }
.compact-sales-table .taxableRate,.compact-sales-table .sellPrice { text-align:right; }
/* Description toggle */
.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'; ?>
