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

try {
    echo "Testing Merit Position with GPA 0.00 Exclusion\n\n";

    // Test with a class
    $class_id = 10;
    $session = '2025';
    $exam_type = 'final';

    // Get all students in class 10
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, roll_number FROM students WHERE class_id = ? AND status = 'active' ORDER BY roll_number LIMIT 10");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();

    echo "Sample students from Class 10:\n";
    foreach ($students as $student) {
        echo "- Roll {$student['roll_number']}: {$student['first_name']} {$student['last_name']} (ID: {$student['id']})\n";
    }
    echo "\n";

    // Simulate merit data (simplified)
    $student_merit_data = [];

    foreach ($students as $student) {
        $sid = $student['id'];

        // Get student results count to determine if GPA should be 0
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM results WHERE student_id = ? AND session = ? AND exam_type = ?");
        $stmt->execute([$sid, $session, $exam_type]);
        $result_count = $stmt->fetch()['count'];

        if ($result_count == 0) {
            $student_merit_data[$sid] = [
                'gpa' => 0.00,
                'total_marks' => 0,
                'student' => $student
            ];
        } else {
            // Simplified GPA calculation (just for testing)
            $student_merit_data[$sid] = [
                'gpa' => rand(200, 500) / 100, // Random GPA between 2.00-5.00
                'total_marks' => rand(800, 1200),
                'student' => $student
            ];
        }
    }

    // Sort by GPA first, then by total marks
    uasort($student_merit_data, function($a, $b) {
        $gpa_compare = $b['gpa'] <=> $a['gpa'];
        if ($gpa_compare !== 0) {
            return $gpa_compare;
        }
        return $b['total_marks'] <=> $a['total_marks'];
    });

    // Create merit order excluding GPA 0.00 students
    $merit_order = [];
    $position = 1;
    foreach ($student_merit_data as $sid => $data) {
        if ($data['gpa'] > 0.00) {
            $merit_order[$sid] = $position++;
        }
    }

    // Display results
    echo "Merit Position Results (GPA 0.00 students excluded):\n";
    echo "Student | GPA | Merit Position\n";
    echo "--------|-----|---------------\n";

    foreach ($students as $student) {
        $sid = $student['id'];
        $data = $student_merit_data[$sid];
        $merit_pos = isset($merit_order[$sid]) ? $merit_order[$sid] : 'N/A';

        printf("%-30s | %-3.2f | %-10s\n",
            $student['first_name'] . ' ' . $student['last_name'],
            $data['gpa'],
            $merit_pos
        );
    }

} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}
?>
