<?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 sorting_groups WHERE id=$id");
$g = mysqli_fetch_assoc($res);

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

<style>
body {
    background: #f6f7f9;
}

.card {
    border-radius: 12px;
}

.form-section {
    background: #fafafa;
    border: 1px dashed #ddd;
    border-radius: 10px;
    padding: 15px;
}
</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 Sorting Group</h6>
    </div>

    <div class="container my-4">

        <form id="editGroupForm">

            <input type="hidden" name="id" value="<?= $g['id'] ?>">

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

                    <div class="row mt-3">

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

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

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

        <?php
        $subs = mysqli_query($conn,"
            SELECT id,name FROM subcategories
            WHERE category_id=".$g['category_id']."
            AND status='active'
        ");

        while($s = mysqli_fetch_assoc($subs)){
            $sel = ($s['id'] == $g['subcategory_id']) ? 'selected' : '';
            echo "<option value='{$s['id']}' $sel>{$s['name']}</option>";
        }
        ?>
    </select>
</div>

                        <!-- GROUP NAME -->
                        <div class="col-md-12 mt-2">
                            <label class="form-label">Group Name</label>
                            <input type="text"
                                   name="name"
                                   value="<?= htmlspecialchars($g['name']) ?>"
                                   class="form-control"
                                   required>
                        </div>

                    </div>

                    <div class="row mt-3">

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

                        <!-- STATUS -->
                        <div class="col-md-6">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select form-control">
                                <option value="active" <?= $g['status']=='active'?'selected':'' ?>>Active</option>
                                <option value="inactive" <?= $g['status']=='inactive'?'selected':'' ?>>Inactive</option>
                            </select>
                        </div>

                    </div>

                </div>
            </div>

            <button class="btn btn-primary">Update Sorting Group</button>
            <a href="show_sorting_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"
};

$('#editGroupForm').submit(function(e){
    e.preventDefault();

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

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

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

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

    }, 'json');
});
</script>
<script>
$('#categorySelect').on('change', function(){

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

    if(category_id === ''){
        $('#subcategorySelect').html('<option value="">Select Subcategory</option>');
        return;
    }

    $.post('api/get_subcategories.php', 
        { category_id: category_id }, 
        function(data){
            $('#subcategorySelect').html(data);
        }
    );
});
</script>
