<?php
include 'layout.php';
include 'db.php';
include 'auth.php';
require_right('View Categories');

// Fetch all categories with their sub-categories
$query = "
    SELECT 
        c.id AS category_id,
        c.name AS category_name,
        GROUP_CONCAT(sc.name ORDER BY sc.name SEPARATOR ', ') AS sub_categories
    FROM categories c
    LEFT JOIN sub_categories sc ON sc.category_id = c.id
    GROUP BY c.id
    ORDER BY c.id DESC
";

$result = $conn->query($query);
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>Category List</h4>
                <h6>View all categories and their sub-categories</h6>
            </div>
            <div class="page-btn">
                <a href="add_category.php" class="btn btn-primary me-2">
                    <i class="fa fa-plus"></i> Add Category
                </a>
                <a href="add_sub_category.php" class="btn btn-secondary">
                    <i class="fa fa-plus"></i> Add Sub Category
                </a>
            </div>
        </div>

        <div class="card">
            <div class="table-responsive">
                <table class="table datatable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Category Name</th>
                            <th>Sub Categories</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= $row['category_id'] ?></td>
                            <td><?= htmlspecialchars($row['category_name']) ?></td>
                            <td><?= htmlspecialchars($row['sub_categories'] ?? '—') ?></td>
                            <td class="text-end">
                                <a href="edit_category.php?id=<?= $row['category_id'] ?>" class="btn btn-sm btn-outline-warning">
                                    <i class="fa fa-edit"></i>
                                </a>
                                <a href="delete_category.php?id=<?= $row['category_id'] ?>" onclick="return confirm('Delete this category and its sub-categories?')" class="btn btn-sm btn-outline-danger">
                                    <i class="fa fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
