<?php
session_start();

// Revoke the DB session record and write audit log before destroying PHP session
if (isset($_SESSION['user_id'])) {
    require_once 'layouts/dbconn.php';

    $ip_address = filter_var(
        $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'],
        FILTER_VALIDATE_IP
    ) ?: $_SERVER['REMOTE_ADDR'];
    $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500);

    try {
        // Revoke the user_sessions record
        if (!empty($_SESSION['session_db_id'])) {
            $rev = $conn->prepare(
                "UPDATE user_sessions SET revoked_at = NOW() WHERE id = ? AND revoked_at IS NULL"
            );
            $rev->bind_param('s', $_SESSION['session_db_id']);
            $rev->execute();
            $rev->close();
        }

        // Audit log
        $duration_sec = isset($_SESSION['login_time']) ? (time() - $_SESSION['login_time']) : 0;
        $log_data = json_encode([
            'event'            => 'LOGOUT',
            'session_duration' => $duration_sec,
        ]);
        $log = $conn->prepare(
            "INSERT INTO audit_logs
               (id, user_id, session_id, action, module,
                entity_type, entity_id, new_values,
                ip_address, user_agent, request_method, request_path)
             VALUES (UUID(), ?, ?, 'LOGOUT', 'authentication',
                     'user', ?, ?, ?, ?, 'GET', '/logout.php')"
        );
        $session_db_id = $_SESSION['session_db_id'] ?? '';

$log->bind_param(
    'ssssss',
    $_SESSION['user_id'],
    $session_db_id,
    $_SESSION['user_id'],
    $log_data,
    $ip_address,
    $user_agent
);
        /*$log->bind_param('ssssss',
            $_SESSION['user_id'],
            $session_db_id = $_SESSION['session_db_id'] ?? '',
            $_SESSION['user_id'],
            $log_data,
            $ip_address,
            $user_agent
        );*/
        $log->execute();
        $log->close();

        $conn->close();

    } catch (Exception $e) {
        error_log('SSBS logout error: ' . $e->getMessage());
    }
}

// Store name for the goodbye message before clearing session
$user_first_name = $_SESSION['first_name'] ?? 'User';
$user_full_name  = isset($_SESSION['first_name'], $_SESSION['last_name'])
    ? trim($_SESSION['first_name'] . ' ' . $_SESSION['last_name'])
    : 'User';

// Destroy PHP session completely
$_SESSION = [];
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(), '', time() - 86400,
        $params['path'], $params['domain'],
        $params['secure'], $params['httponly']
    );
}
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Signed Out — South Sudan Bureau of Standards</title>
    <meta name="robots" content="noindex, nofollow">

    <link rel="stylesheet" href="assets/libs/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/libs/remixicon/remixicon.css">

    <style>
        :root {
            --ssbs-blue:       #1a3a6b;
            --ssbs-blue-light: #2a5298;
            --ssbs-blue-dark:  #0d1f3c;
            --ssbs-gold:       #c8a92b;
            --ssbs-gold-light: #e6c84a;
            --ssbs-green:      #1a6e2e;
            --white:           #ffffff;
            --border:          #d0d7de;
            --text-dark:       #1c2b4a;
            --text-muted:      #6b7280;
        }

        * { box-sizing: border-box; }

        body {
            background: linear-gradient(135deg, #0d1f3c 0%, #1a3a6b 50%, #1a4a2e 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        /* ── Card ─────────────────────────────────── */
        .logout-card {
            width: 100%;
            max-width: 900px;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 25px 60px rgba(0,0,0,.4);
            display: flex;
        }

        /* ── Left panel ───────────────────────────── */
        .panel-left {
            flex: 1;
            background: linear-gradient(160deg, var(--ssbs-blue-dark) 0%, var(--ssbs-blue) 60%, var(--ssbs-green) 100%);
            padding: 48px 36px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        .panel-left::before {
            content: '';
            position: absolute;
            inset: 0;
            background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
        }

        .shield-icon {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            background: rgba(200,169,43,.2);
            border: 3px solid rgba(200,169,43,.4);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
            font-size: 40px;
            position: relative;
            z-index: 1;
        }

        .panel-left h2 {
            color: var(--white);
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 8px;
            position: relative; z-index: 1;
        }
        .panel-left p {
            color: rgba(255,255,255,.7);
            font-size: .85rem;
            margin-bottom: 28px;
            position: relative; z-index: 1;
        }

        .flag-bar {
            display: flex;
            height: 6px;
            width: 70%;
            border-radius: 3px;
            overflow: hidden;
            margin: 0 auto 28px;
            position: relative; z-index: 1;
        }
        .flag-bar span { flex: 1; }
        .flag-bar .f-black { background: #000; }
        .flag-bar .f-red   { background: #DD1C1A; }
        .flag-bar .f-green { background: #007A3D; }
        .flag-bar .f-blue  { background: #003893; }

        .security-item {
            background: rgba(255,255,255,.07);
            border: 1px solid rgba(255,255,255,.1);
            border-radius: 10px;
            padding: 12px 14px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 12px;
            text-align: left;
            width: 100%;
            position: relative; z-index: 1;
        }
        .security-item i {
            font-size: 18px;
            color: var(--ssbs-gold-light);
            flex-shrink: 0;
        }
        .security-item small {
            color: rgba(255,255,255,.85);
            font-size: .78rem;
        }

        /* ── Right panel ──────────────────────────── */
        .panel-right {
            flex: 1;
            background: var(--white);
            padding: 48px 44px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
        }

        .logout-icon-wrap {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #e8f4fd, #dbeafe);
            border: 2px solid #93c5fd;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 34px;
            animation: pop .5s ease-out;
        }
        @keyframes pop {
            0%   { transform: scale(.4); opacity: 0; }
            70%  { transform: scale(1.1); }
            100% { transform: scale(1); opacity: 1; }
        }

        .panel-right h3 {
            color: var(--ssbs-blue);
            font-size: 1.4rem;
            font-weight: 700;
            margin-bottom: 6px;
        }
        .panel-right .goodbye-sub {
            color: var(--text-muted);
            font-size: .9rem;
            margin-bottom: 6px;
        }

        .time-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: #f0f6ff;
            border: 1px solid #c5d8f8;
            color: var(--ssbs-blue);
            border-radius: 20px;
            padding: 6px 16px;
            font-size: .8rem;
            font-weight: 600;
            margin: 10px 0 24px;
        }

        .btn-signin-again {
            background: linear-gradient(135deg, var(--ssbs-blue) 0%, var(--ssbs-blue-light) 100%);
            border: none;
            color: var(--white);
            font-weight: 700;
            font-size: .9rem;
            padding: 11px;
            border-radius: 8px;
            width: 100%;
            transition: all .25s;
            text-decoration: none;
            display: block;
            margin-bottom: 10px;
        }
        .btn-signin-again:hover {
            background: linear-gradient(135deg, var(--ssbs-blue-dark) 0%, var(--ssbs-blue) 100%);
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(26,58,107,.3);
            color: var(--white);
        }
        .btn-home {
            background: transparent;
            border: 2px solid var(--ssbs-blue);
            color: var(--ssbs-blue);
            font-weight: 600;
            font-size: .9rem;
            padding: 9px;
            border-radius: 8px;
            width: 100%;
            transition: all .25s;
            text-decoration: none;
            display: block;
        }
        .btn-home:hover {
            background: #f0f4f8;
            color: var(--ssbs-blue);
        }

        .security-notice {
            background: #fffbeb;
            border: 1px solid #fde68a;
            border-radius: 10px;
            padding: 14px 16px;
            font-size: .78rem;
            color: #78350f;
            text-align: left;
            margin-top: 20px;
        }
        .security-notice ul {
            margin: 6px 0 0;
            padding-left: 16px;
        }
        .security-notice li { margin-bottom: 3px; }

        .quick-links {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 20px;
        }
        .quick-links a {
            color: var(--text-muted);
            font-size: .78rem;
            text-decoration: none;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
            transition: color .2s;
        }
        .quick-links a i { font-size: 20px; }
        .quick-links a:hover { color: var(--ssbs-blue); }

        .auth-footer {
            margin-top: 20px;
            font-size: .75rem;
            color: var(--text-muted);
        }
        .auth-footer a { color: var(--ssbs-blue); text-decoration: none; }

        /* Responsive */
        @media (max-width: 767px) {
            .logout-card { flex-direction: column; border-radius: 14px; }
            .panel-left  { padding: 32px 24px; }
            .panel-right { padding: 32px 24px; }
        }
    </style>
</head>
<body>

<div class="logout-card">

    <!-- ── Left panel ──────────────────────────────────────── -->
    <div class="panel-left">
        <div class="shield-icon">🛡️</div>
        <h2>Session Ended Securely</h2>
        <p>Your SSBS-ISCMS session has been terminated and all data cleared.</p>

        <div class="flag-bar">
            <span class="f-black"></span>
            <span class="f-red"></span>
            <span class="f-green"></span>
            <span class="f-blue"></span>
        </div>

        <div class="security-item">
            <i class="ri-shield-check-line"></i>
            <small>Session token revoked and removed from all records</small>
        </div>
        <div class="security-item">
            <i class="ri-lock-line"></i>
            <small>All locally cached session data has been cleared</small>
        </div>
        <div class="security-item">
            <i class="ri-file-list-3-line"></i>
            <small>Logout event recorded in the system audit trail</small>
        </div>
    </div>

    <!-- ── Right panel ─────────────────────────────────────── -->
    <div class="panel-right">
        <div class="logout-icon-wrap">✅</div>

        <h3>Successfully Signed Out</h3>
        <p class="goodbye-sub">
            Goodbye, <strong><?php echo htmlspecialchars($user_first_name); ?></strong>!<br>
            Thank you for using <strong>SSBS-ISCMS</strong>.
        </p>

        <div class="time-badge">
            <i class="ri-time-line"></i>
            <?php echo date('D, d M Y \a\t H:i'); ?> EAT
        </div>

        <a href="login.php" class="btn-signin-again">
            <i class="ri-login-circle-line me-2"></i>Sign In Again
        </a>
        <a href="login.php" class="btn-home">
            <i class="ri-home-4-line me-2"></i>Back to Homepage
        </a>

        <div class="security-notice">
            <strong><i class="ri-information-line me-1"></i>Security Reminder</strong>
            <ul>
                <li>Your session has been completely terminated on this server.</li>
                <li>For shared computers, close all browser windows now.</li>
                <li>Use a private/incognito window on public devices.</li>
            </ul>
        </div>

        <div class="quick-links">
            <a href="login.php">
                <i class="ri-login-circle-line"></i>
                <span>Login</span>
            </a>
            <a href="forgot_password.php">
                <i class="ri-lock-unlock-line"></i>
                <span>Reset Password</span>
            </a>
            <a href="mailto:support@ssbs.gov.ss">
                <i class="ri-customer-service-2-line"></i>
                <span>Support</span>
            </a>
        </div>

        <div class="auth-footer">
            &copy; <?php echo date('Y'); ?> South Sudan Bureau of Standards (SSBS) &mdash;
            <a href="mailto:support@ssbs.gov.ss">support@ssbs.gov.ss</a>
        </div>
    </div>

</div>

<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script>
// Prevent going back to an authenticated page after logout
window.history.pushState(null, '', window.location.href);
window.addEventListener('popstate', function () {
    window.history.pushState(null, '', window.location.href);
});

// Clear any browser-cached sensitive data
if ('caches' in window) {
    caches.keys().then(names => names.forEach(n => caches.delete(n)));
}
sessionStorage.clear();
</script>
</body>
</html>
