<?php
/**
 * SSO Login Handler
 * Handles automatic login via SSO tokens
 */

require_once(__DIR__ . '/../libs/ApiKeyManager.php');
require_once(__DIR__ . '/../libs/network.php');
require_once(__DIR__ . '/../libs/security.php');
require_once(__DIR__ . '/../configs/config.php');

try {
    $token = $_GET['token'] ?? '';
    
    if (empty($token)) {
        showError('Invalid or missing SSO token');
        exit;
    }
    
    // Validate SSO token
    $apiKeyManager = new ApiKeyManager();
    $netInfo = new network_info();
    $ipAddress = $netInfo->get_client_ip();
    
    $validation = $apiKeyManager->validateSSOToken($token, $ipAddress);
    
    if (!$validation['success']) {
        showError('Invalid or expired SSO token: ' . $validation['error']);
        exit;
    }
    
    $username = $validation['username'];
    $redirectUrl = $validation['redirect_url'];
    
    // Verify user still exists
    require_once(__DIR__ . '/../libs/usermgmt.php');
    $userMgmt = new usermgmt();
    
    if (!$userMgmt->user_exists($username)) {
        showError('User account no longer exists');
        exit;
    }
    
    // Create session using the existing security system
    session_start();
    $security = new security_wrapper();
    
    // Create nonce using the same pattern as auto-prepend.php
    $nonce = $security->create_nonce($username, $ipAddress, NONCE_SALT);
    $_SESSION['nonce'] = $nonce;
    
    // Define constants that the application expects
    define('AUTH_USER', $username);
    define('HOME_DIR', $security->get_home_dir($username));
    
    // Log the SSO login
    error_log("SSO Login successful for user: $username from IP: $ipAddress");
    
    // Redirect to the intended page or dashboard
    $defaultRedirect = '/index.php';
    $finalUrl = $redirectUrl ?: $defaultRedirect;
    
    // Ensure redirect URL is safe (same domain)
    if ($redirectUrl && !isValidRedirectUrl($redirectUrl)) {
        $finalUrl = $defaultRedirect;
    }
    
    // Show success page with auto-redirect
    showSuccess($username, $finalUrl);
    
} catch (Exception $e) {
    error_log("SSO Login Error: " . $e->getMessage());
    showError('Login failed due to internal error');
}

function showError($message) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login Error - WHP</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body { background-color: #f8f9fa; }
            .error-container { 
                min-height: 100vh; 
                display: flex; 
                align-items: center; 
                justify-content: center; 
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <div class="card" style="width: 100%; max-width: 400px;">
                <div class="card-body text-center">
                    <i class="fas fa-exclamation-triangle text-warning mb-3" style="font-size: 3rem;"></i>
                    <h4 class="card-title">Login Failed</h4>
                    <p class="card-text"><?php echo htmlspecialchars($message); ?></p>
                    <a href="/login.php" class="btn btn-primary">Return to Login</a>
                </div>
            </div>
        </div>
        <script src="https://kit.fontawesome.com/your-fontawesome-kit.js"></script>
    </body>
    </html>
    <?php
}

function showSuccess($username, $redirectUrl) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login Successful - WHP</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <meta http-equiv="refresh" content="3;url=<?php echo htmlspecialchars($redirectUrl); ?>">
        <style>
            body { background-color: #f8f9fa; }
            .success-container { 
                min-height: 100vh; 
                display: flex; 
                align-items: center; 
                justify-content: center; 
            }
            .spinner-border { width: 1rem; height: 1rem; }
        </style>
    </head>
    <body>
        <div class="success-container">
            <div class="card" style="width: 100%; max-width: 400px;">
                <div class="card-body text-center">
                    <i class="fas fa-check-circle text-success mb-3" style="font-size: 3rem;"></i>
                    <h4 class="card-title">Login Successful</h4>
                    <p class="card-text">Welcome back, <?php echo htmlspecialchars($username); ?>!</p>
                    <p class="text-muted small">
                        <span class="spinner-border spinner-border-sm text-primary me-2" role="status"></span>
                        Redirecting you to the dashboard...
                    </p>
                    <div class="mt-3">
                        <a href="<?php echo htmlspecialchars($redirectUrl); ?>" class="btn btn-primary btn-sm">
                            Continue Now
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://kit.fontawesome.com/your-fontawesome-kit.js"></script>
        <script>
            // Auto-redirect after 3 seconds
            setTimeout(function() {
                window.location.href = '<?php echo addslashes($redirectUrl); ?>';
            }, 3000);
        </script>
    </body>
    </html>
    <?php
}

function isValidRedirectUrl($url) {
    // Parse the URL
    $parsed = parse_url($url);
    
    // If it's a relative URL (no host), it's safe
    if (!isset($parsed['host'])) {
        return true;
    }
    
    // Check if the host matches the current host
    $currentHost = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
    return $parsed['host'] === $currentHost;
}
?>