<?php

require_once '../../../config.php';

$conn = getDBConnection();



// Set header to return JSON

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



$response = ['success' => false, 'message' => '', 'counts' => []];



try {

    // Classes — primary: Class Management; fallback: students

    $classes = [];

    $classesResult = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");

    if ($classesResult) { while ($classRow = $classesResult->fetch_assoc()) $classes[] = $classRow['class_name']; }

    $classesResult2 = $conn->query("SELECT DISTINCT class FROM students WHERE status = 'active' AND class IS NOT NULL ORDER BY class");

    if ($classesResult2) { while ($classRow = $classesResult2->fetch_assoc()) { if (!in_array($classRow['class'], $classes)) $classes[] = $classRow['class']; } }

    sort($classes);

    

    // For each class, get the subject count

    $counts = [];

    foreach ($classes as $class) {

        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM class_subjects WHERE class_name = ?");

        $stmt->bind_param("s", $class);

        $stmt->execute();

        $result = $stmt->get_result();

        $row = $result->fetch_assoc();

        $counts[$class] = intval($row['count'] ?? 0);

        $stmt->close();

    }

    

    // Also get total active subjects count for reference

    $totalSubjectsQuery = "SELECT COUNT(*) as count FROM subjects WHERE active = 'yes'";

    $totalResult = $conn->query($totalSubjectsQuery);

    $totalRow = $totalResult->fetch_assoc();

    $counts['total_active'] = intval($totalRow['count'] ?? 0);

    

    $response['success'] = true;

    $response['counts'] = $counts;

    

} catch (Exception $e) {

    $response['message'] = 'Error: ' . $e->getMessage();

    error_log('get_subject_counts.php error: ' . $e->getMessage());

}



$conn->close();

echo json_encode($response);

exit;