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

echo "<h2>Fixed Session Filter Test</h2>";

// Test the corrected approach
try {
    // Get some sample data first
    $stmt = $pdo->query("SELECT DISTINCT name FROM classes ORDER BY name LIMIT 5");
    $sample_classes = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    echo "<h3>Sample Classes:</h3>";
    foreach ($sample_classes as $class) {
        echo "- " . htmlspecialchars($class) . "<br>";
    }
    
    // Test admission dates
    echo "<h3>Admission Date Test:</h3>";
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count, YEAR(admission_date) as year FROM students WHERE admission_date IS NOT NULL GROUP BY YEAR(admission_date) ORDER BY year DESC LIMIT 5");
        $admission_stats = $stmt->fetchAll();
        
        if (!empty($admission_stats)) {
            echo "Admission years found:<br>";
            foreach ($admission_stats as $stat) {
                echo "- Year " . $stat['year'] . ": " . $stat['count'] . " students<br>";
            }
        } else {
            echo "No admission dates found<br>";
        }
    } catch (Exception $e) {
        echo "Admission date query failed: " . $e->getMessage() . "<br>";
    }
    
    // Test the actual session filtering approach
    echo "<h3>Session Filter Test:</h3>";
    
    // Try a common year like 2024
    $test_year = '2024';
    echo "Testing with year: " . $test_year . "<br>";
    
    $sql = "SELECT COUNT(*) as count FROM students WHERE (class_id IN (SELECT id FROM classes WHERE name LIKE ?) OR YEAR(admission_date) = ?)";
    $params = ['%' . $test_year . '%', $test_year];
    
    echo "Query: " . $sql . "<br>";
    echo "Parameters: " . json_encode($params) . "<br>";
    
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $result = $stmt->fetch();
        echo "Students found: " . $result['count'] . "<br>";
    } catch (Exception $e) {
        echo "Query execution failed: " . $e->getMessage() . "<br>";
    }
    
    // Test class name pattern matching
    echo "<h3>Class Name Pattern Matching:</h3>";
    foreach ($sample_classes as $class_name) {
        if (preg_match('/\d{4}/', $class_name, $matches)) {
            echo "Class '" . htmlspecialchars($class_name) . "' contains year: " . $matches[0] . "<br>";
        }
    }
    
} catch (Exception $e) {
    echo "General error: " . $e->getMessage() . "<br>";
}
?>