<?php

declare(strict_types=1);

require_once __DIR__ . '/_security_store.php';

function app_guard_skip(): bool
{
    $script = basename($_SERVER['SCRIPT_NAME'] ?? '');
    $route = strtolower(trim((string)($_REQUEST['route'] ?? $_REQUEST['endpoint'] ?? $_REQUEST['action'] ?? '')));
    $route = preg_replace('/[^a-z0-9_\.]/', '', $route) ?: '';
    $route = preg_replace('/\.php$/', '', $route) ?: '';

    if ($route === 'thefulltv_webhook') {
        return true;
    }

    return in_array($script, [
        '_app_guard.php',
        '_security_store.php',
        'thefulltv_webhook.php'
    ], true);
}

function app_guard_secret(): string
{
    return security_store_token();
}

function app_guard_get_header(string $name): string
{
    $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
    return trim((string)($_SERVER[$key] ?? ''));
}

function app_guard_is_panel_session(): bool
{
    if (PHP_SAPI === 'cli') {
        return true;
    }

    if (session_status() === PHP_SESSION_NONE) {
        @session_start();
    }

    return !empty($_SESSION['panel_user']) && !empty($_SESSION['tipo_user']);
}

function app_guard_fail(): void
{
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    http_response_code(403);
    echo json_encode([
        'ok' => false,
        'status' => 'error',
        'message' => 'invalid_app_token'
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function app_guard_validate(): void
{
    if (app_guard_skip()) {
        return;
    }

    if (app_guard_is_panel_session()) {
        return;
    }

    $token = trim((string)(
        $_REQUEST['app_token']
        ?? $_POST['app_token']
        ?? app_guard_get_header('X-App-Token')
        ?? app_guard_get_header('Authorization')
        ?? ''
    ));

    if (stripos($token, 'Bearer ') === 0) {
        $token = trim(substr($token, 7));
    }

    $secret = app_guard_secret();

    if ($token === '' || $secret === '' || !hash_equals($secret, $token)) {
        app_guard_fail();
    }
}
