<?php
declare(strict_types=1);

function mocker_admin_panel_secret_is_active(): bool
{
    static $active = null;
    if ($active !== null) {
        return $active;
    }
    if (!is_readable(__DIR__ . '/config.php')) {
        $active = false;

        return false;
    }
    require_once __DIR__ . '/config.php';
    $active = defined('SITE_ADMIN_PANEL_SECRET') && (string) SITE_ADMIN_PANEL_SECRET !== '';

    return $active;
}

function mocker_admin_panel_gate_expected_cookie(): string
{
    require_once __DIR__ . '/config.php';

    return hash_hmac('sha256', (string) SITE_ADMIN_PANEL_SECRET, 'site_gate_v1');
}

function mocker_admin_panel_gate_cookie_ok(): bool
{
    if (!mocker_admin_panel_secret_is_active()) {
        return false;
    }
    $expected = mocker_admin_panel_gate_expected_cookie();
    $got = $_COOKIE['mocker_admin_gate'] ?? '';

    return is_string($got) && $got !== '' && hash_equals($expected, $got);
}

function mocker_require_admin_panel_gate(): void
{
    if (!mocker_admin_panel_secret_is_active()) {
        return;
    }
    if (mocker_admin_panel_gate_cookie_ok()) {
        return;
    }
    http_response_code(404);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}

function mocker_admin_panel_html_gate(): void
{
    if (!mocker_admin_panel_secret_is_active()) {
        return;
    }
    require_once __DIR__ . '/config.php';
    $secret = (string) SITE_ADMIN_PANEL_SECRET;
    if (mocker_admin_panel_gate_cookie_ok()) {
        return;
    }
    $k = isset($_GET['k']) ? (string) $_GET['k'] : '';
    if ($k !== '' && hash_equals($secret, $k)) {
        $token = mocker_admin_panel_gate_expected_cookie();
        $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
        setcookie('mocker_admin_gate', $token, [
            'expires' => time() + 60 * 60 * 24 * 90,
            'path' => '/',
            'secure' => $secure,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
        $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
        if (!is_string($path) || $path === '') {
            $path = '/admin.php';
        }
        header('Location: ' . $path, true, 302);
        exit;
    }
    http_response_code(404);
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: no-store');
    echo '<!DOCTYPE html><html lang="tr"><head><meta charset="utf-8"><title>404</title></head><body><p>Not Found</p></body></html>';
    exit;
}
