<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}

include 'db.php';
if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Add new category
if (isset($_POST['add_category'])) {
    $game_id = $_POST['game_id'];
    $category = $_POST['category'];
    $category_image = '';

    // Validate game_id
    $stmt = $conn->prepare("SELECT game_id FROM games WHERE game_id = ?");
    $stmt->bind_param("i", $game_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows == 0) {
        echo "<div class='alert alert-danger'>Invalid game ID.</div>";
        exit;
    }
    $stmt->close();

    // Handle image upload
    define('UPLOAD_DIR', '../../assets/images/');
    $target_dir = UPLOAD_DIR;
    if (isset($_FILES['category_image']) && $_FILES['category_image']['error'] === 0) {
        $image_name = basename($_FILES['category_image']['name']);
        $target_file = $target_dir . $image_name;
        if (!is_dir($target_dir)) {
            if (!mkdir($target_dir, 0777, true)) {
                echo "<div class='alert alert-danger'>Failed to create directory.</div>";
                exit;
            }
        }
        if (move_uploaded_file($_FILES['category_image']['tmp_name'], $target_file)) {
            $category_image = $image_name;
        } else {
            echo "<div class='alert alert-danger'>Error uploading image: " . $_FILES['category_image']['error'] . "</div>";
        }
    }

    // Insert category
    $stmt = $conn->prepare("INSERT INTO game_categories (game_id, category) VALUES (?, ?)");
    $stmt->bind_param("is", $game_id, $category);
    if ($stmt->execute()) {
        echo "<div class='alert alert-success'>Category added successfully!</div>";
    } else {
        echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
    }
    $stmt->close();
}

// Delete category
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM game_categories WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        echo "<div class='alert alert-success'>Category deleted successfully!</div>";
    } else {
        echo "<div class='alert alert-danger'>Error deleting category: " . $stmt->error . "</div>";
    }
    $stmt->close();
}

// Fetch categories
$sql = "SELECT gc.*, g.game_name FROM game_categories gc JOIN games g ON gc.game_id = g.game_id";
$result = $conn->query($sql);
if (!$result) {
    echo "<div class='alert alert-danger'>Query error: " . $conn->error . "</div>";
}

if (isset($_SESSION['success_message'])) {
    echo "<div class='alert alert-success'>" . htmlspecialchars($_SESSION['success_message']) . "</div>";
    unset($_SESSION['success_message']); // Clear the message after displaying
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Game Categories</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f0f4f8;
        }

        .sidebar {
            background-color: #343a40;
            min-height: 100vh;
            padding-top: 20px;
        }

        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px;
            display: block;
            border-radius: 5px;
            margin: 5px;
            transition: background-color 0.3s;
        }

        .sidebar a:hover {
            background-color: #007bff;
        }

        .content {
            margin-left: 250px;
            padding: 30px;
        }

        h2 {
            color: #343a40;
        }
    </style>
</head>

<body>
    <div class="d-flex">
        <!-- Sidebar -->
        <div class="sidebar col-md-2">
            <h3 class="text-center text-white">Admin Panel</h3>
            <a href="index.php">Dashboard</a>
            <a href="games.php">Manage Games</a>
            <a href="game_categories.php">Manage Categories</a>
            <a href="leaderboard.php">Leaderboard</a>
            <a href="events.php">Manage Events</a>
            <a href="profile_management.php">Profile Management</a>
            <a href="logout.php">Logout</a>
        </div>

        <div class="container py-5">
            <h2>Manage Game Categories</h2>

            <!-- Add Category Form -->
            <form method="post" action="game_categories.php" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="game_id" class="form-label">Game</label>
                    <select name="game_id" id="game_id" class="form-select" required>
                        <?php
                        $games = $conn->query("SELECT game_id, game_name FROM games");
                        if ($games) {
                            while ($game = $games->fetch_assoc()) {
                                echo "<option value='{$game['game_id']}'>" . htmlspecialchars($game['game_name']) . "</option>";
                            }
                        } else {
                            echo "<option value=''>Error loading games</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="category" class="form-label">Category Name</label>
                    <input type="text" class="form-control" id="category" name="category" required>
                </div>
                <button type="submit" name="add_category" class="btn btn-primary">Add Category</button>
            </form>

            <hr>

            <!-- Display Categories -->
            <h3>Existing Categories</h3>
            <?php if ($result && $result->num_rows > 0): ?>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Game</th>
                            <th>Category</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($row['game_name']); ?></td>
                                <td><?php echo htmlspecialchars($row['category']); ?></td>
                                <td>
                                    <a href="edit_category.php?id=<?php echo $row['id']; ?>"
                                        class="btn btn-warning btn-sm">Edit</a>
                                    <a href="game_categories.php?delete=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm"
                                        onclick="return confirm('Are you sure?');">Delete</a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p>No categories found.</p>
            <?php endif; ?>
        </div>
</body>

</html>