<?php
require_once __DIR__ . '/../../config/config.php';
header('Content-Type: application/json');
ob_start();
try {
    $course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
    $semester = isset($_GET['semester']) ? (int)$_GET['semester'] : 0;
    if (!$course_id || !$semester) { 
        echo json_encode(['status'=>'error','message'=>'Missing params']); 
        exit; 
    }
    
    global $pdo;
    
    // First check if subjects table has semester column
    $checkCol = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'subjects' AND COLUMN_NAME = 'semester'");
    $checkCol->execute();
    $hasSemesterCol = ((int)$checkCol->fetchColumn()) > 0;
    
    if ($hasSemesterCol) {
        // Use semester column if it exists
        $stmt = $pdo->prepare("SELECT subject_id, subject_code, subject_name FROM subjects WHERE course_id=? AND semester=? ORDER BY subject_code");
        $stmt->execute([$course_id, $semester]);
    } else {
        // Fallback: get all subjects for course (no semester filtering)
        $stmt = $pdo->prepare("SELECT subject_id, subject_code, subject_name FROM subjects WHERE course_id=? ORDER BY subject_code");
        $stmt->execute([$course_id]);
    }
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['status'=>'success','data'=>$data]);
} catch (Throwable $e) {
    error_log('read_subjects error: '.$e->getMessage());
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
ob_end_flush();
?>


