<?php
/**
 * Save Explanation API Endpoint
 * Saves explanations to JSON files for caching
 */

// Set headers for JSON response and CORS
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get request body
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON data']);
    exit;
}

// Validate required fields
$required = ['exam', 'questionNumber', 'answerLetter', 'explanation'];
foreach ($required as $field) {
    if (!isset($data[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "Missing required field: $field"]);
        exit;
    }
}

// Sanitize inputs
$exam = basename($data['exam']); // Remove any path components
$exam = preg_replace('/[^a-zA-Z0-9._-]/', '', $exam); // Remove invalid characters
$questionNumber = preg_replace('/[^0-9]/', '', (string)$data['questionNumber']); // Only numbers
$answerLetter = strtoupper(preg_replace('/[^A-D]/', '', $data['answerLetter'])); // Only A-D
$explanation = trim($data['explanation']);

if (empty($exam) || empty($questionNumber) || empty($answerLetter) || empty($explanation)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid or empty parameters']);
    exit;
}

// Construct JSON file path
$explanationsDir = dirname(__DIR__) . '/explanations';

// Create directory if it doesn't exist
if (!is_dir($explanationsDir)) {
    if (!mkdir($explanationsDir, 0755, true)) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create explanations directory']);
        exit;
    }
}

$jsonFile = $explanationsDir . '/' . $exam . '.json';

// Read existing explanations or create new array
$explanations = [];
if (file_exists($jsonFile)) {
    $jsonContent = file_get_contents($jsonFile);
    $explanations = json_decode($jsonContent, true);
    if (!is_array($explanations)) {
        $explanations = [];
    }
}

// Construct key: questionNumber_answerLetter
$key = $questionNumber . '_' . $answerLetter;

// Save/update explanation
$explanations[$key] = $explanation;

// Write back to file
$jsonContent = json_encode($explanations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if (file_put_contents($jsonFile, $jsonContent) === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save explanation']);
    exit;
}

// Return success
echo json_encode([
    'success' => true,
    'message' => 'Explanation saved successfully'
]);
