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

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

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<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 d-flex justify-content-between">
        <h6 class="m-0 font-weight-bold text-secondary">Group Variants</h6>

        <a href="add-variant-groups.php" class="btn btn-primary btn-sm">
            + Add Variant
        </a>
    </div>

    <div class="card-body">

        <!-- ✅ FILTER BAR -->
        <div class="row mb-3">
            <div class="col-md-4">
                <label><strong>Filter by Category</strong></label>
                <select id="productFilter" class="form-control">
                    <option value="">All Categories</option>

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

        <table id="gvTable" class="display table table-bordered" width="100%">
            <thead>
                <tr>
                    <th>ID</th>
<th>Category</th>
<th>Subcategory</th>
<th>Variant Name</th>
<th>Unit</th>
<th>Required</th>
<th>Sort</th>
<th>Actions</th>
                </tr>
            </thead>

            <tbody>
<?php
$q = mysqli_query($conn,"
SELECT vg.*, 
       c.name as category_name,
       sc.name as subcategory_name
FROM variant_groups vg
LEFT JOIN categories c ON c.id = vg.category_id
LEFT JOIN subcategories sc ON sc.id = vg.subcategory_id
ORDER BY vg.id DESC
");

while($row=mysqli_fetch_assoc($q)){
?>
<tr data-id="<?= $row['id'] ?>">
    <td><?= $row['id'] ?></td>
    <td><?= htmlspecialchars($row['category_name']) ?></td>
    <td>
<?= !empty($row['subcategory_name']) 
    ? htmlspecialchars($row['subcategory_name']) 
    : '-' ?>
</td>
    <td><?= htmlspecialchars($row['name']) ?></td>
    <td><?= htmlspecialchars($row['unit']) ?></td>

    <td>
        <span class="badge badge-<?= $row['required'] ? 'warning':'secondary' ?>">
            <?= $row['required'] ? 'Required':'Optional' ?>
        </span>
    </td>

    <td><?= $row['sort_order'] ?></td>

    <td>
        <a href="edit_group_variant.php?id=<?= $row['id'] ?>"
           class="btn btn-sm btn-info mt-1">Edit</a>

        <button class="btn btn-sm btn-danger mt-1 delete-btn">
            Delete
        </button>
    </td>
</tr>
<?php } ?>
            </tbody>
        </table>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function() {

    const table = $('#gvTable').DataTable({
        order: [[0,'desc']]
    });

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

    /* ✅ PRODUCT FILTER */
   $('#productFilter').on('change', function() {
        let val = $(this).val();
        table.column(1).search(val).draw();
    });
    

    /* ✅ DELETE */
    $('#gvTable').on('click', '.delete-btn', function() {

        let row = $(this).closest('tr');
        let id = row.data('id');

        Swal.fire({
            title: 'Delete variant?',
            icon: 'warning',
            showCancelButton: true
        }).then(r => {
            if (r.isConfirmed) {

                $.post('delete_group_variant.php', {id}, function(res) {

                    if (res == 1 || res.status === 'success') {
                        toastr.success('Variant deleted');
                        table.row(row).remove().draw();
                    } else {
                        toastr.error('Unable to delete');
                    }

                }, 'json');

            }
        });

    });

});
</script>
