<?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 Options</h6>

        <a href="add-sorting-options.php" class="btn btn-primary btn-sm">
            + Add Option
        </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 class="col-md-4">
                <label><strong>Filter by Sorting Group</strong></label>
                <select id="groupFilter" class="form-control">
                    <option value="">All Group</option>

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





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

            <tbody>
                <?php
$q = mysqli_query($conn,"
SELECT so.*, sg.name as group_name, c.name as category_name
FROM sorting_options so
LEFT JOIN sorting_groups sg ON sg.id = so.sorting_group_id
LEFT JOIN categories c ON c.id = sg.category_id
ORDER BY so.id DESC
");

while($row=mysqli_fetch_assoc($q)){
?>
                <tr data-id="<?= $row['id'] ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['category_name']) ?></td>
                    <td><?= htmlspecialchars($row['group_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>
                        <a href="edit_sorting_options.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 = $('#optionTable').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();
    });

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




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

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

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

            if (res == 1 || res.status === 'success') {
                toastr.success('Status updated');

                let badge = row.find('.badge');
                badge.removeClass('badge-success badge-danger');
                badge.addClass(status === 'active' ? 'badge-success' : 'badge-danger');
                badge.text(status.charAt(0).toUpperCase() + status.slice(1));

            } else toastr.error('Failed');

        }, 'json');
    });

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

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

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

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

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

                }, 'json');

            }
        });

    });

});
</script>