<?php
include('../includes/db.php');

$class_id = isset($_GET['class_id']) ? intval($_GET['class_id']) : 0;
$section_ids = isset($_GET['section_ids']) ? $_GET['section_ids'] : [];
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
$academic_year = date('Y'); // Current academic year

// If section_ids is a string, convert to array
if (!is_array($section_ids) && !empty($section_ids)) {
    $section_ids = explode(',', $section_ids);
}

// First, get all subjects assigned to the class (with or without specific sections)
$query = "SELECT DISTINCT 
            s.id as subject_id, 
            s.subject_name, 
            s.subject_code, 
            s.theory_full_marks, 
            s.internal_full_marks,
            csm.section_id,
            esm.full_marks_theory as exam_full_marks_theory,
            esm.full_marks_internal as exam_full_marks_internal
          FROM subjects s
          INNER JOIN class_subject_mapping csm ON s.id = csm.subject_id
          LEFT JOIN exam_subject_marks esm ON 
            esm.subject_id = s.id AND 
            esm.exam_id = ? AND 
            esm.class_id = ?
          WHERE csm.class_id = ? 
          AND s.type = 'active";

// Add section filtering if specific sections are selected
if (!empty($section_ids)) {
    $placeholders = implode(',', array_fill(0, count($section_ids), '?'));
    $query .= " AND (csm.section_id IS NULL OR csm.section_id IN ($placeholders))";
} else {
    // If no sections selected, get subjects for all sections or subjects not tied to specific sections
    $query .= " AND (csm.section_id IS NULL OR csm.section_id IN (
                SELECT section_id FROM class_section WHERE class_id = ?
            ))";
}

$query .= " ORDER BY s.subject_name";

$stmt = $conn->prepare($query);

// Bind parameters
if (!empty($section_ids)) {
    $params = array_merge([$exam_id, $class_id, $class_id], $section_ids);
    $stmt->bind_param(str_repeat('i', count($params)), ...$params);
} else {
    $params = [$exam_id, $class_id, $class_id, $class_id];
    $stmt->bind_param("iiii", ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$subjects = [];
while ($row = $result->fetch_assoc()) {
    // Use exam-specific marks if available, otherwise use subject default marks
    $subject = [
        'subject_id' => $row['subject_id'],
        'subject_name' => $row['subject_name'],
        'subject_code' => $row['subject_code'],
        'full_marks_theory' => $row['exam_full_marks_theory'] ?: $row['theory_full_marks'] ?: 0,
        'full_marks_internal' => $row['exam_full_marks_internal'] ?: $row['internal_full_marks'] ?: 0,
        'full_marks_practical' => 0, // Add if you have practical marks
        'section_id' => $row['section_id']
    ];
    
    $subjects[] = $subject;
}

echo json_encode($subjects);
?>