<?php
session_start();
require_once '../config/database.php';

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>Database Connection Test</h2>";

try {
    // Test database connection
    echo "<p>Testing database connection...</p>";
    
    // Check if we can connect
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<p style='color: green;'>✓ Database connection successful</p>";
    
    // Check if exams table exists
    echo "<h3>Checking tables...</h3>";
    
    $tables = ['exams', 'exam_subjects', 'results'];
    foreach ($tables as $table) {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM `$table`");
            $stmt->execute();
            $count = $stmt->fetchColumn();
            echo "<p style='color: green;'>✓ Table '$table' exists with $count records</p>";
        } catch (PDOException $e) {
            echo "<p style='color: red;'>✗ Error accessing table '$table': " . htmlspecialchars($e->getMessage()) . "</p>";
        }
    }
    
    // List some exams
    echo "<h3>Exam Records:</h3>";
    try {
        $stmt = $pdo->prepare("SELECT * FROM exams ORDER BY id LIMIT 10");
        $stmt->execute();
        $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($exams)) {
            echo "<p>No exams found in database</p>";
        } else {
            echo "<table border='1' cellpadding='5' cellspacing='0'>";
            echo "<tr><th>ID</th><th>Name</th><th>Date</th><th>Status</th></tr>";
            foreach ($exams as $exam) {
                echo "<tr>";
                echo "<td>" . htmlspecialchars($exam['id']) . "</td>";
                echo "<td>" . htmlspecialchars($exam['name']) . "</td>";
                echo "<td>" . htmlspecialchars($exam['date']) . "</td>";
                echo "<td>" . htmlspecialchars($exam['status']) . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
    } catch (PDOException $e) {
        echo "<p style='color: red;'>Error fetching exams: " . htmlspecialchars($e->getMessage()) . "</p>";
    }
    
} catch (PDOException $e) {
    echo "<p style='color: red;'>Database connection failed: " . htmlspecialchars($e->getMessage()) . "</p>";
}

echo "<p><a href='routine.php'>Go to Routine Page</a></p>";
?>