<?php
include 'inc/header.php';

if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'user') {
    echo "<script>window.location.href='index.php'</script>";
    exit;
}

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

$res = mysqli_query($conn,"SELECT * FROM variant_groups WHERE id=$id");
$gv = mysqli_fetch_assoc($res);

if (!$gv) {
    echo "<script>window.location.href='show_variant_groups.php'</script>";
    exit;
}
?>

<style>
body {
    background: #f6f7f9;
}

.card {
    border-radius: 12px;
}
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-secondary">Edit Group Variant</h6>
    </div>

    <div class="container my-4">

        <form id="gvEditForm">
            <input type="hidden" name="id" value="<?= $gv['id'] ?>">

            <div class="card mb-3">
                <div class="card-body">
                    <h5>Basic Information</h5>

                    <div class="row mt-3">

                        <!-- Category -->
                        <div class="col-md-4">
                            <label>Category</label>
                            <select name="category_id" id="category" class="form-control" required>
                                <option value="">Select Category</option>

                                <?php
$pf = mysqli_query($conn,"SELECT id,name FROM categories ORDER BY name ASC");
while($p=mysqli_fetch_assoc($pf)){
$sel = ($p['id'] == $gv['category_id']) ? 'selected' : '';
echo "<option value='{$p['id']}' $sel>"
.htmlspecialchars($p['name']).
"</option>";
}
?>
                            </select>
                        </div>

                        <!-- Subcategory -->
                        <div class="col-md-4">
                            <label>Subcategory</label>
                            <select name="subcategory_id" id="subcategory" class="form-control">
                                <option value="">Select Subcategory</option>

                                <?php
if($gv['category_id']){
$scq = mysqli_query($conn,"SELECT id,name FROM subcategories WHERE category_id=".$gv['category_id']." ORDER BY name ASC");
while($sc=mysqli_fetch_assoc($scq)){
$sel = ($sc['id'] == $gv['subcategory_id']) ? 'selected' : '';
echo "<option value='{$sc['id']}' $sel>"
.htmlspecialchars($sc['name']).
"</option>";
}
}
?>
                            </select>
                        </div>

                        <!-- Variant Name -->
                        <div class="col-md-4">
                            <label>Variant Name</label>
                            <input type="text" name="name" value="<?= htmlspecialchars($gv['name']) ?>"
                                class="form-control" required>
                        </div>

                    </div>

                    <div class="row mt-3">

                        <div class="col-md-4">
                            <label>Unit</label>
                            <input type="text" name="unit" value="<?= htmlspecialchars($gv['unit']) ?>"
                                class="form-control">
                        </div>

                        <div class="col-md-4">
                            <label>Required</label>
                            <select name="required" class="form-control">
                                <option value="0" <?= $gv['required']==0?'selected':'' ?>>Optional</option>
                                <option value="1" <?= $gv['required']==1?'selected':'' ?>>Required</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label>Sort Order</label>
                            <input type="number" name="sort_order" value="<?= (int)$gv['sort_order'] ?>"
                                class="form-control">
                        </div>

                    </div>

                </div>
            </div>

            <button class="btn btn-primary">Update Variant</button>
            <a href="show_variant_groups.php" class="btn btn-secondary">Cancel</a>

        </form>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
toastr.options = {
    closeButton: true,
    progressBar: true,
    positionClass: "toast-top-right",
    timeOut: "3000"
};

// store selected subcategory from PHP
var selectedSubcategory = "<?= $gv['subcategory_id'] ?>";

// 🔥 Load subcategories when category changes
$('#category').change(function() {

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

    $('#subcategory').html('<option>Loading...</option>');

    $.post('api/get_subcategories.php', {
        category_id: cat_id
    }, function(data) {

        $('#subcategory').html(data);

        // 🔥 re-select subcategory after reload
        if (selectedSubcategory) {
            $('#subcategory').val(selectedSubcategory);
        }

    });

});

// 🔥 Trigger change on page load to ensure correct load
$(document).ready(function(){
    if ($('#category').val() !== '') {
        $('#category').trigger('change');
    }
});


// Submit form
$('#gvEditForm').submit(function(e) {
    e.preventDefault();

    $.post('api/update_group_variant.php',
        $(this).serialize(),
        function(r) {

            if (r.status === 'success') {
                toastr.success(r.message || 'Variant updated');

                setTimeout(() => {
                    window.location.href = 'show_variant_groups.php';
                }, 1200);

            } else {
                toastr.error(r.message || 'Update failed');
            }

        }, 'json');
});
</script>