<?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_route_name(): string
{
    $route = strtolower(trim((string)($_REQUEST['route'] ?? $_REQUEST['endpoint'] ?? $_REQUEST['action'] ?? '')));
    $route = preg_replace('/[^a-z0-9_\.]/', '', $route) ?: '';
    $route = preg_replace('/\.php$/', '', $route) ?: '';
    return $route;
}

function app_guard_validate_signature(string $secret): bool
{
    $protocol = (string)($_REQUEST['app_protocol'] ?? app_guard_get_header('X-App-Protocol') ?? '');
    $ts = (string)($_REQUEST['app_ts'] ?? app_guard_get_header('X-App-Timestamp') ?? '');
    $nonce = trim((string)($_REQUEST['app_nonce'] ?? app_guard_get_header('X-App-Nonce') ?? ''));
    $sig = strtolower(trim((string)($_REQUEST['app_sig'] ?? app_guard_get_header('X-App-Signature') ?? '')));
    if ($protocol === '' || $ts === '' || $nonce === '' || $sig === '') return false;
    if ((int)$protocol < security_store_min_protocol()) return false;
    $tsInt = (int)$ts;
    if ($tsInt <= 0 || abs(time() - $tsInt) > 900) return false;
    $route = app_guard_route_name();
    if ($route === '') return false;
    $payload = $route . '|' . $ts . '|' . $nonce . '|' . $protocol;
    $expected = hash_hmac('sha256', $payload, $secret . ':THEFULL_V3_PANEL_BRIDGE_2026');
    return hash_equals($expected, $sig);
}

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-TF-Bridge')
        ?? app_guard_get_header('Authorization')
        ?? ''
    ));

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

    $secret = app_guard_secret();

    $tokenOk = $token !== '' && $secret !== '' && hash_equals($secret, $token);
    $sigOk = $tokenOk && app_guard_validate_signature($secret);
    $requiresSignature = function_exists('security_store_require_signature') ? security_store_require_signature() : true;

    if (!$tokenOk || ($requiresSignature && !$sigOk)) {
        app_guard_fail();
    }
}
