<?php
session_start();
header('Content-Type: application/json');

require_once '../../config/database.php';
require_once '../../includes/access_control.php';

// Check if user is logged in and is a teacher
require_teacher();

try {
    $exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    // Get subject_id from exam
    $subject_id = 0;
    if ($exam_id > 0) {
        $stmt = $pdo->prepare("SELECT subject_id FROM exam_subjects WHERE exam_id = ? LIMIT 1");
        $stmt->execute([$exam_id]);
        $exam_subject = $stmt->fetch();
        if ($exam_subject) {
            $subject_id = $exam_subject['subject_id'];
        }
    }
    
    // Build query
    $sql = "SELECT qb.*, s.name as subject_name FROM question_bank qb JOIN subjects s ON qb.subject_id = s.id WHERE 1=1";
    $params = [];
    
    // Filter by subject if available
    if ($subject_id > 0) {
        $sql .= " AND qb.subject_id = ?";
        $params[] = $subject_id;
    }
    
    // Add search filter
    if (!empty($search)) {
        $sql .= " AND (qb.question_text LIKE ? OR qb.chapter_topic LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $sql .= " ORDER BY qb.created_at DESC LIMIT 50";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $questions = $stmt->fetchAll();
    
    echo json_encode(['success' => true, 'questions' => $questions]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}