<?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">Sorting Groups</h6>

        <a href="add-sorting-group.php" class="btn btn-primary btn-sm">
            + Add Group
        </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="categoryFilter" class="form-control">
                    <option value="">All Categories</option>

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

        <table id="groupTable" class="display table table-bordered" width="100%">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Category</th>
                    <th>Subcategory</th>
                    <th>Group Name</th>
                    <th>Sort</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>

            <tbody>

                <?php
$q = mysqli_query($conn,"
    SELECT sg.*, 
           c.name as category_name,
           sc.name as subcategory_name
    FROM sorting_groups sg
    LEFT JOIN categories c ON c.id = sg.category_id
    LEFT JOIN subcategories sc ON sc.id = sg.subcategory_id
    ORDER BY sg.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><?= $row['sort_order'] ?></td>

                    <td>
                        <span class="badge badge-<?= $row['status']=='active'?'success':'danger' ?>">
                            <?= ucfirst($row['status']) ?>
                        </span>
                    </td>

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

                        <!-- DELETE -->
                        <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 = $('#groupTable').DataTable({
        order: [
            [0, 'desc']
        ]
    });


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

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

    /* ✅ STATUS UPDATE */
    $('#groupTable').on('change', '.status-change', function() {

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

        $.post('api/update_sorting_group.php', {
            id: id,
            status: status
        }, function(res) {

            if (res == 1 || res.status === 'success') {

                toastr.success('Status updated');

                let badge = row.find('.badge');
                badge.removeClass('badge-success badge-danger');

                if (status === 'active') badge.addClass('badge-success');
                if (status === 'inactive') badge.addClass('badge-danger');

                badge.text(status.charAt(0).toUpperCase() + status.slice(1));

            } else {
                toastr.error('Failed to update status');
            }
        }, 'json');
    });

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

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

        Swal.fire({
            title: 'Are you sure?',
            text: "Sorting group will be permanently deleted!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {

            if (result.isConfirmed) {

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

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

                }, 'json');

            }
        });

    });

});
</script>