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

require_teacher();

$user_id = $_SESSION['user_id'];

echo "<h2>Basic Leave Test</h2>";
echo "<p>User ID: $user_id</p>";

// Test database connection
try {
    $stmt = $pdo->query("SELECT 1");
    echo "<p style='color: green;'>✓ Database connection OK</p>";
} catch (Exception $e) {
    echo "<p style='color: red;'>✗ Database connection failed: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Test teacher info
try {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $teacher = $stmt->fetch();

    if ($teacher) {
        echo "<p style='color: green;'>✓ Teacher found: " . htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']) . "</p>";
        echo "<p>Teacher ID: " . $teacher['id'] . "</p>";

        // Test simple leave query
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM teacher_leaves WHERE teacher_id = ?");
        $stmt->execute([$teacher['id']]);
        $count = $stmt->fetch()['count'];
        echo "<p style='color: green;'>✓ Leave applications count: $count</p>";

        // Test with status filter
        $stmt = $pdo->prepare("SELECT status, COUNT(*) as count FROM teacher_leaves WHERE teacher_id = ? GROUP BY status");
        $stmt->execute([$teacher['id']]);
        $stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo "<h3>Leave Status Breakdown:</h3><ul>";
        foreach ($stats as $stat) {
            echo "<li>{$stat['status']}: {$stat['count']}</li>";
        }
        echo "</ul>";

    } else {
        echo "<p style='color: red;'>✗ Teacher not found for user_id: $user_id</p>";
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

echo "<hr>";
echo "<p><a href='leave_application.php'>← Back to Leave Application</a></p>";
?>
