<?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">Categories List</h6>

        <a href="add-category.php" class="btn btn-primary btn-sm">
            + Add Category
        </a>
    </div>

    <div class="card-body">
        <table id="categoryTable" class="display table table-bordered" width="100%">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Slug</th>
                <th>Image</th>
                <th>Sort</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
            </thead>

            <tbody>
            <?php
            $sql = "SELECT * FROM categories ORDER BY id DESC";
            $res = mysqli_query($conn, $sql);

            while ($row = mysqli_fetch_assoc($res)) {

                // Set image path or placeholder
                $imagePath = 'assets/images/no-image.png'; // default
                if (!empty($row['image']) && file_exists("uploads/categories/" . $row['image'])) {
                    $imagePath = "uploads/categories/" . $row['image'];
                }
            ?>
                <tr data-id="<?= $row['id'] ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['slug']) ?></td>
                    <td>
                        <img src="<?= $imagePath ?>" alt="<?= htmlspecialchars($row['name']) ?>" 
                             style="width:80px; height:80px; object-fit:cover; border-radius:4px;">
                    </td>
                    <td><?= $row['sort_order'] ?></td>

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

                    <td><?= date('d M Y h:i a', strtotime($row['created_at'])) ?></td>

                    <td>
                        <a href="edit_category.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-info">
                            Edit
                        </a>
                        <button class="btn btn-sm btn-danger 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 = $('#categoryTable').DataTable();

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

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

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

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

            if (result.isConfirmed) {

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

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

                });

            }
        });

    });

});
</script>