<?php
session_start();

if (isset($_SESSION['user_id'])) {
    include 'layouts/dbconn.php';

    $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_sql = "INSERT INTO audit_logs
                        (business_id, user_id, action, table_name, ip_address, user_agent, new_values)
                    VALUES (?, ?, 'LOGOUT', 'users', ?, ?, ?)";
        $log_stmt = $conn->prepare($log_sql);
        $logout_data = json_encode([
            'logout_time'      => date('Y-m-d H:i:s'),
            'session_duration' => isset($_SESSION['login_time']) ? (time() - $_SESSION['login_time']) : 0,
            'role'             => $_SESSION['role_name'] ?? '',
            'ip'               => $ip_address
        ]);
        $log_stmt->bind_param("iisss",
            $_SESSION['business_id'], $_SESSION['user_id'],
            $ip_address, $user_agent, $logout_data
        );
        $log_stmt->execute();
        $log_stmt->close();
        $conn->close();
    } catch (Exception $e) {
        error_log("Logout log error: " . $e->getMessage());
    }
}

$full_name = $_SESSION['full_name'] ?? 'User';
$role_name = $_SESSION['role_name'] ?? '';

session_unset();
session_destroy();

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',
        ['title' => 'Logged Out — Christmond M-Pesa System']); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        :root {
            --mpesa-green:       #00a651;
            --mpesa-green-dark:  #007a3d;
            --mpesa-green-light: #34c470;
            --light-green:       #e8f8ef;
            --very-light-green:  #f2fbf6;
        }

        body { background: linear-gradient(135deg, var(--very-light-green) 0%, var(--light-green) 100%); min-height: 100vh; }
        .auth-page-wrapper { background: inherit; }

        .card {
            border: none;
            border-radius: 18px;
            box-shadow: 0 12px 40px rgba(0,166,81,.12);
            overflow: hidden;
        }
        .card::before {
            content: '';
            position: absolute; top: 0; left: 0; right: 0; height: 4px;
            background: linear-gradient(90deg, var(--mpesa-green) 0%, var(--mpesa-green-light) 100%);
        }

        .brand-panel {
            background: linear-gradient(160deg, var(--mpesa-green-dark) 0%, var(--mpesa-green) 60%, var(--mpesa-green-light) 100%);
        }

        .security-item {
            background: rgba(255,255,255,.13);
            border: 1px solid rgba(255,255,255,.22);
            border-radius: 12px;
            padding: 14px 16px;
            margin-bottom: 10px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            color: #fff;
        }
        .security-item i { font-size: 1.3rem; margin-top: 2px; flex-shrink: 0; }
        .security-item strong { display: block; font-size: .88rem; }
        .security-item small { font-size: .76rem; opacity: .8; }

        .btn-mpesa {
            background: linear-gradient(135deg, var(--mpesa-green), var(--mpesa-green-light));
            border: none; color: #fff; border-radius: 8px;
            padding: 11px 24px; font-weight: 600; transition: all .3s;
        }
        .btn-mpesa:hover {
            background: linear-gradient(135deg, var(--mpesa-green-dark), var(--mpesa-green));
            color: #fff; transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,166,81,.3);
        }
        .btn-outline-mpesa {
            border: 2px solid var(--mpesa-green); color: var(--mpesa-green);
            background: transparent; border-radius: 8px;
            padding: 9px 24px; font-weight: 600; transition: all .3s;
        }
        .btn-outline-mpesa:hover {
            background: var(--light-green); color: var(--mpesa-green-dark);
            transform: translateY(-2px);
        }

        .goodbye-card {
            background: var(--light-green);
            border: 1px solid rgba(0,166,81,.2);
            border-radius: 14px;
            padding: 22px;
        }
        .quick-link { border-radius: 10px; padding: 10px; transition: background .2s; text-decoration: none; }
        .quick-link:hover { background: var(--light-green); }
        .quick-link i { color: var(--mpesa-green); }

        @media (max-width: 768px) { .card { margin: 15px; } }
    </style>
</head>

<body>
<div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
    <div class="auth-page-content overflow-hidden pt-lg-5">
        <div class="container">
            <div class="col-lg-12">
                <div class="card overflow-hidden border-0 position-relative">
                    <div class="row g-0">

                        <!-- Left panel -->
                        <div class="col-lg-5">
                            <div class="brand-panel p-lg-5 p-4 h-100 d-flex flex-column justify-content-center">

                                <div class="text-center mb-4">
                                    <img src="assets/images/logo-christmond.png"
                                         onerror="this.style.display='none'"
                                         alt="Christmond" height="65" class="mb-3">
                                    <h5 class="text-white mb-1">Session Ended Securely</h5>
                                    <p style="color:rgba(255,255,255,.75); font-size:.84rem;">
                                        Your M-Pesa agent session has been safely closed and logged.
                                    </p>
                                </div>

                                <div>
                                    <div class="security-item">
                                        <i class="ri-shield-check-line"></i>
                                        <div>
                                            <strong>Session Cleared</strong>
                                            <small>All authentication tokens have been invalidated</small>
                                        </div>
                                    </div>
                                    <div class="security-item">
                                        <i class="ri-history-line"></i>
                                        <div>
                                            <strong>Activity Logged</strong>
                                            <small>Logout event recorded in the audit trail</small>
                                        </div>
                                    </div>
                                    <div class="security-item">
                                        <i class="ri-lock-password-line"></i>
                                        <div>
                                            <strong>Data Protected</strong>
                                            <small>Float &amp; transaction data remains secure</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right panel -->
                        <div class="col-lg-7">
                            <div class="p-lg-5 p-4">

                                <div class="text-center mb-4">
                                    <div style="width:80px;height:80px;background:var(--light-green);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                                        <i class="ri-logout-box-r-line" style="font-size:2.2rem;color:var(--mpesa-green);"></i>
                                    </div>
                                    <h5 style="color:var(--mpesa-green);" class="mb-1">Successfully Logged Out</h5>
                                    <p class="text-muted mb-0">
                                        Goodbye, <strong><?= htmlspecialchars($full_name) ?></strong>
                                        <?php if($role_name): ?>
                                            <span class="badge ms-1" style="background:var(--mpesa-green);font-size:.7rem;">
                                                <?= ucfirst(str_replace('_',' ', $role_name)) ?>
                                            </span>
                                        <?php endif; ?>
                                    </p>
                                </div>

                                <!-- Goodbye card with time -->
                                <div class="goodbye-card mb-4 text-center">
                                    <div class="text-muted small mb-1">
                                        <i class="ri-time-line me-1"></i>Session closed on
                                    </div>
                                    <div class="fw-semibold" style="color:var(--mpesa-green-dark);">
                                        <?= date('l, d F Y \a\t H:i') ?>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="d-grid gap-2 mb-4">
                                    <button class="btn btn-mpesa" onclick="window.location.href='login.php'">
                                        <i class="ri-login-box-line me-2"></i>Sign In Again
                                    </button>
                                    <button class="btn btn-outline-mpesa" onclick="window.location.href='index.php'">
                                        <i class="ri-home-line me-2"></i>Go to Dashboard
                                    </button>
                                </div>

                                <!-- Security notice -->
                                <div class="p-3 rounded" style="background:#fff3cd; border:1px solid #ffc107; border-radius:10px !important;">
                                    <h6 class="mb-2" style="color:#7a5000; font-size:.83rem;">
                                        <i class="ri-information-line me-1"></i>Security Reminder
                                    </h6>
                                    <ul class="text-muted mb-0 ps-3" style="font-size:.78rem;">
                                        <li>Close all browser tabs if on a shared computer</li>
                                        <li>Ensure any open sessions for the day are properly closed</li>
                                        <li>Contact your manager if you notice any discrepancies</li>
                                    </ul>
                                </div>

                                <!-- Quick links -->
                                <div class="row text-center mt-3">
                                    <div class="col-4">
                                        <a href="login.php" class="quick-link d-block text-muted">
                                            <i class="ri-login-circle-line d-block mb-1 fs-5"></i>
                                            <small>Login</small>
                                        </a>
                                    </div>
                                    <div class="col-4">
                                        <a href="forgot_password.php" class="quick-link d-block text-muted">
                                            <i class="ri-lock-unlock-line d-block mb-1 fs-5"></i>
                                            <small>Reset Password</small>
                                        </a>
                                    </div>
                                    <div class="col-4">
                                        <a href="mailto:christmondinvestmentlimited@ymail.com" class="quick-link d-block text-muted">
                                            <i class="ri-customer-service-line d-block mb-1 fs-5"></i>
                                            <small>Support</small>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="text-center mt-3">
                    <p class="mb-0 text-muted small">
                        &copy; <?= date('Y') ?>
                        <span class="fw-semibold" style="color:var(--mpesa-green);">Christmond Investment Limited</span>
                        &mdash; M-Pesa Agent Management System
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script>
// Prevent back button from re-entering the app
window.history.pushState(null, null, window.location.href);
window.onpopstate = () => window.history.pushState(null, null, window.location.href);

// Clear cached sensitive data
if ('caches' in window) caches.keys().then(keys => keys.forEach(k => caches.delete(k)));
sessionStorage.clear();
</script>
</body>
</html>