<?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'];

/* =====================================================
   SAVE SALE LOGIC
===================================================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_sale'])) {
    
    // 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;
    }

    // 2. Capture Header
    $invoice_type_name = $_POST['invoice_type'] ?? 'GST Invoice';
    
    // FETCH SETTINGS FOR SELECTED INVOICE TYPE TO KNOW IF INCLUSIVE/EXCLUSIVE
    $type_settings = one(
        "SELECT tax_type FROM invoice_types WHERE type_name = ? AND business_id = ?", 
        [$invoice_type_name, $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);
    
    // 3. Capture Charges
    $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);

    // 4. Capture Arrays
    $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;

    // 5. Calculate Totals (SERVER SIDE LOGIC)
    foreach ($items_id as $i => $id) {
        $q = (float)($qty[$i] ?? 0);
        $r = (float)($rate[$i] ?? 0); // User entered rate (e.g., 25000)
        $d = (float)($dis_per[$i] ?? 0);
        $t = (float)($tax_per[$i] ?? 0);

        // --- MATH LOGIC ---
        if ($is_inclusive) {
            // SCENARIO: Rate is 25,000 Inclusive.
            // 1. Calculate Discount on the Inclusive Rate
            $gross_inclusive = $q * $r; 
            $d_amt = $gross_inclusive * ($d / 100);
            
            // 2. Net Inclusive Amount
            $net_inclusive = $gross_inclusive - $d_amt;
            
            // 3. Back Calculate Tax
            // Formula: Value / (1 + Tax%/100)
            $taxable = $net_inclusive / (1 + ($t / 100));
            
            // 4. Tax Amount
            $t_amt = $net_inclusive - $taxable;
            
            // 5. Basic (for database logic)
            $basic = $gross_inclusive; // In inclusive, basic is often stored as the entered rate, or recalculated. 
            // Here we store $taxable as the 'true' basic for consistency in accounting, 
            // OR we store $basic as derived. Let's stick to standard sales columns:
            $basic = $taxable; // The 'Real' basic price before tax.

        } else {
            // SCENARIO: Exclusive (Standard)
            $basic   = $q * $r;
            $d_amt   = $basic * ($d / 100);
            $taxable = $basic - $d_amt;
            $t_amt   = $taxable * ($t / 100);
        }

        $net = $taxable + $t_amt;

        $subtotal         += $basic; // This sums up the Taxable Value
        $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;

    // 6. Insert Header
    query(
        "INSERT INTO sales 
        (business_id, party_id, bill_no, , 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_name, $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();

    // 7. Insert Items
    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);

        // --- REPEAT MATH FOR INSERT ---
        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;
             // For storage: usually strictly 'amount' in DB is basic. 
             $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
            (sale_id, item_id, batch_no, qty, alt_qty, free_qty, rate, amount,
             discount_per, discount_amt, tax_per, tax_amt, net_value)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
            // Note: 'rate' stored is the one user entered. 'amount' is the calculated basic total.
            [$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['last_sale_id'] = $sale_id;
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

/* =====================================================
   DATA FETCHING
===================================================== */
$last_sale_id = $_SESSION['last_sale_id'] ?? 0;
$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]
);

// UPDATED: Fetch 'tax_type' (inclusive/exclusive)
$invoice_types = all_rows("SELECT type_name, tax_type FROM invoice_types WHERE business_id = ?", [$business_id]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Sale Entry</title>
    <style>
        body { 
            background-image: url("<?= BASE_URL ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            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: #0dcaf0; color: white; font-weight: 500; font-size: 13px; }
        .table td { vertical-align: middle; padding: 5px; background: rgba(255,255,255,0.8); }
        .bg-light-blue { background-color: #e0f7fa !important; }
        .footer-totals input { font-weight: bold; text-align: right; }
        label { font-weight: 600; font-size: 12px; margin-bottom: 2px; }
        .stock-display { background-color: #ffecec !important; color: #d63384; font-weight: bold; border-color: #f5c2c7; }
        .price-group { display: flex; flex-direction: column; gap: 2px; }
        .price-sel { font-size: 11px; color: #0d6efd; border-color: #b6d4fe; background: #f8fbff; }
        .charges-section { border-bottom: 1px solid #ffffff40; padding-bottom: 10px; margin-bottom: 10px; }
        .charges-section label { color: #f8f9fa; }
    </style>
</head>
<body>

<div class="container-fluid mt-3">

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

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="text-primary m-0" style="text-shadow: 1px 1px 2px white;">SALE ENTRY</h4>
            
            <div class="input-group" style="width: auto;">
                <span class="input-group-text bg-white text-primary fw-bold">InvoiceType</span>
                <select name="invoice_type" id="invoiceTypeSelect" class="form-select text-primary fw-bold" style="width: 200px; border-color: #0d6efd;">
                    <?php if(empty($invoice_types)): ?>
                        <option value="GST Invoice" data-tax-type="exclusive">GST Invoice</option>
                    <?php else: ?>
                        <?php foreach($invoice_types as $type): ?>
                            <option value="<?= $type['type_name'] ?>" 
                                    data-tax-type="<?= $type['tax_type'] // inclusive or exclusive ?>">
                                <?= $type['type_name'] ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </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: #198754;">
                            + Add New Party
                        </a>
                    </div>
                    
                    <select name="party" class="form-select" required>
                        <option value="">Select Party</option>
                        <?php foreach ($parties as $p): ?>
                            <option value="<?= $p['id'] ?>"><?= $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="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="col-md-2">
                    <label>Terms</label>
                    <select name="terms" class="form-select">
                        <option value="Credit">Credit</option>
                        <option value="Cash">Cash</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>No. (Bill #)</label>
                    <input type="text" name="bill_no" class="form-control" placeholder="Auto/Manual">
                </div>
                <div class="col-md-3">
                    <label>Due Date</label>
                    <input type="date" name="due_date" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
            </div>
        </div>

        <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): ?>
                        <?php $tax_val = (float)($i['tax_slab'] ?? 0); ?>
                        <option value="<?= $i['id'] ?>"
                            data-rate="<?= $i['sale_price'] ?>"
                            data-purchase="<?= $i['purchase_price'] ?>"
                            data-mrp="<?= $i['mrp'] ?>"
                            data-unit="<?= $i['primary_unit'] ?>"
                            data-alt-unit="<?= $i['alternate_unit'] ?? '' ?>"
                            data-stock="<?= $i['opening_qty_kg'] ?>"
                            data-factor="<?= $i['conversion_factor'] ?? 1 ?>"
                            data-tax="<?= $tax_val ?>">
                            <?= $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 placeholder="0.00">
                </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/Gross</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 placeholder="0">
                </div>

                <div class="col-md-1"> 
                    <label>Net Value</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>

        <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>
                        <th>Act</th>
                    </tr>
                </thead>
                <tbody id="addedItems"></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 (Subtotal)</label>
                    <input type="text" class="form-control" id="itemsSubtotal" readonly>
                </div>
                <div class="col-md-2">
                    <label>Overall Disc (%)</label>
                    <input type="number" step="0.01" name="dis_per_all" class="form-control" id="disPerAll" placeholder="%">
                </div>
                <div class="col-md-2">
                    <label>Less: Discount (Amt)</label>
                    <input type="number" step="0.01" name="overall_discount" class="form-control text-danger fw-bold" id="disAmtAll" placeholder="0.00">
                </div>
                <div class="col-md-2">
                    <label>Add: Delivery</label>
                    <input type="number" step="0.01" name="delivery_charges" class="form-control text-success fw-bold" id="deliveryCharges" placeholder="0.00">
                </div>
                <div class="col-md-3">
                    <label>Add: Freight</label>
                    <input type="number" step="0.01" name="freight_charges" class="form-control text-success fw-bold" id="freightCharges" placeholder="0.00">
                </div>
            </div>

            <div class="row g-2 align-items-center">
                <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;">
                </div>
                <div class="col-md-2 text-end">
                    <label>Cash Tendered</label>
                    <input type="number" name="cash_tendered" class="form-control" id="cashTendered" value="0">
                </div>
                <div class="col-md-2 text-end">
                    <label>Change</label>
                    <input type="text" name="change_amt" class="form-control" id="changeAmt" readonly>
                </div>
            </div>

            <div class="text-end mt-3">
                <button type="submit" name="save_sale" class="btn btn-warning fw-bold px-5">SAVE SALE</button>
            </div>
        </div>

    </form>
</div>

<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 ---
        // 1. Gross Inclusive Amount
        let grossInclusive = qty * rate; // e.g. 25,000 * 1

        // 2. Discount Amount (Usually applied on the inclusive price in retail)
        let disAmt = grossInclusive * (disPer / 100);

        // 3. Net Inclusive (after discount)
        let netInclusive = grossInclusive - disAmt;

        // 4. Back-Calculate Taxable Value
        // Formula: NetInclusive / (1 + Tax%/100)
        let taxableValue = netInclusive / (1 + (taxPer / 100));

        // 5. Calculate Tax Amount
        taxAmt = netInclusive - taxableValue;

        // 6. Set values
        basic = taxableValue; // For display purpose, basic is the pre-tax amount
        netValue = netInclusive; // Net value is what the customer pays (25k)
        
        // Show Gross in the "Basic" box so user sees their input math? 
        // Or show the derived taxable? Usually showing derived taxable is better for accounting visibility.
        // Let's show Derived Taxable (Basic) to avoid confusion about where tax went.
        row.querySelector(".basic_amt").value = taxableValue.toFixed(2);

    } else {
        // --- EXCLUSIVE CALCULATION (Standard) ---
        basic = qty * rate; // e.g. 20,000
        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() {
    // Re-calculate the current entry row
    calculateRow();
    
    // Optional: You might want to warn user that existing added items 
    // in the table won't update automatically unless you re-add them.
});

// --- 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 = "";

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

    priceSel.add(new Option(`MRP (${mrpRate})`, mrpRate));
    priceSel.add(new Option(`Purchase (${purRate})`, 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;
    
    // Note: The 'row-net' in the table contains the Final Net Value (Inclusive of tax).
    // The 'Basic' column in the table contains the Taxable Value.
    // For Grand Total, we just sum up the Net Values.
    
    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>

</body>
</html>