<?php
// ajax/get_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; }
try {
  $stmt = $dbh->prepare("SELECT q.*, t.term_name, s.session_year FROM questions q LEFT JOIN terms t ON q.term_id=t.id LEFT JOIN sessions s ON q.session_id=s.id WHERE q.id=:id LIMIT 1");
  $stmt->execute([':id'=>$id]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$row) { echo json_encode(['success'=>false,'message'=>'Not found']); exit; }
  // if options JSON, decode so frontend sees textual form (comma-separated)
  if (!empty($row['options'])){
    $opts = json_decode($row['options'], true);
    if (is_array($opts)) $row['options'] = implode(', ', $opts);
  }
  echo json_encode(['success'=>true,'data'=>$row]);
} catch(Exception $e){
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
