<?php
include('../database/auth_check.php');
header('Content-Type: application/json');

$con = mysqli_connect('localhost','root','','WSAS');

if(!$con){
    echo json_encode([]);
    exit;
}

$year_level = (int)$_GET['year_level'];
$course_id = (int)$_GET['course_id'];

$year_map = [
    1 => '1st',
    2 => '2nd',
    3 => '3rd',
    4 => '4th'
];

$year_text = $year_map[$year_level];

$sy_query = mysqli_query($con,"SELECT semester FROM school_year WHERE is_active=1 LIMIT 1");
$sy = mysqli_fetch_assoc($sy_query);
$active_semester = ($sy['semester'] == '1st Semester') ? '1st' : '2nd';

$query = "
SELECT cs.subject_id, s.subject_code, s.subject_name
FROM course_subject cs
JOIN adminsubject s ON cs.subject_id = s.subject_id
WHERE cs.course_id = $course_id
AND cs.year_level = '$year_text'
AND cs.semester = '$active_semester'
";

$res = mysqli_query($con,$query);

$subjects = [];

while($row = mysqli_fetch_assoc($res)){
    $subjects[] = $row;
}

echo json_encode($subjects);