<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';

header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $questionId = $_POST['question_id'] ?? null;

    if (!$questionId) {
        throw new Exception('Question ID is required');
    }

    // Check if user owns the question or is admin
    $stmt = $db->prepare("SELECT id FROM questions WHERE id = ? AND (instructor_id = ? OR ?)");
    $stmt->execute([$questionId, $userId, hasRole('admin') ? true : false]);
    if (!$stmt->fetch()) {
        throw new Exception('Question not found or access denied');
    }

    // Check if question is being used in any exams
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM exam_questions WHERE question_id = ?");
    $stmt->execute([$questionId]);
    $usage = $stmt->fetch();

    if ($usage['count'] > 0) {
        throw new Exception('Cannot delete question that is being used in exams');
    }

    $db->beginTransaction();

    // Delete question options
    $stmt = $db->prepare("DELETE FROM question_options WHERE question_id = ?");
    $stmt->execute([$questionId]);

    // Delete question tag assignments
    $stmt = $db->prepare("DELETE FROM question_tag_assignments WHERE question_id = ?");
    $stmt->execute([$questionId]);

    // Delete the question
    $stmt = $db->prepare("DELETE FROM questions WHERE id = ?");
    $stmt->execute([$questionId]);

    $db->commit();

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

} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>