<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Minimal debug instrumentation for endpoint hit tracing.
$logsDir = __DIR__ . '/../../logs';
$debugLogFile = $logsDir . '/debug_update.txt';
if (!is_dir($logsDir)) {
    @mkdir($logsDir, 0775, true);
}
@file_put_contents(
    $debugLogFile,
    '[' . date('Y-m-d H:i:s') . '] update_question_content.php called' . PHP_EOL,
    FILE_APPEND | LOCK_EX
);

require_once __DIR__ . '/../config/database.php';

$question_id = $_POST['question_id'] ?? '';
$title = $_POST['title'] ?? '';
$stem = $_POST['stem'] ?? '';
$option_a = $_POST['option_a'] ?? '';
$option_b = $_POST['option_b'] ?? '';
$option_c = $_POST['option_c'] ?? '';
$option_d = $_POST['option_d'] ?? '';
$option_e = $_POST['option_e'] ?? '';
$correct_answer_letter = $_POST['correct_answer_letter'] ?? '';

if (empty($question_id)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Missing question ID.'
    ]);
    exit;
}

$correct_answer = '';

switch ($correct_answer_letter) {
    case 'A':
        $correct_answer = $option_a;
        break;
    case 'B':
        $correct_answer = $option_b;
        break;
    case 'C':
        $correct_answer = $option_c;
        break;
    case 'D':
        $correct_answer = $option_d;
        break;
    case 'E':
        $correct_answer = $option_e;
        break;
}

try {
    $sql = "UPDATE questions SET
    title = :title,
    stem = :stem,
    lead_in = :lead_in,
    option_a = :option_a,
    option_b = :option_b,
    option_c = :option_c,
    option_d = :option_d,
    option_e = :option_e,
    correct_answer_letter = :correct_answer_letter,
    correct_answer = :correct_answer,
    justification = :justification
WHERE id = :question_id";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    'title' => $_POST['title'] ?? '',
    'stem' => $_POST['stem'] ?? '',
    'lead_in' => $_POST['lead_in'] ?? '',
    'option_a' => $option_a,
    'option_b' => $option_b,
    'option_c' => $option_c,
    'option_d' => $option_d,
    'option_e' => $option_e,
    'correct_answer_letter' => $correct_answer_letter,
    'correct_answer' => $correct_answer,
    'justification' => $_POST['justification'] ?? '',
    'question_id' => $question_id
]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Question updated successfully.'
    ]);
} catch (Throwable $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}