<?php
require_once __DIR__ . '/admin_header.php';

// Handle deletion
$msg = '';
$msg_type = 'success';

if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $cat_id = intval($_GET['id']);
    try {
        // Fetch image filename to delete it from disk if possible
        $stmt_img = $pdo->prepare("SELECT image FROM categories WHERE id = ?");
        $stmt_img->execute([$cat_id]);
        $img_name = $stmt_img->fetchColumn();

        $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
        $stmt->execute([$cat_id]);

        // Delete image if not empty and not matching default patterns
        if (!empty($img_name) && file_exists(__DIR__ . '/../assets/images/' . $img_name) && strpos($img_name, 'cat_') === false) {
            @unlink(__DIR__ . '/../assets/images/' . $img_name);
        }

        $msg = 'Category deleted successfully.';
    } catch (Exception $e) {
        $msg = 'Failed to delete category: ' . $e->getMessage() . '. (Hint: Ensure no products remain assigned to this category.)';
        $msg_type = 'danger';
    }
}

// Fetch all categories
try {
    $stmt = $pdo->query("SELECT c.*, COUNT(p.id) as product_count FROM categories c LEFT JOIN products p ON c.id = p.category_id GROUP BY c.id ORDER BY c.id ASC");
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    $categories = [];
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="text-white mb-1">Catalog Categories</h2>
        <p class="text-muted small">Manage classifications, arched landing images, and routing slugs.</p>
    </div>
    <a href="category_add.php" class="btn-luxury">
        <i class="fa-solid fa-plus-circle me-1"></i> Add Category
    </a>
</div>

<?php if (!empty($msg)): ?>
    <div class="alert alert-<?php echo $msg_type; ?> border-<?php echo $msg_type; ?> bg-dark text-<?php echo $msg_type; ?> alert-dismissible fade show rounded-3 mb-4" role="alert">
        <i class="fa-solid <?php echo ($msg_type === 'success') ? 'fa-circle-check' : 'fa-circle-exclamation'; ?> me-2"></i> <?php echo htmlspecialchars($msg); ?>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="admin-card">
    <?php if (empty($categories)): ?>
        <div class="text-center py-5 text-muted">
            <i class="fa-solid fa-folder display-4 mb-3 d-block opacity-25"></i>
            No categories exist. Create your first category to classify collection assets!
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-dark table-luxury align-middle m-0">
                <thead>
                    <tr>
                        <th style="width: 80px;">Preview</th>
                        <th>Category Name</th>
                        <th>Slug Reference</th>
                        <th class="text-center">Assigned Products</th>
                        <th class="text-end" style="width: 200px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat): ?>
                        <tr>
                            <td>
                                <?php if (!empty($cat['image'])): ?>
                                    <img src="../assets/images/<?php echo htmlspecialchars($cat['image']); ?>" alt="Category Preview" class="rounded" style="width: 50px; height: 50px; object-fit: cover; border: 1px solid var(--border-gray);">
                                <?php else: ?>
                                    <div class="rounded d-flex align-items-center justify-content-center bg-dark text-muted" style="width: 50px; height: 50px; border: 1px solid var(--border-gray);">
                                        <i class="fa-solid fa-folder"></i>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td><strong class="text-white"><?php echo htmlspecialchars($cat['name']); ?></strong></td>
                            <td><code class="text-warning bg-dark px-2 py-1 rounded small"><?php echo htmlspecialchars($cat['slug']); ?></code></td>
                            <td class="text-center"><span class="badge bg-dark border border-secondary text-white py-2 px-3 rounded-pill"><?php echo $cat['product_count']; ?> Products</span></td>
                            <td class="text-end">
                                <div class="d-flex justify-content-end gap-2">
                                    <a href="category_edit.php?id=<?php echo $cat['id']; ?>" class="btn btn-outline-warning btn-sm rounded-pill px-3" title="Edit Category Information">
                                        <i class="fa-solid fa-pen-to-square me-1"></i> Edit
                                    </a>
                                    <a href="categories.php?action=delete&id=<?php echo $cat['id']; ?>" class="btn btn-outline-danger btn-sm rounded-pill px-3" onclick="return confirm('Are you completely sure you want to delete category \'<?php echo addslashes($cat['name']); ?>\'? This action is permanent.')" title="Delete Category">
                                        <i class="fa-solid fa-trash-can me-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php
require_once __DIR__ . '/admin_footer.php';
?>
