<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'httponly' => true,
        'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
        'samesite' => 'Lax',
    ]);
    session_start();
}

require_once __DIR__ . '/security_lib.php';
mocker_csrf_ensure();

header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()');

if (!function_exists('str_starts_with')) {
    
    function str_starts_with($haystack, $needle): bool
    {
        $needle = (string) $needle;
        if ($needle === '') {
            return true;
        }

        return strncmp((string) $haystack, $needle, strlen($needle)) === 0;
    }
}

if (!function_exists('mocker_utf8_len')) {
    function mocker_utf8_len(string $s): int
    {
        if (function_exists('mb_strlen')) {
            return (int) mb_strlen($s, 'UTF-8');
        }
        if (function_exists('iconv_strlen')) {
            return (int) iconv_strlen($s, 'UTF-8');
        }

        return strlen($s);
    }
}

if (!function_exists('mocker_utf8_substr')) {
    function mocker_utf8_substr(string $s, int $start, int $length): string
    {
        if ($length <= 0) {
            return '';
        }
        if (function_exists('mb_substr')) {
            return (string) mb_substr($s, $start, $length, 'UTF-8');
        }
        if (function_exists('iconv_substr')) {
            $out = iconv_substr($s, $start, $length, 'UTF-8');

            return $out === false ? '' : (string) $out;
        }

        return (string) substr($s, $start, $length);
    }
}

if (!function_exists('mocker_utf8_lower')) {
    function mocker_utf8_lower(string $s): string
    {
        if (function_exists('mb_strtolower')) {
            return (string) mb_strtolower($s, 'UTF-8');
        }

        return strtolower($s);
    }
}

$script = basename($_SERVER['SCRIPT_FILENAME'] ?? '');

$adminApiEntry = (in_array($script, ['login.php', 'session.php', 'data.php', 'save.php'], true)
    || (str_starts_with($script, 'admin_') && $script !== 'admin_gate.php'))
    && $script !== 'logout.php';
if ($adminApiEntry) {
    require_once __DIR__ . '/admin_gate.php';
    mocker_require_admin_panel_gate();
}
