<?php
// Enable error reporting to see what's causing the 500 error
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>Debugging teachers/leave_application.php</h2>";

// Check if database connection works
echo "<h3>1. Testing database connection...</h3>";
require_once 'config/database.php';

if (isset($pdo)) {
    echo "<p style='color: green;'>✓ Database connection successful</p>";
} else {
    echo "<p style='color: red;'>✗ Database connection failed</p>";
    exit;
}

// Check if teachers table exists
echo "<h3>2. Checking if teachers table exists...</h3>";
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'teachers'");
    if ($stmt->rowCount() > 0) {
        echo "<p style='color: green;'>✓ teachers table exists</p>";
        
        // Test the query that gets teacher info
        echo "<h3>3. Testing teacher info query...</h3>";
        session_start();
        if (isset($_SESSION['user_id'])) {
            echo "<p>Session user_id: " . $_SESSION['user_id'] . "</p>";
            echo "<p>Session user_role: " . ($_SESSION['user_role'] ?? 'not set') . "</p>";
            
            try {
                $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
                $stmt->execute([$_SESSION['user_id']]);
                $teacher_info = $stmt->fetch();
                
                if ($teacher_info) {
                    echo "<p style='color: green;'>✓ Teacher info found: " . $teacher_info['first_name'] . " " . $teacher_info['last_name'] . "</p>";
                } else {
                    echo "<p style='color: orange;'>Teacher info not found for user_id: " . $_SESSION['user_id'] . "</p>";
                    echo "<p>This might be the issue - the user might not have a corresponding record in the teachers table.</p>";
                }
            } catch (Exception $e) {
                echo "<p style='color: red;'>Error querying teacher info: " . $e->getMessage() . "</p>";
            }
        } else {
            echo "<p style='color: red;'>✗ No user is logged in - this page requires authentication</p>";
        }
    } else {
        echo "<p style='color: red;'>✗ teachers table does not exist</p>";
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>Error checking teachers table: " . $e->getMessage() . "</p>";
}

// Check if teacher_leaves table exists
echo "<h3>4. Checking if teacher_leaves table exists...</h3>";
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'teacher_leaves'");
    if ($stmt->rowCount() > 0) {
        echo "<p style='color: green;'>✓ teacher_leaves table exists</p>";
    } else {
        echo "<p style='color: red;'>✗ teacher_leaves table does not exist</p>";
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>Error checking teacher_leaves table: " . $e->getMessage() . "</p>";
}
?>