<?php
require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

$business_id = $current_business['business_id'];

// =====================================================
// 1. DATA FETCHING (VIEW MODE LOGIC)
// =====================================================
$view_mode = false; // Default: New Entry
$sale_data = [];
$sale_items_data = [];

// If ID is passed in URL (e.g. index.php?r=sale&id=15)
if (isset($_GET['id'])) {
    $sale_id = $_GET['id'];
    
    // Fetch Header from 'sales' table
    $sale_data = one(
        "SELECT s.*, it.type_name
        FROM sales s
        JOIN invoice_types it ON s.invoice_type_id = it.id
        WHERE s.id = ? AND s.business_id = ?",
        [$sale_id, $business_id]
        );

    
    if ($sale_data) {
        $view_mode = true; // LOCK PAGE
        
        // Fetch Items: Join with new_items to get the name 'moong dal' etc.
        $sale_items_data = all_rows(
            "SELECT si.*, i.item_name 
             FROM sale_items si 
             JOIN new_items i ON si.item_id = i.id 
             WHERE si.sale_id = ?", 
            [$sale_id]
        );
    }
}

// =====================================================
// 2. SAVE LOGIC (ONLY FOR NEW SALES)
// =====================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_sale']) && !$view_mode) {
    
    // 1. Validate Items
    if (!isset($_POST['item_id']) || !is_array($_POST['item_id'])) {
        $_SESSION['error'] = "Please add at least one item.";
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }

    $invoice_type_id = (int)($_POST['invoice_type'] ?? 0);

    $type_settings = one(
    "SELECT tax_type FROM invoice_types WHERE id = ? AND business_id = ?",
    [$invoice_type_id, $business_id]
    );

    $is_inclusive = ($type_settings && $type_settings['tax_type'] === 'inclusive');
    $party_id = $_POST['party'] ?? 0;
    $bill_no = $_POST['bill_no'] ?? '';
    $sale_date = $_POST['sale_date'] ?? date('Y-m-d');
    $due_date = $_POST['due_date'] ?? date('Y-m-d');
    $terms = $_POST['terms'] ?? 'Cash';
    $cash_tendered = (float)($_POST['cash_tendered'] ?? 0);
    
    $dis_per_all = (float)($_POST['dis_per_all'] ?? 0);
    $overall_discount = (float)($_POST['overall_discount'] ?? 0);
    $delivery_charges = (float)($_POST['delivery_charges'] ?? 0);
    $freight_charges = (float)($_POST['freight_charges'] ?? 0);

    $items_id = $_POST['item_id'] ?? [];
    $batch = $_POST['batch_no'] ?? [];
    $qty = $_POST['qty'] ?? [];     
    $alt_qty = $_POST['alt_qty'] ?? []; 
    $free = $_POST['free_qty'] ?? [];
    $rate = $_POST['rate'] ?? [];    
    $dis_per = $_POST['dis_per'] ?? [];
    $tax_per = $_POST['tax_per'] ?? [];

    $subtotal = 0; $total_dis = 0; $total_tax = 0; $item_grand_total = 0;

    foreach ($items_id as $i => $id) {
        $q = (float)($qty[$i] ?? 0);
        $r = (float)($rate[$i] ?? 0);
        $d = (float)($dis_per[$i] ?? 0);
        $t = (float)($tax_per[$i] ?? 0);

        if ($is_inclusive) {
            $gross_inclusive = $q * $r; 
            $d_amt = $gross_inclusive * ($d / 100);
            $net_inclusive = $gross_inclusive - $d_amt;
            $taxable = $net_inclusive / (1 + ($t / 100));
            $t_amt = $net_inclusive - $taxable;
            $basic = $taxable;
        } else {
            $basic = $q * $r;
            $d_amt = $basic * ($d / 100);
            $taxable = $basic - $d_amt;
            $t_amt = $taxable * ($t / 100);
        }
        $net = $taxable + $t_amt;
        $subtotal += $basic;
        $total_dis += $d_amt;
        $total_tax += $t_amt;
        $item_grand_total += $net;
    }

    $final_grand_total = ($item_grand_total - $overall_discount) + $delivery_charges + $freight_charges;
    $change_amt = $cash_tendered - $final_grand_total;
    $half_tax = $total_tax / 2;

    query(
        "INSERT INTO sales 
        (business_id, party_id, bill_no, invoice_type_id, sale_date, due_date, payment_terms,
         subtotal, total_discount, total_tax, cgst, sgst, 
         discount_all, delivery_charges, freight_charges, grand_total,
         cash_tendered, change_amount, created_at)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())",
        [$business_id, $party_id, $bill_no, $invoice_type_id, $sale_date, $due_date, $terms, 
         $subtotal, $total_dis, $total_tax, $half_tax, $half_tax,
         $overall_discount, $delivery_charges, $freight_charges, $final_grand_total,
         $cash_tendered, $change_amt]
    );
    $sale_id = last_id();

    foreach ($items_id as $i => $id) {
        $q = (float)($qty[$i] ?? 0); $f = (float)($free[$i] ?? 0);
        $r = (float)($rate[$i] ?? 0); $d = (float)($dis_per[$i] ?? 0);
        $t = (float)($tax_per[$i] ?? 0); $b = ($batch[$i] ?? '');
        $a_qty = ($alt_qty[$i] ?? 0);

        if ($is_inclusive) {
             $gross_inclusive = $q * $r; $d_amt = $gross_inclusive * ($d / 100);
             $net_inclusive = $gross_inclusive - $d_amt;
             $taxable = $net_inclusive / (1 + ($t / 100));
             $t_amt = $net_inclusive - $taxable;
             $net = $net_inclusive; $basic_db = $taxable; 
        } else {
             $basic_db = $q * $r; $d_amt = $basic_db * ($d / 100);
             $taxable = $basic_db - $d_amt; $t_amt = $taxable * ($t / 100);
             $net = $taxable + $t_amt;
        }

        query(
            "INSERT INTO sale_items
            (business_id, sale_id, item_id, batch_no, qty, alt_qty, free_qty, rate, amount,
             discount_per, discount_amt, tax_per, tax_amt, net_value)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            [$business_id, $sale_id, $id, $b, $q, $a_qty, $f, $r, $basic_db, $d, $d_amt, $t, $t_amt, $net]
        );
        query("UPDATE new_items SET opening_qty_kg = opening_qty_kg - ? WHERE id = ? AND business_id = ?", [$q + $f, $id, $business_id]);
    }

    $_SESSION['success'] = "Sale saved successfully!";
    $_SESSION['last_sale_id'] = $sale_id;
    echo "<script>window.location.href='" . BASE_URL . "/public/index.php?r=sale&id={$sale_id}';</script>";
    exit;

}

// =====================================================
// 3. LOAD DATA
// =====================================================
$parties = all_rows("SELECT id, name FROM accounts WHERE business_id = ? ORDER BY name", [$business_id]);
$items = all_rows("SELECT id, item_name, primary_unit, alternate_unit, sale_price, purchase_price, mrp, opening_qty_kg, conversion_factor, tax_slab FROM new_items WHERE business_id = ? ORDER BY item_name", [$business_id]);
$invoice_types = all_rows(
  "SELECT id, type_name, tax_type 
   FROM invoice_types 
   WHERE business_id = ?",
  [$business_id]
);


// Helper variable: If View Mode, use 'disabled' attribute on HTML inputs
$disabled = $view_mode ? 'disabled' : '';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Sale View</title>
    <style>
        body { 
            background-image: url("<?= BASE_URL ?>/public/grocery.png");
            background-size: cover; background-attachment: fixed; background-position: center;
            background-color: #f4f6f9; font-size: 14px;
        }
        .card { 
            background: rgba(255, 255, 255, 0.95); border-radius: 8px; 
            padding: 15px; border:none; box-shadow: 0 2px 4px rgba(0,0,0,0.1); 
        }
        .form-control, .form-select { border-radius: 4px; font-size: 13px; padding: 5px 8px; }
        .table th { background: #00bcd4; color: white; font-weight: 500; font-size: 13px; } /* Cyan header like screenshot */
        label { font-weight: 600; font-size: 12px; margin-bottom: 2px; }
        .table td { vertical-align: middle; padding: 5px; background: rgba(255,255,255,0.8); }
        .bg-light-blue { background-color: #e0f7fa !important; }
        .charges-section { border-bottom: 1px solid #ffffff40; padding-bottom: 10px; margin-bottom: 10px; }
        /* Style disabled inputs to look solid like screenshot */
        .form-control:disabled, .form-select:disabled { 
            background-color: #e9ecef; opacity: 1; color: #333; font-weight: 500; border: 1px solid #ced4da;
        }
        .bg-light-blue { background-color: #e0f7fa !important; }
        .footer-totals input { font-weight: bold; text-align: right; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">
    <?php if(isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <strong>Success!</strong> <?= $_SESSION['success']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

    <form method="post" id="saleForm">

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="text-primary m-0">
                <?= $view_mode ? 'VIEW SALE #' . ($sale_data['id'] ?? '') : 'SALE ENTRY' ?>
            </h4>
            
            <div class="input-group" style="width: auto;">
                <span class="input-group-text bg-white text-primary fw-bold">Invoice Type</span>
                <select name="invoice_type" id="invoiceTypeSelect"
                            class="form-select text-primary fw-bold"
                            style="width: 200px;" <?= $disabled ?>>

                    <?php
                    $sel_type = $view_mode ? ($sale_data['invoice_type_id'] ?? 0) : 0;

                    if (empty($invoice_types)) {
                        echo '<option value="0">GST Invoice</option>';
                    } else {
                        foreach ($invoice_types as $type) {
                            $sel = ($sel_type == $type['id']) ? 'selected' : '';
                            echo "<option value='{$type['id']}'
                                        data-tax-type='{$type['tax_type']}'
                                        $sel>
                                    {$type['type_name']}
                                </option>";
                        }
                    }
                    ?>
                </select>

            </div>
        </div>

        <div class="card mb-3">
            <div class="row g-2">
                <div class="col-md-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <label>Party Name</label>
                        <a href="<?= BASE_URL ?>/public/index.php?r=create_account" target="_blank" style="font-size: 11px; text-decoration: none; color: rgba(var(--bs-primary-rgb));">
                            + Add New Party
                        </a>
                    </div>
                    
                    <select name="party" class="form-select" required <?= $disabled ?>>
                        <option value="">Select Party</option>
                        <?php foreach ($parties as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($view_mode && $sale_data['party_id'] == $p['id']) ? 'selected' : '' ?>>
                                <?= $p['name'] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Sale Date</label>
                    <input type="date" name="sale_date" class="form-control" 
                           value="<?= $view_mode ? $sale_data['sale_date'] : date('Y-m-d') ?>" <?= $disabled ?>>
                </div>
                <div class="col-md-2">
                    <label>Terms</label>
                    <select name="terms" class="form-select" <?= $disabled ?>>
                        <?php $t = $view_mode ? ($sale_data['payment_terms']??'') : 'Cash'; ?>
                        <option value="Credit" <?= $t=='Credit'?'selected':'' ?>>Credit</option>
                        <option value="Cash" <?= $t=='Cash'?'selected':'' ?>>Cash</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>No. (Bill #)</label>
                    <input type="text" name="bill_no" class="form-control" placeholder="Auto" 
                           value="<?= $view_mode ? ($sale_data['bill_no']??'') : '' ?>" <?= $disabled ?>>
                </div>
                <div class="col-md-3">
                    <label>Due Date</label>
                    <input type="date" name="due_date" class="form-control" 
                           value="<?= $view_mode ? ($sale_data['due_date']??date('Y-m-d')) : date('Y-m-d') ?>" <?= $disabled ?>>
                </div>
            </div>
        </div>

        <?php if(!$view_mode): ?>
        <div class="card mb-3 bg-light-blue">
            <div class="row g-1 align-items-end" id="entryRow">
                <div class="col-md-2">
                    <label>Item Name</label>
                    <select class="form-select itemSel">
                        <option value="">Select Item</option>
                        <?php foreach ($items as $i): ?>
                        <option value="<?= $i['id'] ?>"
                            data-rate="<?= $i['sale_price'] ?>"
                            data-purchase="<?= $i['purchase_price'] ?>"
                            data-mrp="<?= $i['mrp'] ?>"
                            data-tax="<?= $i['tax_slab'] ?>"
                            data-unit="<?= $i['primary_unit'] ?>" 
                            data-alt-unit="<?= $i['alternate_unit'] ?? '' ?>"
                            data-factor="<?= $i['conversion_factor'] ?? 1 ?>" 
                            data-stock="<?= $i['opening_qty_kg'] ?>">
                            <?= $i['item_name'] ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-1"><label class="text-danger">Stock</label><input type="text" class="form-control stock-display" readonly></div>
                <div class="col-md-1" style="width:7%"><label>Batch</label><input type="text" class="form-control batch" placeholder="Batch"></div>
                <div class="col-md-1" style="width:7%"><label id="lblQty">Qty</label><input type="number" class="form-control qty" placeholder="Qty"></div>
                <div class="col-md-1" style="width:7%"><label id="lblAlt">Alt</label><input type="number" class="form-control alt_qty" placeholder="Alt"></div>
                <div class="col-md-1" style="width:6%"><label>Free</label><input type="number" class="form-control free" value="0"></div>
                <div class="col-md-2" style="width:13%"><label>Price & Unit</label>
                    <div class="price-group">
                        <select class="form-select price-sel"></select>
                        <input type="number" class="form-control rate" step="0.01" placeholder="Rate">
                    </div>
                </div>
                <div class="col-md-1"><label>Basic</label><input type="text" class="form-control basic_amt" readonly></div>
                <div class="col-md-1" style="width:7%"><label>Dis%</label><input type="number" class="form-control dis_per" value="0"></div>
                <div class="col-md-1" style="width:7%"><label>Tax%</label><input type="number" class="form-control tax_per" readonly></div>
                <div class="col-md-1"><label>Net</label>
                    <input type="text" class="form-control net_value" readonly>
                    <input type="hidden" class="tax_amt_hidden">
                </div>
            </div>
            <div class="col-12 mt-3 text-end"><button type="button" class="btn btn-success px-4" id="addItem">Add Item +</button></div>
        </div>
        <?php endif; ?>

        <div class="card mb-3 p-0" style="min-height: 200px;">
            <table class="table table-bordered mb-0">
                <thead>
                    <tr>
                        <th>Item Name</th>
                        <th>Qty</th>
                        <th>Alt</th>
                        <th>Price</th>
                        <th>Basic</th>
                        <th>Dis %</th>
                        <th>Tax</th>
                        <th>Net Value</th>
                        <?php if(!$view_mode): ?><th>Act</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody id="addedItems">
                    <?php if(!empty($sale_items_data)): ?>
                        <?php foreach($sale_items_data as $item): ?>
                            <tr>
                                <td><?= htmlspecialchars($item['item_name']) ?> <br><small class="text-muted"><?= $item['batch_no'] ?></small></td>
                                <td><?= $item['qty'] ?></td>
                                <td><?= $item['alt_qty'] ?></td>
                                <td><?= $item['rate'] ?></td>
                                <td><?= number_format($item['amount'], 2) ?></td>
                                <td><?= $item['discount_per'] ?>%</td>
                                <td>
                                    <?= $item['tax_per'] ?>% 
                                    <br><small class="text-muted">(<?= $item['tax_amt'] ?>)</small>
                                </td>
                                <td class="row-net"><?= number_format($item['net_value'], 2) ?></td>
                                <?php if(!$view_mode): ?><td><button type="button" class="btn btn-danger btn-sm">X</button></td><?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="card bg-secondary text-white p-3">
            <div class="row g-2 align-items-center charges-section">
                <div class="col-md-3">
                    <label>Total Item Value</label>
                    <input type="text" class="form-control" id="itemsSubtotal" readonly value="<?= $view_mode ? $sale_data['subtotal'] : '' ?>">
                </div>
                <div class="col-md-2">
                    <label>Overall Disc (%)</label>
                    <input type="number" class="form-control" id="disPerAll" value="<?= $view_mode ? ($sale_data['discount_all_per']??'') : '' ?>" <?= $disabled ?> placeholder="%">
                </div>
                <div class="col-md-2">
                    <label>Less: Discount</label>
                    <input type="number" class="form-control text-danger fw-bold" id="disAmtAll" value="<?= $view_mode ? $sale_data['discount_all'] : '' ?>" <?= $disabled ?>>
                </div>
                <div class="col-md-2">
                    <label>Add: Delivery</label>
                    <input type="number" class="form-control text-success fw-bold" id="deliveryCharges" value="<?= $view_mode ? $sale_data['delivery_charges'] : '' ?>" <?= $disabled ?>>
                </div>
                <div class="col-md-3">
                    <label>Add: Freight</label>
                    <input type="number" class="form-control text-success fw-bold" id="freightCharges" value="<?= $view_mode ? $sale_data['freight_charges'] : '' ?>" <?= $disabled ?>>
                </div>
            </div>

            <div class="row g-2 align-items-center mt-2">
                <div class="col-md-6"></div> 
                <div class="col-md-2 text-end">
                    <label>NET GRAND TOTAL</label>
                    <input type="text" class="form-control fs-5" id="grandTotal" readonly style="background:#ffc107; color:#000;" 
                           value="<?= $view_mode ? number_format($sale_data['grand_total'], 2) : '' ?>">
                </div>
                <div class="col-md-2 text-end">
                    <label>Cash Tendered</label>
                    <input type="number" name="cash_tendered" class="form-control" id="cashTendered" value="<?= $view_mode ? $sale_data['cash_tendered'] : '0' ?>" <?= $disabled ?>>
                </div>
                <div class="col-md-2 text-end">
                    <label>Change</label>
                    <input type="text" class="form-control" id="changeAmt" readonly value="<?= $view_mode ? $sale_data['change_amount'] : '' ?>">
                </div>
            </div>

            <div class="text-end mt-4">
                <?php if(!$view_mode): ?>
                    <button type="submit" name="save_sale" class="btn btn-warning fw-bold px-5">SAVE SALE</button>
                <?php else: ?>
                    <button type="button" onclick="window.print()" class="btn btn-light fw-bold">PRINT</button>
                    <a href="index.php?r=sale" class="btn btn-primary fw-bold ms-2">NEW SALE</a>
                    <a href="index.php?r=reports/cash_credit" class="btn btn-outline-light ms-2">BACK TO REPORT</a>
                <?php endif; ?>
            </div>
        </div>

    </form>
</div>

<?php if(!$view_mode): ?>

<script>
let currentFactor = 1;

// --- DYNAMIC CALCULATION ---
function calculateRow() {
    let row = document.getElementById("entryRow");
    
    // Get inputs
    let qty = parseFloat(row.querySelector(".qty").value) || 0;
    let rate = parseFloat(row.querySelector(".rate").value) || 0;
    let disPer = parseFloat(row.querySelector(".dis_per").value) || 0;
    let taxPer = parseFloat(row.querySelector(".tax_per").value) || 0;
    
    // Get Tax Type (Inclusive/Exclusive) from Dropdown
    let typeSel = document.getElementById("invoiceTypeSelect");
    let taxType = typeSel.options[typeSel.selectedIndex].dataset.taxType; // 'inclusive' or 'exclusive'

    let basic = 0;
    let taxAmt = 0;
    let netValue = 0;

    if(taxType === 'inclusive') {
        // --- INCLUSIVE CALCULATION ---
        let grossInclusive = qty * rate; 
        let disAmt = grossInclusive * (disPer / 100);
        let netInclusive = grossInclusive - disAmt;
        let taxableValue = netInclusive / (1 + (taxPer / 100));
        taxAmt = netInclusive - taxableValue;
        basic = taxableValue; 
        netValue = netInclusive; 
        row.querySelector(".basic_amt").value = taxableValue.toFixed(2);
    } else {
        // --- EXCLUSIVE CALCULATION (Standard) ---
        basic = qty * rate; 
        let disAmt = basic * (disPer / 100);
        let taxable = basic - disAmt;
        taxAmt = taxable * (taxPer / 100);
        netValue = taxable + taxAmt;
        row.querySelector(".basic_amt").value = basic.toFixed(2);
    }

    row.querySelector(".tax_amt_hidden").value = taxAmt.toFixed(2);
    row.querySelector(".net_value").value = netValue.toFixed(2);
}

// Recalculate if Invoice Type Changes
document.getElementById("invoiceTypeSelect").addEventListener("change", function() {
    calculateRow();
});

// --- ITEM SELECTION ---
document.querySelector(".itemSel").addEventListener("change", function () {
    if (this.value === "") return;

    let op = this.options[this.selectedIndex];
    let row = document.getElementById("entryRow");

    let saleRate = parseFloat(op.dataset.rate) || 0;
    let purRate  = parseFloat(op.dataset.purchase) || 0;
    let mrpRate  = parseFloat(op.dataset.mrp) || 0;
    let taxRate  = parseFloat(op.dataset.tax) || 0; 
    
    let baseUnit = op.dataset.unit || "Qty";
    let altUnit  = op.dataset.altUnit || "";
    let factor   = parseFloat(op.dataset.factor) || 1;
    let stock    = op.dataset.stock || 0;

    document.getElementById("lblQty").innerText = "Qty (" + baseUnit + ")";
    row.querySelector(".qty").placeholder = baseUnit;
    
    if(altUnit && factor > 1) {
        document.getElementById("lblAlt").innerText = "Alt (" + altUnit + ")";
        row.querySelector(".alt_qty").placeholder = altUnit;
        row.querySelector(".alt_qty").disabled = false;
    } else {
        document.getElementById("lblAlt").innerText = "Alt";
        row.querySelector(".alt_qty").placeholder = "-";
        row.querySelector(".alt_qty").disabled = true;
    }

    currentFactor = factor;
    row.querySelector(".stock-display").value = stock;
    row.querySelector(".tax_per").value = taxRate;

    let priceSel = row.querySelector(".price-sel");
    priceSel.innerHTML = "";

    // Always add Sale Price
    priceSel.add(new Option(`Sale (${saleRate}/${baseUnit})`, saleRate));
    
    if (altUnit && factor > 1) {
        let altSale = (saleRate * factor).toFixed(2);
        priceSel.add(new Option(`Sale (${altSale}/${altUnit})`, saleRate)); 
    }
    if (['gms','g','ml'].includes(baseUnit.toLowerCase())) {
        let rate100 = (saleRate * 100).toFixed(2);
        priceSel.add(new Option(`Sale (${rate100}/100${baseUnit})`, saleRate));
    }

    // --- FIX: Only show MRP if it is greater than 0 ---
    if (mrpRate > 0) {
        priceSel.add(new Option(`MRP (${mrpRate}/${baseUnit})`, mrpRate));
    }

    // --- FIX: Only show Purchase Price if it is greater than 0 ---
    if (purRate > 0) {
        priceSel.add(new Option(`Purchase (${purRate}/${baseUnit})`, purRate));
    }

    row.querySelector(".rate").value = saleRate;
    calculateRow();
});

document.querySelector(".price-sel").addEventListener("change", function() {
    document.querySelector(".rate").value = this.value;
    calculateRow();
});

document.querySelector(".alt_qty").addEventListener("input", function() {
    let altVal = parseFloat(this.value) || 0;
    document.querySelector(".qty").value = (altVal * currentFactor); 
    calculateRow();
});

let inputs = document.querySelectorAll("#entryRow input");
inputs.forEach(input => input.addEventListener("input", calculateRow));

// --- ADD ITEM GRID ---
document.getElementById("addItem").addEventListener("click", function () {
    let row = document.getElementById("entryRow");
    let itemSel = row.querySelector(".itemSel");
    
    if (itemSel.value === "") { alert("Select Item"); return; }

    let id = itemSel.value;
    let name = itemSel.options[itemSel.selectedIndex].text;
    let batch = row.querySelector(".batch").value;
    let qty = row.querySelector(".qty").value;
    let alt = row.querySelector(".alt_qty").value;
    let free = row.querySelector(".free").value;
    let rate = row.querySelector(".rate").value;
    let dis = row.querySelector(".dis_per").value;
    let tax = row.querySelector(".tax_per").value;
    let taxAmt = row.querySelector(".tax_amt_hidden").value;
    let net = row.querySelector(".net_value").value;
    let basic = row.querySelector(".basic_amt").value; // Take derived basic

    let tr = `
        <tr>
            <td>
                ${name} <br><small class="text-muted">${batch}</small>
                <input type="hidden" name="item_id[]" value="${id}"> 
                <input type="hidden" name="batch_no[]" value="${batch}">
            </td>
            <td>${qty} <input type="hidden" name="qty[]" value="${qty}"></td>
            <td>${alt} <input type="hidden" name="alt_qty[]" value="${alt}"></td>
            <td>${rate} <input type="hidden" name="rate[]" value="${rate}"></td>
            <td>${basic}</td>
            <td>${dis}% <input type="hidden" name="dis_per[]" value="${dis}"></td>
            <td>
                ${tax}% <br><small class="text-muted">(${taxAmt})</small>
                <input type="hidden" name="tax_per[]" value="${tax}">
                <input type="hidden" name="free_qty[]" value="${free}">
            </td>
            <td class="row-net">${net}</td>
            <td><button type="button" class="btn btn-danger btn-sm remove-btn">X</button></td>
        </tr>
    `;
    document.getElementById("addedItems").innerHTML += tr;
    updateGrandTotal();
    
    itemSel.value = "";
    row.querySelector(".qty").value = "";
    row.querySelector(".alt_qty").value = "";
    row.querySelector(".batch").value = "";
    row.querySelector(".free").value = "0";
    row.querySelector(".rate").value = "";
    row.querySelector(".dis_per").value = "0";
    row.querySelector(".tax_per").value = "";
    row.querySelector(".basic_amt").value = "";
    row.querySelector(".net_value").value = "";
    row.querySelector(".price-sel").innerHTML = "";
});

document.addEventListener("click", function(e){
    if(e.target && e.target.classList.contains("remove-btn")){
        e.target.closest("tr").remove(); 
        updateGrandTotal(); 
    }
});

function updateGrandTotal() {
    let subtotal = 0;    
    document.querySelectorAll(".row-net").forEach(td => { 
        subtotal += parseFloat(td.innerText); 
    });

    document.getElementById("itemsSubtotal").value = subtotal.toFixed(2);

    let disPer   = parseFloat(document.getElementById("disPerAll").value) || 0;
    let disAmt   = parseFloat(document.getElementById("disAmtAll").value) || 0;
    let delivery = parseFloat(document.getElementById("deliveryCharges").value) || 0;
    let freight  = parseFloat(document.getElementById("freightCharges").value) || 0;

    let finalTotal = (subtotal - disAmt) + delivery + freight;

    document.getElementById("grandTotal").value = finalTotal.toFixed(2);
    calcChange();
}

document.getElementById("disPerAll").addEventListener("input", function() {
    let subtotal = parseFloat(document.getElementById("itemsSubtotal").value) || 0;
    let per = parseFloat(this.value) || 0;
    let amt = subtotal * (per / 100);
    document.getElementById("disAmtAll").value = amt.toFixed(2);
    updateGrandTotal();
});

document.getElementById("disAmtAll").addEventListener("input", function() {
    document.getElementById("disPerAll").value = ""; 
    updateGrandTotal();
});

document.getElementById("deliveryCharges").addEventListener("input", updateGrandTotal);
document.getElementById("freightCharges").addEventListener("input", updateGrandTotal);

document.getElementById("cashTendered").addEventListener("input", calcChange);
function calcChange() {
    let total = parseFloat(document.getElementById("grandTotal").value) || 0;
    let cash = parseFloat(document.getElementById("cashTendered").value) || 0;
    document.getElementById("changeAmt").value = (cash - total).toFixed(2);
}
</script>
<?php endif; ?>

</body>
</html>