<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false, 'message'=>'Database connection failed']); exit; }

$id = (int) ($_POST['id'] ?? 0);
$subjectId = (int) ($_POST['subject_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
$term = trim((string) ($_POST['term'] ?? ''));
$academicYear = trim((string) ($_POST['academic_year'] ?? ''));
$questionType = trim((string) ($_POST['question_type'] ?? 'mcq'));
$question = trim((string) ($_POST['question'] ?? ''));
$optionA = trim((string) ($_POST['option_a'] ?? ''));
$optionB = trim((string) ($_POST['option_b'] ?? ''));
$optionC = trim((string) ($_POST['option_c'] ?? ''));
$optionD = trim((string) ($_POST['option_d'] ?? ''));
$correctAnswer = trim((string) ($_POST['correct_answer'] ?? ''));
$marks = max(1, (int) ($_POST['marks'] ?? 1));
$difficulty = trim((string) ($_POST['difficulty'] ?? 'medium'));
$diagramRequired = (int) (!empty($_POST['diagram_required']));
$diagramType = trim((string) ($_POST['diagram_type'] ?? ''));
$diagramSpec = trim((string) ($_POST['diagram_spec'] ?? ''));
$diagramSpec = $diagramSpec !== '' ? $diagramSpec : null;

if ($subjectId <= 0 || $className === '' || $question === '') {
    echo json_encode(['success'=>false, 'message'=>'Subject, class and question are required']); exit;
}
if ($questionType === 'mcq' && $correctAnswer === '') {
    echo json_encode(['success'=>false, 'message'=>'MCQ questions must have a correct answer']); exit;
}
if ($questionType !== 'mcq') {
    $optionA = $optionB = $optionC = $optionD = '';
    $correctAnswer = '';
}

if ($id > 0) {
    $stmt = $conn->prepare(
        "UPDATE exam_questions
         SET subject_id=?, class_name=?, term=?, academic_year=?, question_type=?, question=?, option_a=?, option_b=?, option_c=?, option_d=?, correct_answer=?, marks=?, difficulty=?, diagram_required=?, diagram_type=?, diagram_spec=?
         WHERE id=?"
    );
    $stmt->bind_param('isssssssssssisssi', $subjectId, $className, $term, $academicYear, $questionType, $question, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $marks, $difficulty, $diagramRequired, $diagramType, $diagramSpec, $id);
    $stmt->execute();
    $stmt->close();
    echo json_encode(['success'=>true, 'message'=>'Question updated successfully', 'question'=>['id'=>$id]]);
    exit;
}

$userId = (int) $_SESSION['user_id'];
$stmt = $conn->prepare(
    "INSERT INTO exam_questions
      (subject_id, class_name, term, academic_year, question_type, question, option_a, option_b, option_c, option_d, correct_answer, marks, difficulty, diagram_required, diagram_type, diagram_spec, created_by)
     VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
);
$stmt->bind_param('isssssssssssisssi', $subjectId, $className, $term, $academicYear, $questionType, $question, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $marks, $difficulty, $diagramRequired, $diagramType, $diagramSpec, $userId);
$stmt->execute();
$newId = (int) $stmt->insert_id;
$stmt->close();
echo json_encode(['success'=>true, 'message'=>'Question saved successfully', 'question'=>['id'=>$newId]]);
