<?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;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Edit Item</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f0f2f5; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .form-label { font-weight: 600; font-size: 0.9rem; color: #555; }
        .section-title { font-size: 1.1rem; font-weight: 700; color: #0d6efd; margin-bottom: 15px; border-bottom: 2px solid #e9ecef; padding-bottom: 8px; }
        .unit-preview { background: #e7f1ff; color: #0c63e4; padding: 10px; border-radius: 8px; font-weight: bold; font-size: 0.9rem; display: none; }
    </style>
</head>

<body>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            
            <form action="<?= BASE_URL ?>/public/?r=items/update" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?= $item['id'] ?>">
                <input type="hidden" name="old_img" value="<?= $item['img'] ?>">

                <div class="card">
                    <div class="card-header bg-white py-3 border-bottom-0">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0 text-dark fw-bold">✏️ Edit Product</h4>
                            <a href="<?= BASE_URL ?>/public/?r=items" class="btn btn-outline-secondary btn-sm">Cancel</a>
                        </div>
                    </div>

                    <div class="card-body p-4">

                        <h5 class="section-title">1. Basic Details</h5>
                        <div class="row g-3 mb-4">
                            <div class="col-md-6">
                                <label class="form-label">Item Name</label>
                                <input type="text" name="item_name" class="form-control" value="<?= $item['item_name'] ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Short Name / SKU</label>
                                <input type="text" name="short_name" class="form-control" value="<?= $item['short_name'] ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">HSN Code</label>
                                <input type="text" name="hsn_code" class="form-control" value="<?= $item['hsn_code'] ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Company / Brand</label>
                                <input type="text" name="company" class="form-control" value="<?= $item['company'] ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Item Group</label>
                                <input type="text" name="item_group" class="form-control" value="<?= $item['item_group'] ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">GST Tax Slab</label>
                                <select name="tax_slab" class="form-select">
                                    <?php 
                                    $taxes = ['0', '5', '12', '18', '28'];
                                    foreach($taxes as $t) {
                                        $sel = (strpos($item['tax_slab'], $t) !== false) ? 'selected' : '';
                                        echo "<option value='$t' $sel>$t% GST</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>

                        <h5 class="section-title">2. Unit & Conversion</h5>
                        <div class="row g-3 mb-2">
                            <div class="col-md-4">
                                <label class="form-label">Primary Unit</label>
                                <input type="text" name="primary_unit" id="primary_unit" class="form-control" value="<?= $item['primary_unit'] ?>" required oninput="updateUnitLogic()">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Alternate Unit</label>
                                <input type="text" name="alternate_unit" id="alternate_unit" class="form-control" value="<?= $item['alternate_unit'] ?>" oninput="updateUnitLogic()">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Conversion Factor</label>
                                <input type="number" step="any" name="conversion_factor" id="conversion_factor" class="form-control" value="<?= (float)$item['conversion_factor'] ?>" oninput="updateUnitLogic()">
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-12">
                                <div id="unitPreview" class="unit-preview text-center">
                                    ℹ️ 1 <span id="lbl_alt"></span> contains <b><span id="lbl_factor"></span></b> <span id="lbl_base"></span>
                                </div>
                            </div>
                        </div>

                        <h5 class="section-title">3. Pricing & Stock</h5>
                        <div class="row g-3 mb-4">
                            <div class="col-md-3">
                                <label class="form-label">Pricing Per?</label>
                                <select name="price_per" id="price_per_select" class="form-select"></select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Purchase Price</label>
                                <input type="number" step="0.01" name="purchase_price" class="form-control" value="<?= $item['purchase_price'] ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Sale Price</label>
                                <input type="number" step="0.01" name="sale_price" class="form-control" value="<?= $item['sale_price'] ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">MRP</label>
                                <input type="number" step="0.01" name="mrp" class="form-control" value="<?= $item['mrp'] ?>">
                            </div>
                        </div>

                        <div class="row g-3 mb-4 bg-light p-3 rounded">
                            <div class="col-md-6">
                                <label class="form-label">Opening Stock (In Base Unit)</label>
                                <input type="number" step="0.01" name="opening_qty_kg" class="form-control" value="<?= (float)$item['opening_qty_kg'] ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Update Image</label>
                                <input type="file" name="img" class="form-control">
                                <?php if(!empty($item['img'])): ?>
                                    <div class="mt-2 text-muted" style="font-size:0.8rem;">
                                        Current: <a href="uploads/<?= $item['img'] ?>" target="_blank"><?= $item['img'] ?></a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                    </div>
                    
                    <div class="card-footer bg-white text-end py-3">
                        <button type="submit" class="btn btn-primary btn-lg px-5 shadow-sm">
                            <i class="bi bi-check-circle"></i> Update Product
                        </button>
                    </div>
                </div>
            </form>
            
        </div>
    </div>
</div>

<script>
    const savedPricePer = "<?= $item['price_per'] ?>";

    function updateUnitLogic() {
        let base = document.getElementById("primary_unit").value || 'Unit';
        let alt  = document.getElementById("alternate_unit").value;
        let factor = document.getElementById("conversion_factor").value || 1;
        
        let preview = document.getElementById("unitPreview");
        let priceSelect = document.getElementById("price_per_select");

        document.getElementById("lbl_base").innerText = base;
        document.getElementById("lbl_alt").innerText = alt || base;
        document.getElementById("lbl_factor").innerText = factor;

        if(alt && alt !== base) {
            preview.style.display = "block";
            priceSelect.innerHTML = `<option value="${base}">Per ${base}</option><option value="${alt}">Per ${alt}</option>`;
        } else {
            preview.style.display = "none";
            priceSelect.innerHTML = `<option value="${base}">Per ${base}</option>`;
        }

        if (savedPricePer && (savedPricePer === base || savedPricePer === alt)) {
            priceSelect.value = savedPricePer;
        }
    }
    window.onload = updateUnitLogic;
</script>

</body>
</html>