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

include 'db.php';

if (isset($_GET['id'])) {
    $game_id = (int) $_GET['id'];

    try {
        // 1. Find all quizzes associated with this game
        $quiz_ids = [];
        $stmt_find = $conn->prepare("SELECT quiz_id FROM quiz_games WHERE game_id = ?");
        $stmt_find->bind_param("i", $game_id);
        $stmt_find->execute();
        $res = $stmt_find->get_result();
        while ($row = $res->fetch_assoc()) {
            $quiz_ids[] = $row['quiz_id'];
        }
        $stmt_find->close();

        // 2. Clear out dependencies that don't have CASCADE
        if (!empty($quiz_ids)) {
            $placeholders = implode(',', array_fill(0, count($quiz_ids), '?'));
            $types = str_repeat('i', count($quiz_ids));

            if ($stmt_del_att = $conn->prepare("DELETE FROM quiz_attempts WHERE quiz_id IN ($placeholders)")) {
                $stmt_del_att->bind_param($types, ...$quiz_ids);
                $stmt_del_att->execute();
                $stmt_del_att->close();
            }

            if ($stmt_del_lb = $conn->prepare("DELETE FROM quiz_leaderboard WHERE quiz_id IN ($placeholders)")) {
                $stmt_del_lb->bind_param($types, ...$quiz_ids);
                $stmt_del_lb->execute();
                $stmt_del_lb->close();
            }
        }

        // 3. Delete from game_categories
        if ($stmt_cat = $conn->prepare("DELETE FROM game_categories WHERE game_id = ?")) {
            $stmt_cat->bind_param("i", $game_id);
            $stmt_cat->execute();
            $stmt_cat->close();
        }

        // 4. Delete the game (this cascades to quiz_games and quiz_questions)
        if ($stmt_game = $conn->prepare("DELETE FROM games WHERE game_id = ?")) {
            $stmt_game->bind_param("i", $game_id);
            if ($stmt_game->execute()) {
                header('Location: games.php?msg=deleted');
                exit();
            } else {
                throw new Exception("Error deleting game: " . $stmt_game->error);
            }
            $stmt_game->close();
        } else {
            throw new Exception("Database Error: Could not prepare game deletion.");
        }
    } catch (Exception $e) {
        echo "<div class='container mt-5'><div class='alert alert-danger'>
                <h4>Deletion Failed</h4>
                <p>" . $e->getMessage() . "</p>
                <a href='games.php' class='btn btn-outline-danger'>Back to Games</a>
              </div></div>";
    }
}
?>