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

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$quiz_id = isset($_GET['quiz_id']) ? (int) $_GET['quiz_id'] : 0;

if ($id) {
    // 1. Get media URL to delete file
    $stmt = $conn->prepare("SELECT media_url FROM quiz_questions WHERE question_id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
        if (!empty($row['media_url']) && file_exists('../' . $row['media_url'])) {
            unlink('../' . $row['media_url']);
        }
    }
    $stmt->close();

    // 2. Delete from DB
    $stmt_del = $conn->prepare("DELETE FROM quiz_questions WHERE question_id = ?");
    $stmt_del->bind_param("i", $id);
    if ($stmt_del->execute()) {
        header("Location: manage_questions.php?quiz_id=$quiz_id&msg=deleted");
    } else {
        echo "Error: " . $conn->error;
    }
    $stmt_del->close();
} else {
    header("Location: manage_quizzes.php");
}
?>