<?php
/**
 * Estreka Ratsaklubi - Väljalogimine
 * Turvaline sessiooni lõpetamine ja visuaalne kinnitus
 * 🆕 PARANDATUD: Näitab visuaalset kinnitust
 */

require_once 'config/config.php';
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';

// Turvalisuse headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$logout_successful = false;
$logout_reason = '';
$auto_logout = false;

// Kontrolli kas kasutaja on sisse logitud
if (isLoggedIn()) {
    $user_id = $_SESSION['user_id'];
    $username = $_SESSION['username'] ?? $_SESSION['user_name'] ?? 'unknown';
    
    // Kontrolli auto-logout parameetreid
    $auto_logout = isset($_GET['auto']) && $_GET['auto'] === '1';
    $logout_reason = $_GET['reason'] ?? '';
    
    // Logi väljalogimine
    try {
        $log_details = $auto_logout ? 
            "Auto-logout: {$logout_reason}" : 
            "Manual logout";
        logActivity($user_id, 'logout', $log_details);
    } catch (Exception $e) {
        error_log('Logout logging error: ' . $e->getMessage());
    }
    
    // Kustuta kõik sessiooni andmed
    $_SESSION = array();
    
    // Kustuta sessiooni küpsis kui see eksisteerib
    if (ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
        );
    }
    
    // Hävita sessioon
    session_destroy();
    
    $logout_successful = true;
}

// Kui ei toimunud logout'i, suuna avalehele kohe
if (!$logout_successful && !isset($_GET['show'])) {
    header('Location: ' . url());
    exit;
}

// NÄITA VISUAALSET LOGOUT LEHTE
$page_title = 'Välja logitud';
$page_description = 'Oled edukalt süsteemist välja logitud';
$body_class = 'logout-page';

// Automaatse suunamise aeg (sekundites)
$redirect_delay = $auto_logout ? 3 : 5;

?>
<!DOCTYPE html>
<html lang="et">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Estreka Ratsaklubi</title>
    <meta name="description" content="<?php echo $page_description; ?>">
    
    <!-- CSS -->
    <link rel="stylesheet" href="<?php echo url('assets/css/style.css'); ?>">
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <link rel="stylesheet" href="<?php echo url('assets/css/icons.css'); ?>">
    
    <!-- Auto-redirect -->
    <meta http-equiv="refresh" content="<?php echo $redirect_delay; ?>;url=<?php echo url(); ?>">
    
    <style>
    /* Logout page specific styles */
    .logout-page {
        background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0;
        padding: var(--spacing-4);
    }
    
    .logout-container {
        background: white;
        border-radius: var(--radius-2xl);
        box-shadow: var(--shadow-xl);
        padding: var(--spacing-8);
        text-align: center;
        max-width: 500px;
        width: 100%;
        border: 1px solid var(--gray-200);
    }
    
    .logout-icon {
        width: 80px;
        height: 80px;
        background: linear-gradient(135deg, var(--success-color), #059669);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5rem;
        margin: 0 auto var(--spacing-6);
        animation: successPulse 2s ease-in-out infinite;
    }
    
    .logout-icon.auto-logout {
        background: linear-gradient(135deg, var(--warning-color), #d97706);
    }
    
    @keyframes successPulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.05); }
    }
    
    .logout-title {
        font-size: var(--font-size-3xl);
        font-weight: 700;
        color: var(--gray-900);
        margin-bottom: var(--spacing-4);
    }
    
    .logout-message {
        font-size: var(--font-size-lg);
        color: var(--gray-600);
        margin-bottom: var(--spacing-6);
        line-height: 1.6;
    }
    
    .logout-reason {
        background: var(--gray-50);
        border: 1px solid var(--gray-200);
        border-radius: var(--radius-lg);
        padding: var(--spacing-4);
        margin-bottom: var(--spacing-6);
        font-size: var(--font-size-sm);
        color: var(--gray-700);
    }
    
    .logout-reason.auto {
        background: color-mix(in srgb, var(--warning-color) 5%, transparent);
        border-color: color-mix(in srgb, var(--warning-color) 20%, transparent);
        color: #92400e;
    }
    
    .logout-actions {
        display: flex;
        gap: var(--spacing-4);
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .btn {
        display: inline-flex;
        align-items: center;
        gap: var(--spacing-2);
        padding: var(--spacing-3) var(--spacing-6);
        border-radius: var(--radius-lg);
        font-weight: 600;
        text-decoration: none;
        transition: all var(--transition-fast);
        border: 2px solid transparent;
    }
    
    .btn-primary {
        background: var(--primary-color);
        color: white;
    }
    
    .btn-primary:hover {
        background: var(--primary-dark);
        transform: translateY(-1px);
        box-shadow: var(--shadow-lg);
    }
    
    .btn-secondary {
        background: white;
        color: var(--gray-700);
        border-color: var(--gray-300);
    }
    
    .btn-secondary:hover {
        background: var(--gray-50);
        border-color: var(--gray-400);
    }
    
    .redirect-notice {
        margin-top: var(--spacing-6);
        padding: var(--spacing-4);
        background: var(--gray-50);
        border-radius: var(--radius);
        font-size: var(--font-size-sm);
        color: var(--gray-600);
    }
    
    .countdown {
        font-weight: 600;
        color: var(--primary-color);
    }
    
    /* Responsive */
    @media (max-width: 640px) {
        .logout-container {
            padding: var(--spacing-6);
        }
        
        .logout-actions {
            flex-direction: column;
        }
        
        .btn {
            width: 100%;
            justify-content: center;
        }
    }
    </style>
</head>
<body class="logout-page">
    <div class="logout-container">
        <!-- Success/Auto-logout Icon -->
        <div class="logout-icon <?php echo $auto_logout ? 'auto-logout' : ''; ?>">
            <?php if ($auto_logout): ?>
                🔒
            <?php else: ?>
                ✅
            <?php endif; ?>
        </div>
        
        <!-- Title -->
        <h1 class="logout-title">
            <?php if ($auto_logout): ?>
                Automaatne väljalogimine
            <?php else: ?>
                Edukalt välja logitud
            <?php endif; ?>
        </h1>
        
        <!-- Message -->
        <div class="logout-message">
            <?php if ($auto_logout): ?>
                Sinu sessioon aegus passiivsuse tõttu ja sind logiti automaatselt välja turvalisuse kaalutlustel.
            <?php else: ?>
                Oled süsteemist edukalt välja logitud. Sinu sessioon on turvaliselt lõpetatud.
            <?php endif; ?>
        </div>
        
        <!-- Reason (if auto-logout) -->
        <?php if ($auto_logout && $logout_reason): ?>
            <div class="logout-reason auto">
                <strong>🔍 Põhjus:</strong>
                <?php 
                switch ($logout_reason) {
                    case 'timeout':
                        echo 'Passiivsuse timeout (30 minutit)';
                        break;
                    case 'server':
                        echo 'Serveri poolt lõpetatud (kasutaja deaktiveeritud või sessioon kehtetu)';
                        break;
                    default:
                        echo htmlspecialchars($logout_reason);
                }
                ?>
            </div>
        <?php endif; ?>
        
        <!-- Actions -->
        <div class="logout-actions">
            <a href="<?php echo url('login.php'); ?>" class="btn btn-primary">
                <i class="icon-log-in"></i>
                <span>Logi uuesti sisse</span>
            </a>
            
            <a href="<?php echo url(); ?>" class="btn btn-secondary">
                <i class="icon-home"></i>
                <span>Avalehele</span>
            </a>
        </div>
        
        <!-- Auto-redirect notice -->
        <div class="redirect-notice">
            <i class="icon-clock"></i>
            Suunatakse automaatselt avalehele <span class="countdown" id="countdown"><?php echo $redirect_delay; ?></span> sekundi pärast
        </div>
    </div>
    
    <!-- Countdown JavaScript -->
    <script>
    // Countdown timer
    let timeLeft = <?php echo $redirect_delay; ?>;
    const countdownElement = document.getElementById('countdown');
    
    const timer = setInterval(() => {
        timeLeft--;
        if (countdownElement) {
            countdownElement.textContent = timeLeft;
        }
        
        if (timeLeft <= 0) {
            clearInterval(timer);
            if (countdownElement) {
                countdownElement.textContent = '0';
            }
        }
    }, 1000);
    
    // Log logout completion
    console.log('🔒 Logout completed:', {
        auto_logout: <?php echo $auto_logout ? 'true' : 'false'; ?>,
        reason: '<?php echo htmlspecialchars($logout_reason); ?>',
        redirect_in: <?php echo $redirect_delay; ?>
    });
    </script>
</body>
</html>