<?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());
}

// Validate category ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo "<div class='alert alert-danger'>Invalid category ID.</div>";
    exit();
}

$id = (int) $_GET['id'];

// Fetch category
$stmt = $conn->prepare("SELECT * FROM game_categories WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$category = $result->fetch_assoc();
$stmt->close();

if (!$category) {
    echo "<div class='alert alert-danger'>Category not found.</div>";
    exit();
}

// Handle form submission
if (isset($_POST['update_category'])) {
    $game_id = $_POST['game_id'];
    $category_name = $_POST['category'];
    $category_image = $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>";
        }
    }

    // Update category
    $stmt = $conn->prepare("UPDATE game_categories SET game_id = ?, category = ?, category_image = ? WHERE id = ?");
    $stmt->bind_param("issi", $game_id, $category_name, $category_image, $id);
    if ($stmt->execute()) {
        $_SESSION['success_message'] = "Category updated successfully!";
        header("Location: game_categories.php");
        exit;
    } else {
        echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
    }
    $stmt->close();
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Game Category</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="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>Edit Game Category</h2>

            <!-- Edit Category Form -->
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars($id); ?>">
                <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()) {
                                $selected = $game['game_id'] === $category['game_id'] ? 'selected' : '';
                                echo "<option value='{$game['game_id']}' $selected>" . 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" name="category" id="category" class="form-control"
                        value="<?php echo htmlspecialchars($category['category']); ?>" required>
                </div>
                <div class="mb-3">
                    <label for="category_image" class="form-label">Category Image</label>
                    <input type="file" name="category_image" id="category_image" class="form-control" accept="image/*">
                    <?php if (!empty($category['category_image'])): ?>
                        <div class="mt-2">
                            <p>Current Image:</p>
                            <img src="<?php echo htmlspecialchars($category['category_image']); ?>" alt="Category Image"
                                width="100">
                        </div>
                    <?php endif; ?>
                </div>
                <button type="submit" name="update_category" class="btn btn-primary">Update Category</button>
                <a href="game_categories.php" class="btn btn-secondary">Cancel</a>
            </form>
        </div>
</body>

</html>