<?php
ob_start();

$PathPrefix = '';
session_name('CAKEPHP');

include($PathPrefix . 'config.php');

if (isset($SessionSavePath)) {
    session_save_path($SessionSavePath);
}

ini_set('session.gc_maxlifetime', $SessionLifeTime);
ini_set('max_execution_time', $MaximumExecutionTime);

$isApiLogout = (
    (isset($_REQUEST['api']) && $_REQUEST['api'] == '1') ||
    (isset($_REQUEST['format']) && strtolower($_REQUEST['format']) == 'json')
);
$returnUrl = isset($_REQUEST['return_url']) ? trim($_REQUEST['return_url']) : '';

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if ($origin !== '') {
    $originHost = (string)parse_url($origin, PHP_URL_HOST);
    $serverHost = isset($_SERVER['HTTP_HOST']) ? preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']) : '';
    $serverAddr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
    $allowOrigin = (
        $originHost === $serverHost ||
        $originHost === $serverAddr ||
        $originHost === 'localhost' ||
        $originHost === '127.0.0.1' ||
        preg_match('/^192\.168\.\d+\.\d+$/', $originHost)
    );

    if ($allowOrigin) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization');
        header('Vary: Origin');
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

function herp_is_allowed_logout_return($url)
{
    if ($url === '') {
        return false;
    }

    if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
        return true;
    }

    $host = (string)parse_url($url, PHP_URL_HOST);
    $serverHost = isset($_SERVER['HTTP_HOST']) ? preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']) : '';
    $serverAddr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';

    return (
        $host === $serverHost ||
        $host === $serverAddr ||
        $host === 'localhost' ||
        $host === '127.0.0.1' ||
        preg_match('/^192\.168\.\d+\.\d+$/', $host)
    );
}

session_start();

$lastLoginHistoryId = isset($_SESSION['LastLogin_HistoryId']) ? $_SESSION['LastLogin_HistoryId'] : '';

if ($lastLoginHistoryId !== '') {
    include($PathPrefix . 'includes/LanguageSetup.php');
    include($PathPrefix . 'includes/ConnectDB.inc');

    if (isset($db)) {
        $historyId = DB_escape_string($lastLoginHistoryId);
        DB_query(
            "UPDATE crm_login_history
             SET sign_outtime = NOW(),
                 id_address = '" . DB_escape_string($_SERVER['REMOTE_ADDR']) . "'
             WHERE id = '$historyId'",
            $db
        );
    }
}

$_SESSION = array();

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

session_unset();
session_destroy();

while (ob_get_level() > 0) {
    ob_end_clean();
}

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if ($isApiLogout) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array(
        'success' => true,
        'message' => 'HERP logout completed',
        'logged_out_at' => date('Y-m-d H:i:s')
    ));
    exit;
}

if ($returnUrl !== '' && herp_is_allowed_logout_return($returnUrl)) {
    header('Location: ' . $returnUrl);
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Logging out</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f3f7fb;
            color: #263238;
        }

        body {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logout-box {
            width: min(420px, calc(100% - 32px));
            padding: 24px;
            border: 1px solid #d9e4ef;
            border-radius: 6px;
            background: #fff;
            text-align: center;
            box-shadow: 0 12px 32px rgba(38, 50, 56, 0.12);
        }

        .logout-box h1 {
            margin: 0 0 8px;
            font-size: 20px;
            line-height: 1.3;
        }

        .logout-box p {
            margin: 0;
            font-size: 13px;
            line-height: 1.5;
            color: #5f6f7a;
        }

        .logout-box button {
            display: none;
            margin-top: 16px;
            padding: 8px 14px;
            border: 1px solid #0b63ce;
            border-radius: 4px;
            background: #0b63ce;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="logout-box">
        <h1>You have been logged out</h1>
        <p id="logout-message">Closing HERP...</p>
        <button type="button" id="close-button">Close tab</button>
    </div>

    <script>
        (function () {
            var now = String(Date.now());
            var hostOrigin = window.location.protocol + '//' + window.location.hostname;
            var electraLogoutUrls = [
                window.location.origin.replace(/\/+$/, '') + '/logout',
                hostOrigin + ':4000/logout',
                'http://192.168.1.21:4000/logout'
            ];
            var authKeys = [
                'accessToken',
                'user',
                'sessionExpiryAt',
                'sessionLastActivityAt',
                'OPEN_POST_LOGIN_MODAL',
                'locationId'
            ];

            function safeRun(fn) {
                try {
                    fn();
                } catch (error) {}
            }

            function uniqueUrls(urls) {
                var seen = {};
                var clean = [];

                urls.forEach(function (url) {
                    if (!seen[url]) {
                        seen[url] = true;
                        clean.push(url);
                    }
                });

                return clean;
            }

            function triggerElectraLogout() {
                uniqueUrls(electraLogoutUrls).forEach(function (logoutUrl) {
                    var iframe = document.createElement('iframe');
                    iframe.src = logoutUrl;
                    iframe.title = 'Electra logout';
                    iframe.style.display = 'none';
                    iframe.setAttribute('aria-hidden', 'true');
                    document.body.appendChild(iframe);
                });
            }

            safeRun(function () {
                if (window.BroadcastChannel) {
                    var channel = new BroadcastChannel('electra-session');
                    channel.postMessage({ type: 'logout', at: Date.now() });
                    channel.close();
                }
            });

            safeRun(function () {
                authKeys.forEach(function (key) {
                    localStorage.removeItem(key);
                    sessionStorage.removeItem(key);
                });
                localStorage.setItem('sessionLogoutAt', now);
            });

            safeRun(function () {
                localStorage.clear();
                sessionStorage.clear();
                localStorage.setItem('sessionLogoutAt', now);
                window.setTimeout(function () {
                    localStorage.removeItem('sessionLogoutAt');
                }, 500);
            });

            safeRun(triggerElectraLogout);

            window.setTimeout(function () {
                window.close();
            }, 1200);

            window.setTimeout(function () {
                var message = document.getElementById('logout-message');
                var button = document.getElementById('close-button');

                if (message) {
                    message.innerHTML = 'HERP and Electra logout was triggered. Your browser blocked automatic tab closing.';
                }
                if (button) {
                    button.style.display = 'inline-block';
                    button.onclick = function () {
                        window.close();
                    };
                }
            }, 1700);
        }());
    </script>
</body>
</html>
