<?php
session_start();
include 'includes/header.php';
include 'includes/sidebar.php';
include 'includes/connect.php'; // DB connection

// Get inventory ID
if(!isset($_GET['id']) || empty($_GET['id'])){
    echo "<script>alert('Invalid Inventory ID'); window.location.href='inventory_list.php';</script>";
    exit;
}

$id = intval($_GET['id']);

// Fetch inventory record
$query = "SELECT * FROM inventory_management WHERE id=$id";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result)==0){
    echo "<script>alert('Inventory record not found'); window.location.href='inventory_list.php';</script>";
    exit;
}

$inventory = mysqli_fetch_assoc($result);

// Fetch distributors and categories
$distributors = mysqli_query($conn, "SELECT * FROM distributor ORDER BY name ASC");
$categories   = mysqli_query($conn, "SELECT * FROM category ORDER BY category_name ASC");

// ✅ Variety name fetch
$variety_q = mysqli_query($conn, "SELECT label_name FROM lifeline_configuration WHERE id='".$inventory['variety_id']."'");
$variety_data = mysqli_fetch_assoc($variety_q);
$current_variety = $variety_data['label_name'] ?? '';

// Handle form submission
if(isset($_POST['update_inventory'])){
    $distributor  = intval($_POST['distributor']);
    $category_id  = intval($_POST['category']);
    $variety_id   = intval($_POST['variety']); // ✅ NEW
    $brand        = mysqli_real_escape_string($conn, $_POST['brand']);
    $tray_no      = intval($_POST['tray_no']);
    $cavity       = intval($_POST['cavity']);
    $price        = intval($_POST['price']); // ✅ NEW
    $creation_date= mysqli_real_escape_string($conn, $_POST['creation_date']);

    // Validation
    if(empty($brand) || empty($tray_no) || empty($cavity) || empty($price) || empty($creation_date)){
        $error = "All fields are required";
    } elseif(!is_numeric($tray_no) || !is_numeric($cavity) || !is_numeric($price)){
        $error = "Tray No, Cavity and Price must be numeric";
    } else {
        $update = "
            UPDATE inventory_management SET 
            distributor=$distributor,
            category_id=$category_id,
            variety_id=$variety_id,
            brand='$brand',
            tray_no=$tray_no,
            cavity=$cavity,
            price=$price,
            creation_date='$creation_date'
            WHERE id=$id
        ";
        if(mysqli_query($conn, $update)){
            echo "<script>alert('Inventory updated successfully'); window.location.href='inventory_list.php';</script>";
            exit;
        } else {
            $error = "Database error: ".mysqli_error($conn);
        }
    }
}
?>

<div class="main-content-inner">
    <div class="main-content-wrap">

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>Edit Inventory</h3>
        </div>

        <?php if(isset($error)){ ?>
            <div class="text-red-500 mb-4"><?php echo $error; ?></div>
        <?php } ?>

        <form class="form-add-category" method="POST">

            <div class="wg-box mb-30" style="display:flex; gap:20px; flex-wrap:wrap;">

                <!-- Distributor -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Distributor <span class="tf-color-1">*</span></div>
                    <select name="distributor" required>
                        <option value="">Select Distributor</option>
                        <?php while($d = mysqli_fetch_assoc($distributors)){ ?>
                            <option value="<?php echo $d['id']; ?>" <?php if($d['id']==$inventory['distributor']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($d['name']); ?>
                            </option>
                        <?php } ?>
                    </select>
                </fieldset>

                <!-- Category -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Category <span class="tf-color-1">*</span></div>
                    <select name="category" id="category-select" required>
                        <option value="">Select Category</option>
                        <?php while($c = mysqli_fetch_assoc($categories)){ ?>
                            <option value="<?php echo $c['id']; ?>" <?php if($c['id']==$inventory['category_id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($c['category_name']); ?>
                            </option>
                        <?php } ?>
                    </select>
                </fieldset>

                <!-- ✅ Variety -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Variety <span class="tf-color-1">*</span></div>
                    <select name="variety" id="variety-select" required>
                        <option value="<?php echo $inventory['variety_id']; ?>" selected>
                            <?php echo htmlspecialchars($current_variety); ?>
                        </option>
                    </select>
                </fieldset>

                <!-- Brand -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Brand <span class="tf-color-1">*</span></div>
                    <select name="brand" id="brand-select" required>
                        <option value="<?php echo htmlspecialchars($inventory['brand']); ?>" selected>
                            <?php echo htmlspecialchars($inventory['brand']); ?>
                        </option>
                    </select>
                </fieldset>

                <!-- Tray No -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Tray No <span class="tf-color-1">*</span></div>
                    <input type="number" name="tray_no" value="<?php echo $inventory['tray_no']; ?>" required>
                </fieldset>

                <!-- Cavity -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Cavity <span class="tf-color-1">*</span></div>
                    <input type="number" name="cavity" value="<?php echo $inventory['cavity']; ?>" required>
                </fieldset>

                <!-- ✅ Price -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Price <span class="tf-color-1">*</span></div>
                    <input type="number" name="price" value="<?php echo $inventory['price']; ?>" required>
                </fieldset>

                <!-- Creation Date -->
                <fieldset style="flex:1; min-width:200px;">
                    <div class="body-title mb-10">Creation Date <span class="tf-color-1">*</span></div>
                    <input type="date" name="creation_date" value="<?php echo $inventory['creation_date']; ?>" required>
                </fieldset>

            </div>

            <div class="cols gap10">
                <button class="tf-button w380" type="submit" name="update_inventory">Update Inventory</button>
                <a href="inventory_list.php" class="tf-button style-3 w380">Cancel</a>
            </div>

        </form>

    </div>
</div>

<?php include 'includes/footer.php'; ?>

<!-- jQuery for category-dependent brand -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){

    // ================= CATEGORY → VARIETY =================
    $('#category-select').change(function(){

        var category_id = $(this).val();

        if(category_id){

            $.ajax({
                url: 'get_variety.php',
                type: 'POST',
                data: {category_id: category_id},
                success: function(response){
                    $('#variety-select').html(response);

                    // reset brand
                    $('#brand-select').html('<option value="">Select Brand</option>');
                }
            });

        } else {
            $('#variety-select').html('<option value="">Select Variety</option>');
            $('#brand-select').html('<option value="">Select Brand</option>');
        }

    });

    // ================= VARIETY → BRAND =================
    $('#variety-select').change(function(){

        var variety_id = $(this).val();

        if(variety_id){

            $.ajax({
                url: 'get_brands.php',
                type: 'POST',
                data: {variety_id: variety_id},
                success: function(response){
                    $('#brand-select').html(response);
                }
            });

        } else {
            $('#brand-select').html('<option value="">Select Brand</option>');
        }

    });

});
</script>