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

// Require authentication
requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}
// ------------------------ SAVE SALE ------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_sale'])) {

    // 1. Validation: Prevent crash if no items added
    if (!isset($_POST['item_id']) || !is_array($_POST['item_id'])) {
        echo "<script>alert('Please add at least one item.'); window.history.back();</script>";
        exit;
    }

    // Header Details
    $party_id   = $_POST['party'];
    $bill_no    = $_POST['bill_no'];
    $sale_date  = $_POST['sale_date']; 
    $due_date   = $_POST['due_date'];
    $terms      = $_POST['terms'];     

    // Footer Details
    $cash_tendered = $_POST['cash_tendered'] ?? 0; 
    $change_amt    = $_POST['change_amt'] ?? 0;    
    
    // 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'];  
    
    // Calculate Global Totals
    $grand_total = 0;
    $total_tax   = 0;
    $total_dis   = 0;
    $subtotal_all = 0; // Missing in your code

    for ($i = 0; $i < count($items_id); $i++) {
        $basic   = $qty[$i] * $rate[$i];
        $d_amt   = $basic * ($dis_per[$i] / 100);
        $taxable = $basic - $d_amt;
        $t_amt   = $taxable * ($tax_per[$i] / 100);
        $net     = $taxable + $t_amt;

        $subtotal_all += $basic;
        $grand_total  += $net;
        $total_tax    += $t_amt;
        $total_dis    += $d_amt;
    }

    // INSERT INTO SALES
    // Fixed: Removed duplicate 'created_at'. Added 'subtotal', 'cgst', 'sgst' (split tax for DB structure)
    // INSERT INTO SALES
    $half_tax = $total_tax / 2; 
    
    // CHANGED: Added 'business_id' to the columns and the values (?)
    query("INSERT INTO sales (business_id, party_id, bill_no, sale_date, due_date, payment_terms, subtotal, total_discount, total_tax, cgst, sgst, grand_total, cash_tendered, change_amount, created_at)
           VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?, NOW())",
           [
               $business_id,  // <--- ADDED THIS (This was missing in your code!)
               $party_id, 
               $bill_no, 
               $sale_date, 
               $due_date, 
               $terms, 
               $subtotal_all, 
               $total_dis, 
               $total_tax, 
               $half_tax, 
               $half_tax, 
               $grand_total, 
               $cash_tendered, 
               $change_amt
           ]);

    $sale_id = last_id();
    // INSERT ITEMS & UPDATE STOCK
    for ($i = 0; $i < count($items_id); $i++) {
        
        $basic = $qty[$i] * $rate[$i];
        $d_amt = $basic * ($dis_per[$i] / 100);
        $t_amt = ($basic - $d_amt) * ($tax_per[$i] / 100);
        $net   = ($basic - $d_amt) + $t_amt;

        // Fixed: Added 'amount' column (Basic Amount)
        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 (?,?,?,?,?,?,?,?,?,?,?,?,?)",
               [$sale_id, $items_id[$i], $batch[$i], $qty[$i], $alt_qty[$i], $free[$i], $rate[$i], $basic, $dis_per[$i], $d_amt, $tax_per[$i], $t_amt, $net]);

        // Update Stock
        $total_qty_out = $qty[$i] + $free[$i];
        query("UPDATE new_items SET opening_qty_kg = opening_qty_kg - ? WHERE id = ?",
               [$total_qty_out, $items_id[$i]]);
    }

    echo "<script>alert('Sale Saved Successfully!'); window.location.href=window.location.href;</script>";
}

$business_id = $current_business['business_id'];
$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, sale_price, mrp, opening_qty_kg FROM new_items WHERE business_id = ? ORDER BY item_name", [$business_id]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Sale Entry</title>
    <style>
        body { background: #f4f6f9; font-size: 14px; }
        .card { 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; }
        .bg-light-blue { background-color: #e0f7fa; }
        .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; }
    </style>
</head>
<body>

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

    <h4 class="mb-3 text-primary">SALE ENTRY</h4>

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

        <div class="card mb-3">
            <div class="row g-2">
                <div class="col-md-3">
                    <label>Party Name</label>
                    <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): ?>
                        <option value="<?= $i['id'] ?>" 
                                data-rate="<?= $i['sale_price'] ?>" 
                                data-unit="<?= $i['primary_unit'] ?>"
                                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 placeholder="0.00">
                </div>
                
                <div class="col-md-1">
                    <label>Batch</label>
                    <input type="text" class="form-control batch" placeholder="Batch">
                </div>

                <div class="col-md-1">
                    <label>Qty</label>
                    <input type="number" class="form-control qty" value="1">
                </div>
                
                <div class="col-md-1">
                    <label>Alt</label>
                    <input type="number" class="form-control alt_qty" placeholder="0">
                </div>

                <div class="col-md-1">
                    <label>Free</label>
                    <input type="number" class="form-control free" value="0">
                </div>

                <div class="col-md-1">
                    <label>Price</label>
                    <input type="number" class="form-control rate">
                </div>

                <div class="col-md-1">
                    <label>Basic</label>
                    <input type="text" class="form-control basic_amt" readonly>
                </div>

                <div class="col-md-1">
                    <label>Dis %</label>
                    <input type="number" class="form-control dis_per" value="0">
                </div>

                <div class="col-md-1">
                    <label>Tax %</label>
                    <input type="number" class="form-control tax_per" value="0">
                </div>

                <div class="col-md-1"> <label>Net Value</label>
                    <div class="input-group">
                        <input type="text" class="form-control net_value" readonly>
                    </div>
                </div>

                <div class="col-12 mt-2 text-end">
                     <button type="button" class="btn btn-success px-4" id="addItem">Add Item +</button>
                </div>

            </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>Batch</th>
                        <th>Qty</th>
                        <th>Alt</th>
                        <th>Free</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">
                <div class="col-md-6"></div> 
                <div class="col-md-2 text-end">
                    <label>Net Bill Amt</label>
                    <input type="text" class="form-control" id="grandTotal" readonly>
                </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>
// --- CALCULATIONS LOGIC ---
function calculateRow() {
    let row = document.getElementById("entryRow");
    
    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;

    let basic = qty * rate;
    let disAmt = basic * (disPer / 100);
    let taxable = basic - disAmt;
    let taxAmt = taxable * (taxPer / 100);
    let netValue = taxable + taxAmt;

    row.querySelector(".basic_amt").value = basic.toFixed(2);
    row.querySelector(".net_value").value = netValue.toFixed(2);
}

// Event Listeners for Input Changes
let inputs = document.querySelectorAll("#entryRow input");
inputs.forEach(input => {
    input.addEventListener("input", calculateRow);
});

// Item Selection Change
document.querySelector(".itemSel").addEventListener("change", function () {
    let op = this.options[this.selectedIndex];
    if(this.value === "") return;
    let row = document.getElementById("entryRow");
    row.querySelector(".rate").value = op.dataset.rate;
    row.querySelector(".stock-display").value = op.dataset.stock; 
    calculateRow();
});

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

    // Get Values
    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 net = row.querySelector(".net_value").value;
    let basic = (qty * rate).toFixed(2);

    // FIXED: Hidden inputs are now INSIDE the table row. 
    // This allows them to be deleted when the row is deleted.
    let tr = `
        <tr>
            <td>
                ${name}
                <input type="hidden" name="item_id[]" value="${id}">
                <input type="hidden" name="batch_no[]" value="${batch}">
            </td>
            <td>${batch}</td>
            <td>
                ${qty}
                <input type="hidden" name="qty[]" value="${qty}">
            </td>
            <td>
                ${alt}
                <input type="hidden" name="alt_qty[]" value="${alt}">
            </td>
            <td>
                ${free}
                <input type="hidden" name="free_qty[]" value="${free}">
            </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}%
                <input type="hidden" name="tax_per[]" value="${tax}">
            </td>
            <td class="row-net">
                ${net}
                <input type="hidden" name="row_net_value[]" value="${net}">
            </td>
            <td><button type="button" class="btn btn-danger btn-sm remove-btn">X</button></td>
        </tr>
    `;
    document.getElementById("addedItems").innerHTML += tr;

    updateGrandTotal();
    
    // Reset Form
    itemSel.value = "";
    row.querySelector(".stock-display").value = ""; 
    row.querySelector(".qty").value = "1";
    row.querySelector(".rate").value = "";
    row.querySelector(".net_value").value = "";
    row.querySelector(".basic_amt").value = "";
    row.querySelector(".batch").value = "";
});

// --- REMOVE ITEM ---
document.addEventListener("click", function(e){
    if(e.target && e.target.classList.contains("remove-btn")){
        e.target.closest("tr").remove(); // This now removes the hidden inputs too!
        updateGrandTotal(); 
    }
});

// --- TOTALS CALCULATION ---
function updateGrandTotal() {
    let total = 0;
    document.querySelectorAll(".row-net").forEach(td => {
        total += parseFloat(td.innerText);
    });
    document.getElementById("grandTotal").value = total.toFixed(2);
    calcChange();
}

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>