<?php
session_start();
require_once '../../config/database.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];

// Get question ID from request
$question_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($question_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid question ID']);
    exit();
}

try {
    // Fetch question details
    $stmt = $pdo->prepare("
        SELECT q.*, e.created_by as exam_creator
        FROM online_exam_questions q
        JOIN online_exams e ON q.online_exam_id = e.id
        WHERE q.id = ?
    ");
    $stmt->execute([$question_id]);
    $question = $stmt->fetch();
    
    if (!$question) {
        echo json_encode(['success' => false, 'message' => 'Question not found']);
        exit();
    }
    
    // Check if user has permission to edit this question
    if ($question['exam_creator'] != $user_id && $user_role != 'admin') {
        echo json_encode(['success' => false, 'message' => 'Permission denied']);
        exit();
    }
    
    echo json_encode(['success' => true, 'question' => $question]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching question: ' . $e->getMessage()]);
}