<?php
include 'auth.php';
require_once '../config/db.php';

// Self-heal: create table if missing
$conn->query("CREATE TABLE IF NOT EXISTS `local_tour_categories` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(150) NOT NULL,
    `slug` VARCHAR(150) NOT NULL,
    `description` TEXT,
    `sort_order` INT DEFAULT 0,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Handle delete
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    // Unlink tours from this category
    $conn->query("UPDATE local_tours SET category_id = NULL WHERE category_id = $del_id");
    $conn->query("DELETE FROM local_tour_categories WHERE id = $del_id");
    $_SESSION['success_msg'] = "Category deleted successfully!";
    header("Location: categories.php");
    exit();
}

$categories = $conn->query("SELECT c.*, COUNT(t.id) as tour_count FROM local_tour_categories c LEFT JOIN local_tours t ON t.category_id = c.id GROUP BY c.id ORDER BY c.sort_order ASC, c.id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tour Categories | Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body { background: #f0f2f5; margin: 0; }
        /* Sidebar */
        .admin-sidebar {
            position: fixed; top: 0; left: 0;
            width: 260px; height: 100vh;
            background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            z-index: 100; padding: 30px 0;
            display: flex; flex-direction: column;
            box-shadow: 4px 0 20px rgba(0,0,0,0.3);
        }
        .sidebar-logo { text-align: center; padding: 0 20px 30px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 20px; }
        .sidebar-logo img { height: 70px; filter: brightness(0) invert(1); }
        .sidebar-logo h6 { color: #aaa; font-size: 11px; text-transform: uppercase; letter-spacing: 3px; margin-top: 8px; }
        .sidebar-nav a { display: flex; align-items: center; padding: 12px 25px; color: rgba(255,255,255,0.65); text-decoration: none; font-size: 14px; font-weight: 500; transition: 0.3s; gap: 12px; border-left: 3px solid transparent; }
        .sidebar-nav a:hover, .sidebar-nav a.active { color: #fff; background: rgba(255,255,255,0.08); border-left-color: #ff6900; }
        .sidebar-nav a i { width: 20px; text-align: center; font-size: 15px; }
        .sidebar-section { padding: 15px 25px 5px; color: rgba(255,255,255,0.3); font-size: 10px; text-transform: uppercase; letter-spacing: 2px; }
        .sidebar-bottom { margin-top: auto; padding: 20px 25px; border-top: 1px solid rgba(255,255,255,0.1); }
        .sidebar-bottom a { display: flex; align-items: center; gap: 10px; color: rgba(255,255,255,0.6); text-decoration: none; font-size: 14px; padding: 10px; border-radius: 10px; transition: 0.3s; }
        .sidebar-bottom a:hover { color: #fff; background: rgba(255,0,0,0.2); }
        /* Main */
        .admin-main { margin-left: 260px; min-height: 100vh; padding: 30px; }
        .admin-topbar { display: flex; justify-content: space-between; align-items: center; background: #fff; border-radius: 16px; padding: 15px 25px; margin-bottom: 30px; box-shadow: 0 2px 20px rgba(0,0,0,0.06); }
        .admin-card { background: #fff; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.06); overflow: hidden; }
        .admin-card-header { padding: 20px 25px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; }
        .admin-table th { background: #f8f9fa; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: #888; padding: 12px 20px; border: none; }
        .admin-table td { padding: 14px 20px; border-bottom: 1px solid #f5f5f5; vertical-align: middle; }
        .admin-table tr:last-child td { border-bottom: none; }
        .cat-badge { display: inline-flex; align-items: center; gap: 6px; background: linear-gradient(135deg, #ff6900, #ff8c00); color: #fff; padding: 6px 14px; border-radius: 50px; font-size: 12px; font-weight: 600; }
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="admin-sidebar">
    <div class="sidebar-logo">
        <img src="../assets/img/logo.png" alt="Logo" onerror="this.style.display='none'">
        <h6>Admin Panel</h6>
    </div>
    <div class="sidebar-nav">
        <a href="index.php"><i class="fas fa-home"></i> Dashboard</a>
        <div class="sidebar-section" style="padding-top:20px;">Tour Management</div>
        <a href="packages.php"><i class="fas fa-globe"></i> International Tours</a>
        <a href="add-package.php"><i class="fas fa-plus-circle"></i> Add Tour</a>
        <a href="local-tours.php"><i class="fas fa-map-marked-alt"></i> Local Tours</a>
        <a href="add-local-tour.php"><i class="fas fa-plus"></i> Add Local Tour</a>
        <a href="categories.php" class="active"><i class="fas fa-tags"></i> Categories</a>
        <div class="sidebar-section" style="padding-top:20px;">Homepage</div>
        <a href="destinations.php"><i class="fas fa-map-pin"></i> Destinations</a>
        <a href="add-destination.php"><i class="fas fa-plus-circle"></i> Add Destination</a>
        <a href="testimonials.php"><i class="fas fa-star"></i> Testimonials</a>
        <a href="add-testimonial.php"><i class="fas fa-plus-circle"></i> Add Testimonial</a>
        <a href="google-reviews.php"><i class="fab fa-google"></i> Google Reviews</a>
        <div class="sidebar-section" style="padding-top:20px;">Media</div>
        <a href="manage-gallery.php"><i class="fas fa-images"></i> Gallery Manager</a>
        <div class="sidebar-section" style="padding-top:20px;">Site</div>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt"></i> View Website</a>
    </div>
    <div class="sidebar-bottom">
        <a href="logout.php"><i class="fas fa-sign-out-alt text-danger"></i> Logout</a>
    </div>
</div>

<!-- Main -->
<div class="admin-main">
    <div class="admin-topbar">
        <div>
            <h5 class="fw-bold mb-0">Tour Categories</h5>
            <p class="text-muted small mb-0">Manage local tour categories</p>
        </div>
        <a href="add-category.php" class="btn btn-primary rounded-pill px-4 shadow-sm">
            <i class="fas fa-plus me-2"></i>Add Category
        </a>
    </div>

    <?php if (isset($_SESSION['success_msg'])): ?>
        <div class="alert alert-success border-0 rounded-4 shadow-sm mb-4">
            <i class="fas fa-check-circle me-2"></i><?= $_SESSION['success_msg'] ?>
        </div>
        <?php unset($_SESSION['success_msg']); ?>
    <?php endif; ?>

    <div class="admin-card">
        <table class="table admin-table mb-0">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Category Name</th>
                    <th>Slug</th>
                    <th>Description</th>
                    <th>Tours</th>
                    <th>Sort Order</th>
                    <th style="width:120px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($categories && $categories->num_rows > 0): ?>
                    <?php while ($cat = $categories->fetch_assoc()): ?>
                    <tr>
                        <td class="fw-bold text-muted"><?= $cat['id'] ?></td>
                        <td>
                            <span class="cat-badge"><i class="fas fa-tag"></i> <?= htmlspecialchars($cat['name']) ?></span>
                        </td>
                        <td><code class="text-muted small"><?= htmlspecialchars($cat['slug']) ?></code></td>
                        <td class="text-muted small" style="max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                            <?= htmlspecialchars($cat['description'] ?? '—') ?>
                        </td>
                        <td>
                            <span class="badge bg-light text-dark fw-bold"><?= $cat['tour_count'] ?> tours</span>
                        </td>
                        <td class="text-muted"><?= $cat['sort_order'] ?></td>
                        <td>
                            <a href="edit-category.php?id=<?= $cat['id'] ?>" class="btn btn-light btn-sm rounded-circle me-1" title="Edit">
                                <i class="fas fa-edit text-primary" style="font-size:12px;"></i>
                            </a>
                            <a href="categories.php?delete=<?= $cat['id'] ?>" class="btn btn-light btn-sm rounded-circle" title="Delete"
                               onclick="return confirm('Delete category \'<?= htmlspecialchars(addslashes($cat['name'])) ?>\'? Tours in this category will be uncategorized.')">
                                <i class="fas fa-trash text-danger" style="font-size:12px;"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-5">
                            <i class="fas fa-tags fa-2x mb-3 d-block text-muted opacity-50"></i>
                            No categories yet. <a href="add-category.php" class="text-primary fw-bold">Add your first category</a>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
