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

// --- GET ID ---
if (!isset($_GET['id'])) {
    echo "Invalid Request"; exit;
}
$id = $_GET['id'];

// --- FIX: Use all_rows() instead of unique_row() ---
// We fetch all matching rows (should be just 1) and grab the first one [0]
$rows = all_rows(
    "SELECT * FROM new_items WHERE id = ? AND business_id = ?", 
    [$id, $business_id]
);

$item = $rows[0] ?? null;

if (!$item) {
    echo "Item not found or access denied."; 
    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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    
    <style>
        body {
            background-image: url("<?php echo BASE_URL; ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
        }
        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; }
        
        body {
            background-image: url("<?php echo BASE_URL; ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
        }
        .container{
            background: rgba(255, 255, 255, 0.88);
            border-radius: 16px;
            padding: 1rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
            backdrop-filter: blur(2px);
        }
    </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" onsubmit="return convertPricesBeforeSubmit()">
                <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" list="groupList" class="form-control" value="<?= $item['item_group'] ?>">
                                <datalist id="groupList">
                                    <option value="Grocery">
                                    <option value="Electronics">
                                    <option value="Garments">
                                </datalist>
                            </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">I am Editing Price for:</label>
                                <select name="price_per" id="price_per_select" class="form-select bg-light border-primary">
                                    <option value="1">Per 1 Unit</option>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Purchase Price</label>
                                <input type="number" step="0.01" name="purchase_price" id="p_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" id="s_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" id="m_price" 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>
    function updateUnitLogic() {
        let base = document.getElementById("primary_unit").value || 'Unit';
        let alt  = document.getElementById("alternate_unit").value;
        let factor = parseFloat(document.getElementById("conversion_factor").value) || 1;
        
        let preview = document.getElementById("unitPreview");
        let priceSelect = document.getElementById("price_per_select");

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

        // --- SMART DROPDOWN LOGIC ---
        let options = `<option value="1">Per 1 ${base}</option>`;

        // 1. If unit is small (grams/ml), add "Per 100" option
        let smallUnits = ['gms', 'g', 'ml', 'gram', 'grams'];
        if (smallUnits.includes(base.toLowerCase())) {
            options += `<option value="100">Per 100 ${base}</option>`;
        }

        // 2. If Alternate Unit exists, add "Per Alt Unit" option
        if (alt && alt !== base && factor > 1) {
            preview.style.display = "block";
            options += `<option value="${factor}">Per 1 ${alt} (${factor} ${base})</option>`;
        } else {
            preview.style.display = "none";
        }

        priceSelect.innerHTML = options;
    }

    // --- CONVERT BEFORE SUBMIT ---
    function convertPricesBeforeSubmit() {
        // Get the Divider (1, 100, or 50000)
        let divider = parseFloat(document.getElementById("price_per_select").value);

        if (divider === 1) return true; // No conversion needed

        // Select Inputs
        let pPrice = document.getElementById("p_price");
        let sPrice = document.getElementById("s_price");
        let mPrice = document.getElementById("m_price");

        // Logic: You enter 20 for 100g -> We save 0.20 for 1g
        if(pPrice.value) pPrice.value = (parseFloat(pPrice.value) / divider).toFixed(4);
        if(sPrice.value) sPrice.value = (parseFloat(sPrice.value) / divider).toFixed(4);
        if(mPrice.value) mPrice.value = (parseFloat(mPrice.value) / divider).toFixed(4);

        return true;
    }

    // Initialize on page load to set correct labels
    window.onload = updateUnitLogic;
</script>

</body>
</html>