<?php
require_once 'config/database.php';
require_once 'includes/subject_helpers.php';

// Get a sample class to test subject ordering
try {

    // Get a class ID that has students
    $stmt = $pdo->query('SELECT c.id, c.name, COUNT(s.id) as student_count FROM classes c JOIN students s ON c.id = s.class_id WHERE s.status = "active" GROUP BY c.id, c.name HAVING student_count > 0 LIMIT 1');
    $class = $stmt->fetch();
    if ($class) {
        $class_id = $class['id'];
        echo "Testing subject ordering for class ID: $class_id (Class: {$class['name']}, Students: {$class['student_count']})\n\n";
    } else {
        echo "No classes with active students found.\n";
        exit;
    }

        // Get subjects for this class
        $stmt = $pdo->prepare('
            SELECT DISTINCT sub.id, sub.name, sub.code,
                   COALESCE(cs.group_name, \'\') as group_name,
                   CASE WHEN cs.group_name IS NULL OR cs.group_name = \'\' THEN 1 ELSE 0 END as is_general
            FROM student_subjects ss
            JOIN subjects sub ON ss.subject_id = sub.id
            JOIN students s ON ss.student_id = s.id
            LEFT JOIN class_subjects cs ON cs.subject_id = sub.id AND cs.class_id = ?
            WHERE s.class_id = ?
        ');
        $stmt->execute([$class_id, $class_id]);
        $raw_subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo "Raw subjects found: " . count($raw_subjects) . "\n";
        foreach ($raw_subjects as $subject) {
            echo "- " . $subject['name'] . " (" . $subject['code'] . ")\n";
        }

        echo "\nAfter grouping:\n";
        $grouped_subjects = groupSubjectsWithCategory($raw_subjects, $pdo, $class_id, date('Y'), '');

        foreach ($grouped_subjects as $index => $subject) {
            $order = $index + 1;
            echo "$order. " . $subject['name'] . " (" . ($subject['code'] ?? 'N/A') . ")\n";
        }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
