<?php
// ajax/save_question.php
require '../config.php';
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) { echo json_encode(['success'=>false,'message'=>'No input']); exit; }

// sanitize & validate
$teacher_id = intval($input['teacher_id'] ?? 0);
$student_class = trim($input['student_class'] ?? '');
$session_id = intval($input['session_id'] ?? 0);
$term_id = intval($input['term_id'] ?? 0);
$subject_id = intval($input['subject_id'] ?? 0);
$type = in_array($input['type'] ?? '', ['objective','fill','theory']) ? $input['type'] : null;
$set_time_minutes = intval($input['set_time_minutes'] ?? 0);
$question_text = trim($input['question_text'] ?? '');
$options_raw = trim($input['options'] ?? '');
$correct_answer = trim($input['correct_answer'] ?? '');

if (!$student_class || !$session_id || !$term_id || !$question_text){
  echo json_encode(['success'=>false,'message'=>'Missing required fields.']); exit;
}

// For objective, ensure options are stored as JSON array
$options = null;
if ($type === 'objective'){
  $arr = array_filter(array_map('trim', explode(',', $options_raw)));
  // store as JSON string in `options` field
  $options = json_encode(array_values($arr));
} else {
  $options = null;
}

try {
  $sql = "INSERT INTO questions (teacher_id, student_class, term_id, session_id, subject_id, type, question_text, options, correct_answer, set_time_minutes)
          VALUES (:teacher_id, :student_class, :term_id, :session_id, :subject_id, :type, :question_text, :options, :correct_answer, :set_time_minutes)";
  $stmt = $dbh->prepare($sql);
  $stmt->execute([
    ':teacher_id'=>$teacher_id,
    ':student_class'=>$student_class,
    ':term_id'=>$term_id,
    ':session_id'=>$session_id,
    ':subject_id'=>$subject_id ?: null,
    ':type'=>$type,
    ':question_text'=>$question_text,
    ':options'=>$options,
    ':correct_answer'=>$correct_answer,
    ':set_time_minutes'=>$set_time_minutes
  ]);
  echo json_encode(['success'=>true,'id'=>$dbh->lastInsertId()]);
} catch (Exception $e){
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
