<?php
/**
 * GEM ACC webhook endpoint v27.48
 *
 * Emergency fast-mode restore for shared hosting.
 * This endpoint intentionally does NOT reserve/process Telegram updates through
 * the database queue before routing. Reply-keyboard buttons must be handled in
 * the same request so Telegram users get an immediate response.
 */
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__DIR__));
}

$__logFile = BASE_PATH . '/storage/logs/webhook.log';
if (!is_dir(dirname($__logFile))) @mkdir(dirname($__logFile), 0755, true);

function gemaccWebhookLog(string $msg): void {
    global $__logFile;
    @file_put_contents($__logFile, '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND | LOCK_EX);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo '🤖 Webhook OK v27.48-fast-direct';
    exit;
}

try {
    // Load only .env for secret validation. Do not require config.php here,
    // because legacy bot.php requires it itself and double-loading config.php
    // redeclares functions.
    $envFile = BASE_PATH . '/src/Env.php';
    if (is_file($envFile)) {
        require_once $envFile;
        if (class_exists('App\\Env')) {
            App\Env::load(BASE_PATH . '/.env');
        }
    }

    $secret = '';
    if (class_exists('App\\Env')) {
        $secret = (string)App\Env::get('WEBHOOK_SECRET', App\Env::get('TELEGRAM_SECRET_TOKEN', ''));
    } else {
        $secret = (string)(getenv('WEBHOOK_SECRET') ?: getenv('TELEGRAM_SECRET_TOKEN') ?: '');
    }

    if ($secret !== '') {
        $incomingSecret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
        if (!hash_equals($secret, $incomingSecret)) {
            http_response_code(403);
            echo 'Forbidden';
            exit;
        }
    }

    $raw = file_get_contents('php://input') ?: '';
    if ($raw === '') {
        http_response_code(200);
        echo 'OK';
        exit;
    }

    $update = json_decode($raw, true);
    if (!is_array($update)) {
        gemaccWebhookLog('Invalid JSON body bytes=' . strlen($raw));
        http_response_code(200);
        echo 'OK';
        exit;
    }

    $type = 'unknown';
    foreach (['message','callback_query','inline_query','edited_message','channel_post','edited_channel_post','my_chat_member'] as $k) {
        if (isset($update[$k])) { $type = $k; break; }
    }
    $uid = isset($update['update_id']) ? (string)$update['update_id'] : 'no-update-id';
    gemaccWebhookLog('FAST_DIRECT update_id=' . $uid . ' type=' . $type . ' bytes=' . strlen($raw));

    // Pass the exact Telegram payload to the legacy router.
    $GLOBALS['__update_override_raw'] = $raw;
    require BASE_PATH . '/src/legacy/bot.php';

    http_response_code(200);
    echo 'OK';
} catch (Throwable $e) {
    gemaccWebhookLog('WEBHOOK_FATAL: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(200);
    echo 'OK';
}
