<?php 
session_start();

// Log the logout activity before destroying session
if (isset($_SESSION['user_id'])) {
    include 'layouts/dbconn.php';
    
    // Get client information for logging
    $ip_address = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    try {
        // Log logout activity (matching exact activity_log schema)
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent, session_id) 
                   VALUES (?, 'LOGOUT', 'AUTH', ?, 'USER', ?, ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $session_id = session_id();
        $logout_data = json_encode(array(
            'logout_time' => date('Y-m-d H:i:s'),
            'session_duration' => isset($_SESSION['login_time']) ? (time() - $_SESSION['login_time']) : 0,
            'ip_address' => $ip_address
        ));
        $log_stmt->bind_param("iissss", $_SESSION['user_id'], $_SESSION['user_id'], $logout_data, $ip_address, $user_agent, $session_id);
        $log_stmt->execute();
        $log_stmt->close();
        
        $conn->close();
    } catch (Exception $e) {
        error_log("Logout logging error: " . $e->getMessage());
    }
}

// Store user name for display before destroying session
$user_name = $_SESSION['full_name'] ?? 'User';

session_unset();
session_destroy();

// Clear session cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Logged Out - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Phosphor Icons -->
    <link href="https://unpkg.com/phosphor-icons@1.4.2/src/css/icons.css" rel="stylesheet">
    
    <!-- LordIcon Script -->
    <script src="https://cdn.lordicon.com/lordicon.js"></script>
    
    <style>
        /* Custom logout page styling matching login design */
        .auth-page-wrapper {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }
        
        .logout-card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .logout-left-panel {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            position: relative;
        }
        
        .logout-left-panel::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="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }
        
        .logout-content {
            position: relative;
            z-index: 2;
        }
        
        .feature-item {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .feature-item:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.15);
        }
        
        .logout-animation {
            animation: bounceIn 1s ease-out;
        }
        
        @keyframes bounceIn {
            0% {
                opacity: 0;
                transform: scale(0.3);
            }
            50% {
                opacity: 1;
                transform: scale(1.05);
            }
            70% {
                transform: scale(0.9);
            }
            100% {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
            background: linear-gradient(135deg, #5a67d8 0%, #667eea 100%);
        }
        
        .btn-secondary-custom {
            border: 2px solid #667eea;
            background: transparent;
            color: #667eea;
            border-radius: 12px;
            padding: 10px 30px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-secondary-custom:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
        }
        
        .security-info {
            background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
            border: 1px solid rgba(102, 126, 234, 0.2);
            border-radius: 15px;
            padding: 20px;
        }
        
        .time-display {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            color: #666;
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 8px;
            display: inline-block;
        }
    </style>
</head>

<body>
    <!-- auth-page wrapper -->
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        
        <!-- auth-page content -->
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card logout-card">
                            <div class="row g-0">
                                <div class="col-lg-6">
                                    <div class="logout-left-panel p-lg-5 p-4 h-100 d-flex flex-column justify-content-center">
                                        <div class="logout-content text-center text-white">
                                            <div class="mb-4">
                                                <a href="index.php" class="d-block">
                                                    <img src="assets/images/logo/ultrasure_logo_white.png" alt="Ultrasure Insurance Platform" height="80" class="mb-3">
                                                </a>
                                                <h4 class="text-white mb-3">Session Ended Securely</h4>
                                                <p class="text-white-50 mb-4">Your session has been safely terminated. Thank you for using Ultrasure Insurance Platform.</p>
                                            </div>
                                            
                                            <!-- Security features -->
                                            <div class="row text-center">
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-shield-check-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Secure Logout</small>
                                                        <div class="text-white-75 small mt-1">All session data cleared</div>
                                                    </div>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-lock-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Data Protected</small>
                                                        <div class="text-white-75 small mt-1">Your information is safe</div>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="feature-item">
                                                        <i class="ri-time-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Activity Logged</small>
                                                        <div class="text-white-75 small mt-1">Session recorded securely</div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->

                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4 d-flex flex-column justify-content-center h-100">
                                        <div class="text-center logout-animation">
                                            <!-- Logout Icon Animation -->
                                            <lord-icon
                                                src="https://cdn.lordicon.com/hzomhqxz.json"
                                                trigger="loop"
                                                colors="primary:#667eea,secondary:#764ba2"
                                                style="width:120px;height:120px">
                                            </lord-icon>
                                            
                                            <div class="mt-4">
                                                <h4 class="text-primary mb-2">Successfully Logged Out</h4>
                                                <p class="text-muted mb-1">
                                                    Goodbye, <strong><?php echo htmlspecialchars($user_name); ?></strong>!
                                                </p>
                                                <p class="text-muted mb-4">
                                                    Thank you for using <span class="fw-semibold text-primary">Ultrasure Insurance Platform</span>
                                                </p>
                                                
                                                <!-- Current time display -->
                                                <div class="mb-4">
                                                    <div class="time-display">
                                                        <i class="ri-time-line me-2"></i>
                                                        Logged out at: <?php echo date('F j, Y \a\t g:i A T'); ?>
                                                    </div>
                                                </div>
                                                
                                                <!-- Action buttons -->
                                                <div class="d-grid gap-2 d-md-block">
                                                    <a href="login.php" class="btn btn-primary-custom me-md-2">
                                                        <i class="ri-login-circle-line me-2"></i>Sign In Again
                                                    </a>
                                                    <a href="index.php" class="btn btn-secondary-custom">
                                                        <i class="ri-home-line me-2"></i>Go Home
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Security information -->
                                        <div class="mt-5">
                                            <div class="security-info">
                                                <h6 class="text-primary mb-3">
                                                    <i class="ri-information-line me-2"></i>Security Notice
                                                </h6>
                                                <ul class="text-muted small mb-0 ps-3">
                                                    <li>Your session has been completely terminated</li>
                                                    <li>All temporary data has been cleared</li>
                                                    <li>For your security, close all browser windows</li>
                                                    <li>Use a private/incognito window on shared computers</li>
                                                </ul>
                                            </div>
                                        </div>
                                        
                                        <!-- Quick access links -->
                                        <div class="mt-4 text-center">
                                            <div class="row text-center">
                                                <div class="col-4">
                                                    <a href="agent_registration.php" class="text-decoration-none small text-muted">
                                                        <i class="ri-user-add-line d-block mb-1"></i>
                                                        New Agent?
                                                    </a>
                                                </div>
                                                <div class="col-4">
                                                    <a href="forgot_password.php" class="text-decoration-none small text-muted">
                                                        <i class="ri-lock-unlock-line d-block mb-1"></i>
                                                        Reset Password
                                                    </a>
                                                </div>
                                                <div class="col-4">
                                                    <a href="mailto:support@ultrasure.co.ke" class="text-decoration-none small text-muted">
                                                        <i class="ri-customer-service-line d-block mb-1"></i>
                                                        Get Support
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->
                            </div>
                            <!-- end row -->
                        </div>
                        <!-- end card -->
                    </div>
                    <!-- end col -->
                </div>
                <!-- end row -->
            </div>
            <!-- end container -->
        </div>
        <!-- end auth page content -->

        <!-- footer -->
        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <script>document.write(new Date().getFullYear())</script> 
                                <span class="text-primary fw-semibold">Ultrasure Insurance Platform</span> - 
                                Leading Digital Insurance Solutions in East Africa
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
        <!-- end Footer -->
    </div>
    <!-- end auth-page-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script>
    // Auto-redirect after a delay (optional)
    setTimeout(function() {
        // Uncomment the next line if you want auto-redirect to login after 30 seconds
        // window.location.href = 'login.php';
    }, 30000);

    // Prevent back button after logout
    window.history.pushState(null, null, window.location.href);
    window.onpopstate = function(event) {
        window.history.pushState(null, null, window.location.href);
    };

    // Clear any cached data
    if ('caches' in window) {
        caches.keys().then(function(names) {
            names.forEach(function(name) {
                caches.delete(name);
            });
        });
    }

    // Display success message
    document.addEventListener('DOMContentLoaded', function() {
        // Optional: Show a toast notification
        const toastElement = document.createElement('div');
        toastElement.className = 'toast position-fixed top-0 end-0 m-3';
        toastElement.innerHTML = `
            <div class="toast-header">
                <i class="ri-shield-check-line text-success me-2"></i>
                <strong class="me-auto">Logout Successful</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                You have been securely logged out of your account.
            </div>
        `;
        document.body.appendChild(toastElement);
        
        const toast = new bootstrap.Toast(toastElement);
        toast.show();
    });
    </script>
</body>
</html>