<?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 PURCHASE ------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_purchase'])) {

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

    $party_id      = $_POST['party'];
    $bill_no       = $_POST['bill_no'];
    $purchase_date = $_POST['purchase_date'];
    $payment_terms = $_POST['terms'];

    $items_id = $_POST['item_id'];
    $qty      = $_POST['qty'];
    $rate     = $_POST['rate'];
    $tax_per  = $_POST['tax_per'];

    $grand_total  = 0;
    $total_tax    = 0;
    $subtotal_all = 0;

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

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

    query("INSERT INTO purchases (business_id, party_id, bill_no, purchase_date, payment_terms, subtotal, total_tax, grand_total, created_at)
           VALUES (?,?,?,?,?,?,?,?, NOW())",
           [$business_id, $party_id, $bill_no, $purchase_date, $payment_terms, $subtotal_all, $total_tax, $grand_total]);

    $purchase_id = last_id();

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

        query("INSERT INTO purchase_items (purchase_id, item_id, qty, rate, amount, tax_per, tax_amt, net_value)
               VALUES (?,?,?,?,?,?,?,?)",
               [$purchase_id, $items_id[$i], $qty[$i], $rate[$i], $basic, $tax_per[$i], $t_amt, $net]);

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

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

$parties = all_rows("SELECT id, name FROM accounts WHERE business_id = ? AND group_name = 'SUPPLIERS' ORDER BY name", [$business_id]);
$items = all_rows("SELECT id, item_name, primary_unit, purchase_price, opening_qty_kg FROM new_items WHERE business_id = ? ORDER BY item_name", [$business_id]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Purchase Entry</title>
    <style>
    body {
        /* Set the image */
        background-image: url("<?php echo BASE_URL; ?>/public/grocery.png");
        background-size: cover;
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-position: center;
        
        /* Fallback color if image fails */
        background-color: #f4f6f9; 
        
        /* General Font Settings */
        font-size: 14px;
    }

    /* Optional: Add a semi-transparent white overlay to make text readable */
    .container-fluid {
        background: rgba(255, 255, 255, 0.85); /* 85% opacity white */
        min-height: 100vh;
        padding-top: 20px;
    }

    .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: #198754; color: white; font-weight: 500; font-size: 13px; }
    .table td { vertical-align: middle; padding: 5px; }
    .bg-light-green { background-color: #e8f5e9; }
    label { font-weight: 600; font-size: 12px; margin-bottom: 2px; }
</style>
</head>
<body>

<div class="container-fluid mt-3">
    <h4 class="mb-3 text-success">PURCHASE ENTRY</h4>

    <form method="post" id="purchaseForm">
        <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>Supplier 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 Supplier
                        </a>
                    </div>
                    <select name="party" class="form-select" required>
                        <option value="">Select Supplier</option>
                        <?php foreach ($parties as $p): ?>
                            <option value="<?= $p['id'] ?>"><?= $p['name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Purchase Date</label>
                    <input type="date" name="purchase_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="col-md-3">
                    <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-3">
                    <label>Invoice No.</label>
                    <input type="text" name="bill_no" class="form-control" placeholder="Invoice #">
                </div>
            </div>
        </div>

        <div class="card mb-3 bg-light-green">
            <div class="row g-1 align-items-end" id="entryRow">
                <div class="col-md-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <label>Item Name</label>
                        <a href="<?= BASE_URL ?>/public/index.php?r=add_items" target="_blank" style="font-size: 11px; text-decoration: none; color: #198754;">
                            + Add New Item
                        </a>
                    </div>
                    <select class="form-select itemSel">
                        <option value="">Select Item</option>
                        <?php foreach ($items as $i): ?>
                        <option value="<?= $i['id'] ?>" 
                                data-rate="<?= $i['purchase_price'] ?>" 
                                data-unit="<?= $i['primary_unit'] ?>"> <?= $i['item_name'] ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label>Qty</label>
                    <input type="number" step="any" class="form-control qty" value="1">
                </div>
                <div class="col-md-2">
                    <label>Rate</label>
                    <input type="number" step="any" class="form-control rate">
                </div>
                <div class="col-md-2">
                    <label>Tax %</label>
                    <input type="number" step="any" class="form-control tax_per" value="0">
                </div>
                <div class="col-md-2">
                    <label>Net Value</label>
                    <input type="text" class="form-control net_value" readonly>
                </div>
                <div class="col-md-1">
                     <button type="button" class="btn btn-success w-100" id="addItem">Add</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>Qty</th>
                        <th>Rate</th>
                        <th>Tax%</th>
                        <th>Net Value</th>
                        <th>Act</th>
                    </tr>
                </thead>
                <tbody id="addedItems"></tbody>
            </table>
        </div>

        <div class="card bg-success text-white p-3">
            <div class="row g-2 align-items-center">
                <div class="col-md-10 text-end">
                    <label>Grand Total</label>
                </div>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="grandTotal" readonly>
                </div>
            </div>
            <div class="text-end mt-3">
                <button type="submit" name="save_purchase" class="btn btn-warning fw-bold px-5">SAVE PURCHASE</button>
            </div>
        </div>
    </form>
</div>

<script>
function calculateRow() {
    let row = document.getElementById("entryRow");
    let qty = parseFloat(row.querySelector(".qty").value) || 0;
    let rate = parseFloat(row.querySelector(".rate").value) || 0;
    let taxPer = parseFloat(row.querySelector(".tax_per").value) || 0;

    let basic = qty * rate;
    let taxAmt = basic * (taxPer / 100);
    let netValue = basic + taxAmt;

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

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

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

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 qty = row.querySelector(".qty").value;
    let rate = row.querySelector(".rate").value;
    let tax = row.querySelector(".tax_per").value;
    let net = row.querySelector(".net_value").value;

    let tr = `
        <tr>
            <td>${name} <input type="hidden" name="item_id[]" value="${id}"></td>
            <td>${qty} <input type="hidden" name="qty[]" value="${qty}"></td>
            <td>${rate} <input type="hidden" name="rate[]" value="${rate}"></td>
            <td>${tax}% <input type="hidden" name="tax_per[]" value="${tax}"></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").insertAdjacentHTML('beforeend', tr);
    updateGrandTotal();
    
    itemSel.value = "";
    row.querySelector(".qty").value = "1";
    row.querySelector(".rate").value = "";
    row.querySelector(".net_value").value = "";
});

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

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

</body>
</html>