<?php
declare(strict_types=1);

session_start();
require_once '../../config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');
$conn = getDBConnection();
$id = (int) ($_POST['id'] ?? 0);

if (!$conn instanceof mysqli || $id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$check = $conn->prepare("SELECT id FROM exam_paper_questions WHERE question_id = ? LIMIT 1");
$check->bind_param('i', $id);
$check->execute();
$res = $check->get_result();
if ($res->num_rows > 0) {
    $check->close();
    echo json_encode(['success' => false, 'message' => 'Question is used in a paper']);
    exit;
}
$check->close();

$stmt = $conn->prepare("DELETE FROM exam_questions WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();

echo json_encode(['success' => true, 'message' => 'Question deleted successfully']);
