<?php
/**
 * Get Explanation API Endpoint
 * Retrieves cached explanations from JSON files
 */

// Set headers for JSON response and CORS
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get parameters
$exam = isset($_GET['exam']) ? $_GET['exam'] : '';
$questionNumber = isset($_GET['question']) ? $_GET['question'] : '';
$answerLetter = isset($_GET['answer']) ? strtoupper($_GET['answer']) : '';

// Validate required parameters
if (empty($exam) || empty($questionNumber) || empty($answerLetter)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required parameters: exam, question, answer']);
    exit;
}

// Sanitize inputs to prevent directory traversal
$exam = basename($exam); // Remove any path components
$exam = preg_replace('/[^a-zA-Z0-9._-]/', '', $exam); // Remove invalid characters
$questionNumber = preg_replace('/[^0-9]/', '', $questionNumber); // Only numbers
$answerLetter = preg_replace('/[^A-D]/', '', $answerLetter); // Only A-D

if (empty($exam) || empty($questionNumber) || empty($answerLetter)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid parameters']);
    exit;
}

// Construct JSON file path
$explanationsDir = dirname(__DIR__) . '/explanations';
$jsonFile = $explanationsDir . '/' . $exam . '.json';

// Check if file exists
if (!file_exists($jsonFile)) {
    echo json_encode([
        'exists' => false,
        'explanation' => null
    ]);
    exit;
}

// Read and parse JSON file
$jsonContent = file_get_contents($jsonFile);
$explanations = json_decode($jsonContent, true);

if (!is_array($explanations)) {
    echo json_encode([
        'exists' => false,
        'explanation' => null
    ]);
    exit;
}

// Construct key: questionNumber_answerLetter
$key = $questionNumber . '_' . $answerLetter;

// Check if explanation exists
if (isset($explanations[$key]) && !empty($explanations[$key])) {
    echo json_encode([
        'exists' => true,
        'explanation' => $explanations[$key]
    ]);
} else {
    echo json_encode([
        'exists' => false,
        'explanation' => null
    ]);
}
