<?php
//ajax/get_subjects_by_class_section.php

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

header('Content-Type: application/json');

$response = array('success' => false, 'subjects' => array(), 'error' => '');

if(isset($_GET['class_id']) && !empty($_GET['class_id']) && isset($_GET['section_id']) && !empty($_GET['section_id'])) {
    $class_id = intval($_GET['class_id']);
    $section_id = intval($_GET['section_id']);
    
    // Debug: Log the request
    error_log("Subject request - Class: $class_id, Section: $section_id");
    
    // Query to get subjects
    $query = "SELECT DISTINCT s.id as subject_id, s.subject_code, s.subject_name, 
                     s.theory_full_marks, s.internal_full_marks, s.type
              FROM class_subject_mapping csm
              INNER JOIN subjects s ON csm.subject_id = s.id
              WHERE csm.class_id = ? 
                AND (csm.section_id = ? OR csm.section_id IS NULL)
                AND s.status = '1'
              ORDER BY s.subject_name";
    
    $stmt = $conn->prepare($query);
    
    if($stmt) {
        $stmt->bind_param("ii", $class_id, $section_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $response['subjects'][] = array(
                    'subject_id' => $row['subject_id'],
                    'subject_code' => $row['subject_code'],
                    'subject_name' => $row['subject_name'],
                    'theory_full_marks' => $row['theory_full_marks'],
                    'internal_full_marks' => $row['internal_full_marks'],
                    'type' => $row['type']
                );
            }
            $response['success'] = true;
            $response['count'] = count($response['subjects']);
        } else {
            $response['error'] = "No subjects found for this class-section combination";
            $response['success'] = false;
        }
        
        $stmt->close();
    } else {
        $response['error'] = "Database query preparation failed: " . $conn->error;
    }
} else {
    $response['error'] = "Missing required parameters: class_id and section_id";
}

// Make sure we're sending valid JSON
echo json_encode($response, JSON_PRETTY_PRINT);
?>