<?php include("auth.php"); ?>

<!DOCTYPE html>
<html>
<head>
    <title>Categories</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<nav class="navbar navbar-dark bg-dark px-4">
    <span class="navbar-brand">Category Management</span>
    <a href="dashboard.php" class="btn btn-secondary btn-sm">Dashboard</a>
</nav>

<div class="container mt-4">
    <div class="d-flex justify-content-between mb-3">
        <h3>Categories</h3>
        <a href="category-add.php" class="btn btn-primary">Add Category</a>
    </div>

    <table class="table table-bordered table-hover bg-white">
        <tr class="table-dark">
            <th>#</th>
            <th>Category Name</th>
            <th>Action</th>
        </tr>

        <?php
        $data = $conn->query("SELECT * FROM categories ORDER BY name");
        $i = 1;
        while($row = $data->fetch_assoc()):
        ?>
        <tr>
            <td><?= $i++ ?></td>
            <td><?= htmlspecialchars($row['name']) ?></td>
            <td>
                <a href="category-edit.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
                <a href="categories.php?delete=<?= $row['id'] ?>"
                   class="btn btn-danger btn-sm"
                   onclick="return confirm('Delete this category?')">
                   Delete
                </a>
            </td>
        </tr>
        <?php endwhile; ?>
    </table>
</div>

<?php
if (isset($_GET['delete'])) {
    $stmt = $conn->prepare("DELETE FROM categories WHERE id=?");
    $stmt->bind_param("i", $_GET['delete']);
    $stmt->execute();
    header("Location: categories.php");
}
?>

</body>
</html>
