<?php
require_once __DIR__ . '/../src/bootstrap.php';

if (!($_ENV['APP_DEBUG'] ?? false)) {
    header('HTTP/1.0 404 Not Found');
    exit('Debug page only available in development mode');
}

use App\Services\KeycloakService;
use App\Models\User;
use App\Middleware\AuthMiddleware;

$auth = new AuthMiddleware();
$userModel = new User();
$keycloakService = new KeycloakService();

echo "<h2>Auth Status Debug</h2>";
echo "<pre>";

echo "=== SESSION DATA ===\n";
if (isset($_SESSION['user'])) {
    echo "User in session: " . json_encode($_SESSION['user'], JSON_PRETTY_PRINT) . "\n";
} else {
    echo "No user in session\n";
}

echo "\n=== AUTHENTICATION STATUS ===\n";
echo "Is Authenticated: " . ($auth->isAuthenticated() ? 'YES' : 'NO') . "\n";
echo "Has Role: " . ($auth->hasRole() ? 'YES' : 'NO') . "\n";
echo "Is Admin: " . ($auth->isAdmin() ? 'YES' : 'NO') . "\n";

if ($auth->isAuthenticated()) {
    $user = $auth->getCurrentUser();
    echo "\n=== CURRENT USER ===\n";
    echo "ID: " . ($user['id'] ?? 'N/A') . "\n";
    echo "Username: " . ($user['username'] ?? 'N/A') . "\n";
    echo "Email: " . ($user['email'] ?? 'N/A') . "\n";
    echo "Is Active: " . ($user['is_active'] ? 'YES' : 'NO') . "\n";
    echo "Role ID: " . ($user['role_id'] ?? 'NULL') . "\n";
    echo "Role Name: " . ($user['role_name'] ?? 'NULL') . "\n";
    echo "Role Display: " . ($user['role_display_name'] ?? 'NULL') . "\n";
    
    echo "\n=== FRESH DATA FROM DB ===\n";
    $freshUser = $userModel->findById($user['id']);
    if ($freshUser) {
        echo "Fresh User Data: " . json_encode($freshUser, JSON_PRETTY_PRINT) . "\n";
        echo "Has Access: " . ($keycloakService->userHasAccess($freshUser) ? 'YES' : 'NO') . "\n";
    } else {
        echo "Could not fetch fresh user data\n";
    }
}

echo "</pre>";

echo '<br><a href="/">← Back to Home</a> | <a href="/auth/check-role-status" target="_blank">Test AJAX Endpoint</a>';
?>