<?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'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Add New Item</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <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; }
        
        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="py-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            
            <form action="<?= BASE_URL ?>/public/?r=items/save_item" method="POST" enctype="multipart/form-data" onsubmit="return convertPricesBeforeSubmit()">
                <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">📦 Add New Product</h4>
                            <a href="<?= BASE_URL ?>/public/?r=items" class="btn btn-outline-secondary btn-sm">Back to List</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 <span class="text-danger">*</span></label>
                                <input type="text" name="item_name" class="form-control" placeholder="e.g. Moong Dal" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Short Name / SKU</label>
                                <input type="text" name="short_name" class="form-control" placeholder="e.g. MD-500">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">HSN Code</label>
                                <input type="text" name="hsn_code" class="form-control" placeholder="e.g. 1905">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Company / Brand</label>
                                <input type="text" name="company" class="form-control" placeholder="e.g. Himalaya">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Item Group</label>
                                <input type="text" name="item_group" list="groupList" class="form-control" placeholder="Select or Type">
                                <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">
                                    <option value="0">0% (Nil Rated)</option>
                                    <option value="5">5% GST</option>
                                    <option value="12">12% GST</option>
                                    <option value="18">18% GST</option>
                                    <option value="28">28% 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 (Base) <span class="text-danger">*</span></label>
                                <input type="text" name="primary_unit" id="primary_unit" class="form-control" list="unitList" placeholder="e.g. gms" required oninput="updateUnitLogic()">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Alternate Unit (Optional)</label>
                                <input type="text" name="alternate_unit" id="alternate_unit" class="form-control" list="altUnitList" placeholder="e.g. Bag" 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="1" oninput="updateUnitLogic()">
                            </div>
                            
                            <datalist id="unitList"><option value="Pcs"><option value="gms"><option value="kg"><option value="ltr"><option value="ml"></datalist>
                            <datalist id="altUnitList"><option value="Bag"><option value="Box"><option value="Carton"><option value="Bundle"></datalist>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-12">
                                <div id="unitPreview" class="unit-preview text-center">
                                    ℹ️ 1 <span id="lbl_alt">Bag</span> contains <b><span id="lbl_factor">1</span></b> <span id="lbl_base">gms</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 Entering 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>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" step="0.01" name="purchase_price" id="p_price" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Sale Price</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" step="0.01" name="sale_price" id="s_price" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">MRP</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" step="0.01" name="mrp" id="m_price" class="form-control">
                                </div>
                            </div>
                        </div>

                        <h5 class="section-title d-flex justify-content-between align-items-center">
                            4. Additional Details
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="addCustomField()">
                                <i class="bi bi-plus-circle"></i> Add Field
                            </button>
                        </h5>

                        <div id="dynamic_fields_container" class="mb-4">
                            </div>

                        <datalist id="standard_fields">
                            <option value="Color">
                            <option value="Size">
                            <option value="IMEI">
                            <option value="Serial No">
                            <option value="Material">
                            <option value="Warranty">
                            <option value="Batch No">
                            <option value="Expiry Date">
                        </datalist>

                        <h5 class="section-title">5. Images & Inventory</h5>
                        <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" placeholder="e.g. 10000">
                                <small class="text-muted">Enter quantity in <span id="stock_hint">Primary Unit</span></small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Product Image</label>
                                <input type="file" name="img" class="form-control">
                            </div>
                        </div>

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

<template id="field_template">
    <div class="row g-2 mb-2 align-items-center field-row">
        <div class="col-5">
            <input type="text" name="custom_keys[]" list="standard_fields" class="form-control" placeholder="Label (e.g. Color)">
        </div>
        <div class="col-6">
            <input type="text" name="custom_values[]" class="form-control" placeholder="Value (e.g. Red)">
        </div>
        <div class="col-1">
            <button type="button" class="btn btn-outline-danger w-100" onclick="removeField(this)">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    </div>
</template>

<script>
    function addCustomField() {
        const container = document.getElementById('dynamic_fields_container');
        const template = document.getElementById('field_template');
        const clone = template.content.cloneNode(true);
        container.appendChild(clone);
    }

    function removeField(button) {
        button.closest('.field-row').remove();
    }

    // --- YOUR EXISTING UNIT LOGIC ---
    function updateUnitLogic() {
        let base = document.getElementById("primary_unit").value || 'Unit';
        let alt  = document.getElementById("alternate_unit").value || base; 
        let factor = parseFloat(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;
        document.getElementById("lbl_factor").innerText = factor;
        document.getElementById("stock_hint").innerText = base;

        preview.style.display = "block";

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

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

        if (alt && alt !== base && factor > 1) {
            options += `<option value="${factor}">Per 1 ${alt} (${factor} ${base})</option>`;
        }

        priceSelect.innerHTML = options;
    }
    
    document.addEventListener("DOMContentLoaded", function() {
        updateUnitLogic();
    });

    function convertPricesBeforeSubmit() {
        let divider = parseFloat(document.getElementById("price_per_select").value);
        if (divider === 1) return true;

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

        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;
    }
</script>

</body>
</html>