<?php
// Logout Script - Secure session destruction
session_start();

// Log the logout attempt
error_log("=== LOGOUT ATTEMPT ===");
error_log("Session ID: " . session_id());
error_log("User: " . ($_SESSION['user'] ?? 'Unknown'));
error_log("User ID: " . ($_SESSION['user_id'] ?? 'Unknown'));
error_log("Role: " . ($_SESSION['role_name'] ?? 'Unknown'));
error_log("IP Address: " . ($_SERVER['REMOTE_ADDR'] ?? 'Unknown'));
error_log("User Agent: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'));

// Store user info for display before destroying session
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'] ?? 'User';
$was_logged_in = isset($_SESSION['logged_in']) && $_SESSION['logged_in'];

// Log activity if user was logged in
if ($was_logged_in && isset($_SESSION['user_id'])) {
    try {
        require_once 'layouts/dbconn.php';
        
        if (isset($conn) && !$conn->connect_error) {
            $user_id = $_SESSION['user_id'];
            $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $session_id = session_id();
            
            // Log the logout activity
            $stmt = $conn->prepare("
                INSERT INTO activity_log 
                (user_id, action, module, record_id, ip_address, user_agent, session_id, additional_info) 
                VALUES (?, 'LOGOUT', 'authentication', ?, ?, ?, ?, 'User logged out successfully')
            ");
            
            if ($stmt) {
                $stmt->bind_param("issss", $user_id, $user_id, $ip_address, $user_agent, $session_id);
                $stmt->execute();
                $stmt->close();
                error_log("✓ Logout activity logged for user ID: " . $user_id);
            }
        }
    } catch (Exception $e) {
        error_log("Error logging logout activity: " . $e->getMessage());
    }
}

// Destroy the session completely
session_unset();     // Remove all session variables
session_destroy();   // Destroy the session
session_write_close(); // Ensure session is written and closed

// Clear any session cookies
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
}

// Clear any remember me cookies if they exist
if (isset($_COOKIE['remember_me'])) {
    setcookie('remember_me', '', time() - 3600, '/');
}

error_log("✅ User successfully logged out and session destroyed");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Logged Out - ConnectPay Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="ConnectPay Plugin Platform" name="description" />
    <meta content="ConnectPay Platform" name="author" />
    
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">

    <!-- Bootstrap CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
        
        .authentication-bg {
            position: relative;
        }
        
        .authentication-bg::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.1;
        }
        
        .card {
            border: none;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            border-radius: 1rem;
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }
        
        .logout-checkmark {
            width: 80px;
            height: 80px;
            margin: 0 auto 1rem;
            position: relative;
        }
        
        .logout-checkmark svg {
            width: 100%;
            height: 100%;
        }
        
        .logout-checkmark .path {
            stroke-dasharray: 1000;
            stroke-dashoffset: 0;
        }
        
        .logout-checkmark .circle {
            animation: dash 0.9s ease-in-out;
        }
        
        .logout-checkmark .check {
            stroke-dashoffset: -100;
            animation: dash-check 0.9s 0.35s ease-in-out forwards;
        }
        
        @keyframes dash {
            0% {
                stroke-dashoffset: 1000;
            }
            100% {
                stroke-dashoffset: 0;
            }
        }
        
        @keyframes dash-check {
            0% {
                stroke-dashoffset: -100;
            }
            100% {
                stroke-dashoffset: 900;
            }
        }
        
        .logo img {
            filter: brightness(0) invert(1);
        }
        
        .fade-in {
            animation: fadeIn 0.8s ease-in;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .btn-return {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 0.5rem;
            padding: 0.75rem 2rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }
        
        .btn-return:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        
        .security-note {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.2);
            border-radius: 0.5rem;
            padding: 1rem;
            margin-top: 1.5rem;
        }
        
        .security-note i {
            color: #22c55e;
        }
    </style>
</head>

<body class="authentication-bg">

    <div class="account-pages mt-5 mb-5">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8 col-lg-6 col-xl-4">
                    <div class="card fade-in">
                        <div class="card-body p-4">
                            
                            <!-- Logo Section -->
                            <div class="text-center w-75 m-auto mb-4">
                                <div class="auth-logo">
                                    <a href="index.php" class="logo text-center d-block">
                                        <span class="logo-lg">
                                            <img src="assets/images/logo-dark.png" alt="ConnectPay Platform" height="22" 
                                                 onerror="this.style.display='none'; this.parentNode.innerHTML='<h4 style=\'color: #667eea; font-weight: bold;\'>ConnectPay Platform</h4>'">
                                        </span>
                                    </a>
                                </div>
                            </div>

                            <!-- Logout Success Message -->
                            <div class="text-center">
                                <div class="mt-3">
                                    <div class="logout-checkmark">
                                        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 130.2 130.2">
                                            <circle class="path circle" fill="none" stroke="#22c55e" stroke-width="6" stroke-miterlimit="10" cx="65.1" cy="65.1" r="62.1"/>
                                            <polyline class="path check" fill="none" stroke="#22c55e" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" points="100.2,40.2 51.5,88.8 29.8,67.5 "/>
                                        </svg>
                                    </div>
                                </div>
                                
                                <h3 class="mb-3">See you again, <?php echo htmlspecialchars($user_name); ?>!</h3>
                                <p class="text-muted mb-4">
                                    You have been successfully logged out from your ConnectPay Platform account.
                                </p>

                                <!-- Security Information -->
                                <div class="security-note">
                                    <div class="d-flex align-items-center justify-content-center mb-2">
                                        <i class="fas fa-shield-alt me-2"></i>
                                        <strong>Security Notice</strong>
                                    </div>
                                    <small class="text-muted">
                                        For your security, all session data has been cleared. 
                                        Remember to close your browser if using a shared computer.
                                    </small>
                                </div>

                                <!-- Action Buttons -->
                                <div class="mt-4">
                                    <a href="auth-login.php" class="btn btn-return text-white w-100 mb-3">
                                        <i class="fas fa-sign-in-alt me-2"></i>
                                        Sign In Again
                                    </a>
                                    <a href="index.php" class="btn btn-outline-secondary w-100">
                                        <i class="fas fa-home me-2"></i>
                                        Go to Homepage
                                    </a>
                                </div>
                            </div>

                        </div> <!-- end card-body -->
                    </div>
                    <!-- end card -->

                    <!-- Footer Links -->
                    <div class="row mt-3">
                        <div class="col-12 text-center">
                            <p class="text-white-50 mb-2">
                                Need help? <a href="mailto:support@yourplatform.com" class="text-white"><b>Contact Support</b></a>
                            </p>
                            <p class="text-white-50 small">
                                © <?php echo date('Y'); ?> ConnectPay. All rights reserved.
                            </p>
                        </div>
                    </div>

                </div> <!-- end col -->
            </div>
            <!-- end row -->
        </div>
        <!-- end container -->
    </div>
    <!-- end page -->

    <!-- Bootstrap JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('🔐 Logout page loaded successfully');
        
        // Auto-redirect to login after 10 seconds (optional)
        let countdown = 30;
        const countdownElement = document.createElement('p');
        countdownElement.className = 'text-muted small mt-3';
        countdownElement.id = 'auto-redirect';
        
        function updateCountdown() {
            if (countdown > 0) {
                countdownElement.innerHTML = `<i class="fas fa-clock me-1"></i>Auto-redirecting to login in ${countdown} seconds... <a href="#" onclick="clearTimeout(redirectTimer); document.getElementById('auto-redirect').style.display='none';" class="text-decoration-none">Cancel</a>`;
                countdown--;
            } else {
                window.location.href = 'auth-login.php';
            }
        }
        
        // Add countdown element
        document.querySelector('.card-body').appendChild(countdownElement);
        
        // Start countdown
        updateCountdown();
        const redirectTimer = setInterval(updateCountdown, 1000);
        
        // Clear any remaining session storage on client side
        try {
            if (typeof(Storage) !== "undefined") {
                localStorage.clear();
                sessionStorage.clear();
            }
        } catch(e) {
            console.log('Storage clearing not available');
        }
        
        // Aggressive back button prevention after logout
        function preventBack() {
            window.history.forward();
        }
        
        // Replace current page in history
        history.pushState(null, null, window.location.href);
        
        // Handle back button attempts
        window.onpopstate = function(event) {
            history.pushState(null, null, window.location.href);
            alert('🔐 Session expired! You have been logged out for security. Please sign in again.');
            window.location.replace('auth-login.php');
        };
        
        // Additional protection - disable browser cache for previous pages
        window.onunload = function() {
            // This helps clear the cache when leaving the logout page
        };
        
        // Force reload if user somehow gets back to cached page
        if (performance.navigation.type == performance.navigation.TYPE_BACK_FORWARD) {
            window.location.replace('auth-login.php');
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                window.location.href = 'auth-login.php';
            }
        });
        
        console.log('✅ Logout completed successfully');
    });
    </script>

</body>
</html>