<?php
// ajax/update_question.php
require '../config.php';
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
$id = intval($input['id'] ?? 0);
if (!$id){ echo json_encode(['success'=>false,'message'=>'Missing id']); exit; }
$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 (!$question_text) { echo json_encode(['success'=>false,'message'=>'Question text required']); exit; }
$options = null;
if ($type === 'objective' && $options_raw !== ''){
  $arr = array_filter(array_map('trim', explode(',', $options_raw)));
  $options = json_encode(array_values($arr));
} else {
  $options = null;
}

try {
  $sql = "UPDATE questions SET type=:type, set_time_minutes=:set_time_minutes, question_text=:question_text, options=:options, correct_answer=:correct_answer WHERE id=:id";
  $stmt = $dbh->prepare($sql);
  $stmt->execute([
    ':type'=>$type,
    ':set_time_minutes'=>$set_time_minutes,
    ':question_text'=>$question_text,
    ':options'=>$options,
    ':correct_answer'=>$correct_answer,
    ':id'=>$id
  ]);
  echo json_encode(['success'=>true]);
} catch(Exception $e){
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
