<?php
/**
 * Keycloak SSO Login - SIMPLIFIED VERSION FOR TESTING
 * 
 * This is a minimal version that doesn't require Vvveb bootstrap
 * Use this to test if the basic Keycloak connection works
 * 
 * Access: /admin/keycloak-login-simple.php
 */

// Suppress deprecation warnings
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);

// Prevent any output before redirect
if (ob_get_level()) {
    ob_clean();
}

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if Composer autoload exists
$vendorPath = dirname(__DIR__) . '/vendor/autoload.php';

if (!file_exists($vendorPath)) {
    die("ERROR: Composer autoload not found at: $vendorPath\nPlease run: composer install");
}

require_once $vendorPath;

use Jumbojett\OpenIDConnectClient;

// Configuration Keycloak
$keycloakUrl    = 'https://connect.slm-lab.net/realms/cercle';
$keycloakClient = 'page.slm-lab.net';
$keycloakSecret = 'IGFw1QWDs9xQ7OyRp6YM8VRgQxn09tFF';

// Redirect URL - MUST match exactly the one configured in Keycloak
$redirectUrl = 'https://www.slm-lab.net/admin/index.php?module=keycloak/callback';

try {
    // Create OpenID Connect client
    $oidc = new OpenIDConnectClient(
        $keycloakUrl,
        $keycloakClient,
        $keycloakSecret
    );
    
    $oidc->setRedirectURL($redirectUrl);
    $oidc->addScope(['openid', 'profile', 'email']);
    
    // Redirect user to Keycloak for authentication
    $oidc->authenticate();
    
} catch (\Exception $e) {
    // Show error
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Keycloak Authentication Error</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; text-align: center; }
            .error { color: #d32f2f; background: #ffebee; padding: 20px; border-radius: 4px; margin: 20px auto; max-width: 600px; }
            pre { text-align: left; background: #f5f5f5; padding: 10px; border-radius: 4px; }
        </style>
    </head>
    <body>
        <h1>Keycloak Authentication Error</h1>
        <div class="error">
            <p><strong>Failed to start Keycloak authentication:</strong></p>
            <p><?php echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'); ?></p>
        </div>
        <h3>Debug Information:</h3>
        <pre>
Vendor Path: <?php echo $vendorPath; ?>
Exists: <?php echo file_exists($vendorPath) ? 'YES' : 'NO'; ?>

Keycloak URL: <?php echo $keycloakUrl; ?>
Client ID: <?php echo $keycloakClient; ?>
Redirect URL: <?php echo $redirectUrl; ?>

PHP Version: <?php echo PHP_VERSION; ?>
Session Status: <?php echo session_status() === PHP_SESSION_ACTIVE ? 'ACTIVE' : 'INACTIVE'; ?>
        </pre>
        <p><a href="/admin/index.php?module=user/login">Return to login page</a></p>
    </body>
    </html>
    <?php
    exit;
}
