<?php
include 'db.php';
include 'auth.php';
require_right('Edit Items');

$id = (int)$_GET['id'];
$item = $conn->query("SELECT * FROM items WHERE id = $id")->fetch_assoc();
if (!$item) {
    die("Item not found.");
}

$categories = $conn->query("SELECT * FROM categories");
$sub_categories = $conn->query("SELECT * FROM sub_categories WHERE category_id = {$item['category_id']}");
$tax_rates = $conn->query("SELECT * FROM tax_rates");

// Grouped UOMs
$uom_groups = [];
$uoms = $conn->query("SELECT uoms.*, uom_groups.name AS group_name FROM uoms
                      JOIN uom_groups ON uoms.group_id = uom_groups.id
                      ORDER BY uom_groups.id, uoms.name");
foreach ($uoms as $uom) {
    $uom_groups[$uom['group_name']][] = $uom;
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_code = trim($_POST['item_code']);
    $sku_number = trim($_POST['sku_number']);
    $name = trim($_POST['name']);
    $category_id = (int)$_POST['category_id'];
    $sub_category_id = (int)$_POST['sub_category_id'];
    $retail_price = (float)$_POST['retail_price'];
    $cost_price = (float)$_POST['cost_price'];
    $reorder_quantity = (int)$_POST['reorder_quantity'];
    $reorder_level = (int)$_POST['reorder_level'];
    $tax_type = $_POST['tax_type'];
    $tax_rate_id = !empty($_POST['tax_rate_id']) ? (int)$_POST['tax_rate_id'] : NULL;
    $item_type = $_POST['item_type'];
    $bulk_qty = $item_type === 'bulk' ? (int)$_POST['bulk_qty'] : NULL;
    $bulk_price = $item_type === 'bulk' ? (float)$_POST['bulk_price'] : NULL;
    $pkg_qty = $item_type === 'bulk' ? (int)$_POST['pkg_qty'] : NULL;
    $uom_id = $item_type === 'bulk' ? (int)$_POST['uom_id'] : NULL;
    $item_role = $_POST['item_role'];

    if (!$item_code || !$sku_number || !$name || !$retail_price || $cost_price === '' || !$tax_type || !$item_type || !$item_role) {
        $errors[] = "Please fill all required fields.";
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE items SET 
            item_code = ?, sku_number = ?, name = ?, category_id = ?, sub_category_id = ?, 
            retail_price = ?, cost_price = ?, reorder_quantity = ?, reorder_level = ?, 
            tax_type = ?, tax_rate_id = ?, item_type = ?, bulk_qty = ?, bulk_price = ?, pkg_qty = ?, uom_id = ?, item_role = ?
            WHERE id = ?");
        $stmt->bind_param("sssiddddisisidiis",
            $item_code, $sku_number, $name, $category_id, $sub_category_id,
            $retail_price, $cost_price, $reorder_quantity, $reorder_level,
            $tax_type, $tax_rate_id, $item_type, $bulk_qty, $bulk_price, $pkg_qty, $uom_id, $item_role, $id
        );
        $stmt->execute();
        $success = true;

        // Refresh data
        $item = $conn->query("SELECT * FROM items WHERE id = $id")->fetch_assoc();
        $sub_categories = $conn->query("SELECT * FROM sub_categories WHERE category_id = {$item['category_id']}");
    }
}

include 'layout.php';
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header"><div class="page-title"><h4>Edit Item</h4></div></div>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger"><ul><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul></div>
        <?php elseif ($success): ?>
            <div class="alert alert-success">Item updated successfully!</div>
        <?php endif; ?>

        <form method="POST" id="editItemForm">
            <input type="hidden" name="id" value="<?= $item['id'] ?>">
            <input type="text" name="item_code" value="<?= htmlspecialchars($item['item_code']) ?>" class="form-control mb-3" required>
            <input type="text" name="sku_number" value="<?= htmlspecialchars($item['sku_number']) ?>" class="form-control mb-3" required>
            <input type="text" name="name" value="<?= htmlspecialchars($item['name']) ?>" class="form-control mb-3" required>

            <select name="category_id" id="category_id" class="form-control mb-3" required>
                <option value="">Select Category</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= $item['category_id'] == $cat['id'] ? 'selected' : '' ?>><?= $cat['name'] ?></option>
                <?php endforeach; ?>
            </select>

            <select name="sub_category_id" id="sub_category_id" class="form-control mb-3">
                <option value="">Select Sub Category</option>
                <?php foreach ($sub_categories as $sub): ?>
                    <option value="<?= $sub['id'] ?>" <?= $item['sub_category_id'] == $sub['id'] ? 'selected' : '' ?>><?= $sub['name'] ?></option>
                <?php endforeach; ?>
            </select>

            <input type="number" step="0.01" name="retail_price" value="<?= $item['retail_price'] ?>" class="form-control mb-3" required>
            <input type="number" step="0.01" name="cost_price" value="<?= $item['cost_price'] ?>" class="form-control mb-3" required>
            <input type="number" name="reorder_quantity" value="<?= $item['reorder_quantity'] ?>" class="form-control mb-3">
            <input type="number" name="reorder_level" value="<?= $item['reorder_level'] ?>" class="form-control mb-3">

            <select name="tax_type" class="form-control mb-3" required>
                <option value="">Select Tax Type</option>
                <?php foreach (["included", "excluded", "nil"] as $type): ?>
                    <option value="<?= $type ?>" <?= $item['tax_type'] == $type ? 'selected' : '' ?>><?= ucfirst($type) ?></option>
                <?php endforeach; ?>
            </select>

            <select name="tax_rate_id" class="form-control mb-3">
                <option value="">Select Tax Rate</option>
                <?php foreach ($tax_rates as $rate): ?>
                    <option value="<?= $rate['id'] ?>" <?= $item['tax_rate_id'] == $rate['id'] ? 'selected' : '' ?>><?= $rate['name'] ?> (<?= $rate['rate'] ?>%)</option>
                <?php endforeach; ?>
            </select>

            <select name="item_type" id="item_type" class="form-control mb-3" required>
                <option value="loose" <?= $item['item_type'] == 'loose' ? 'selected' : '' ?>>Loose</option>
                <option value="bulk" <?= $item['item_type'] == 'bulk' ? 'selected' : '' ?>>Bulk</option>
            </select>

            <select name="item_role" class="form-control mb-3" required>
                <option value="">Select Item Role</option>
                <option value="stock" <?= $item['item_role'] == 'stock' ? 'selected' : '' ?>>Stock</option>
                <option value="material" <?= $item['item_role'] == 'material' ? 'selected' : '' ?>>Material</option>
                <option value="non_stock" <?= $item['item_role'] == 'non_stock' ? 'selected' : '' ?>>Non Stock</option>
            </select>

            <div id="bulkFields" style="<?= $item['item_type'] == 'bulk' ? 'display:block' : 'display:none' ?>;">
                <input type="number" name="bulk_qty" value="<?= $item['bulk_qty'] ?>" class="form-control mb-3" placeholder="Bulk Quantity">
                <input type="number" step="0.01" name="bulk_price" value="<?= $item['bulk_price'] ?>" class="form-control mb-3" placeholder="Bulk Price">
                <input type="number" name="pkg_qty" value="<?= $item['pkg_qty'] ?>" class="form-control mb-3" placeholder="Package Quantity">

                <div class="mb-3">
                    <label>Unit of Measurement (UOM) <span class="text-danger">*</span></label>
                    <select name="uom_id" class="form-control" required>
                        <option value="">Select Unit of Measurement</option>
                        <?php foreach ($uom_groups as $group => $units): ?>
                            <optgroup label="<?= htmlspecialchars($group) ?>">
                                <?php foreach ($units as $uom): ?>
                                    <option value="<?= $uom['id'] ?>" <?= $item['uom_id'] == $uom['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($uom['name']) ?> (<?= htmlspecialchars($uom['symbol']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">Choose the unit for this item (e.g. Piece, Kilogram, Liter).</small>
                </div>
            </div>

            <div class="text-end">
                <button type="submit" class="btn btn-success">Update Item</button>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('category_id').addEventListener('change', function () {
    const catId = this.value;
    const subCatDropdown = document.getElementById('sub_category_id');
    subCatDropdown.innerHTML = '<option>Loading...</option>';

    fetch('fetch_sub_categories.php?category_id=' + catId)
        .then(res => res.text())
        .then(html => {
            subCatDropdown.innerHTML = '<option value="">Select Sub Category</option>' + html;
        });
});

document.getElementById('item_type').addEventListener('change', function () {
    const bulkFields = document.getElementById('bulkFields');
    bulkFields.style.display = this.value === 'bulk' ? 'block' : 'none';
});
</script>
