<?php
// ajax/get_questions.php
require '../config.php';
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true) ?: $_GET;
$class = $input['class'] ?? null;
$session = $input['session'] ?? null;
$term = $input['term'] ?? null;
$type = $input['type'] ?? null;
$subject = $input['subject'] ?? null;

try {
  $sql = "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 1=1";
  $params = [];
  if ($class) { $sql .= " AND q.student_class = :class"; $params[':class'] = $class; }
  if ($session) { $sql .= " AND q.session_id = :session"; $params[':session'] = $session; }
  if ($term) { $sql .= " AND q.term_id = :term"; $params[':term'] = $term; }
  if ($type) { $sql .= " AND q.type = :type"; $params[':type'] = $type; }
  if ($subject) { $sql .= " AND q.subject_id = :subject"; $params[':subject'] = $subject; }
  $sql .= " ORDER BY q.id DESC LIMIT 500";
  $stmt = $dbh->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  // For options field, return as raw string (JSON) so frontend can show
  echo json_encode(['success'=>true, 'data'=>$rows]);
} catch(Exception $e){
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
