<?php
// ajax/get_subjects_by_class.php
include('../includes/db.php');
header('Content-Type: application/json');

$class_id = isset($_POST['class_id']) ? intval($_POST['class_id']) : 0;

if (!$class_id) {
    echo json_encode(['success' => false, 'message' => 'Class ID required']);
    exit;
}

// Get subjects assigned to this class from studentsub table
$query = "SELECT DISTINCT s.id, s.subject_name, s.subject_code, s.theory_full_marks, s.internal_full_marks
          FROM subjects s
          INNER JOIN studentsub ss ON s.subject_code = ss.sub1 OR s.subject_code = ss.sub2 OR 
                                      s.subject_code = ss.sub3 OR s.subject_code = ss.sub4 OR 
                                      s.subject_code = ss.sub5 OR s.subject_code = ss.sub6 OR 
                                      s.subject_code = ss.sub7
          WHERE ss.class_id = ? AND ss.status = 'active'
          ORDER BY s.subject_name";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $class_id);
$stmt->execute();
$result = $stmt->get_result();

$subjects = [];
while ($row = $result->fetch_assoc()) {
    $subjects[] = $row;
}

echo json_encode([
    'success' => true,
    'subjects' => $subjects
]);

$stmt->close();
$conn->close();
?>