<?php
/**
 * Telegram Webhook entry point + temporary performance diagnostics.
 * DEBUG VERSION: writes timing data to data/webhook_debug.log.
 */

$__bot_debug_start = microtime(true);
$__bot_debug_log = __DIR__ . '/data/webhook_debug.log';
function botDebugLog($message) {
    global $__bot_debug_log;
    @file_put_contents($__bot_debug_log, '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL, FILE_APPEND | LOCK_EX);
}
botDebugLog('--- REQUEST START pid=' . getmypid() . ' uri=' . ($_SERVER['REQUEST_URI'] ?? '') . ' ---');

require __DIR__ . '/config.php';
botDebugLog('after config +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
require __DIR__ . '/functions.php';
botDebugLog('after functions +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
require __DIR__ . '/handlers.php';
botDebugLog('after handlers +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');

if (defined('WEBHOOK_SECRET') && trim((string)WEBHOOK_SECRET) !== '') {
    $received = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
    if (!hash_equals((string)WEBHOOK_SECRET, (string)$received)) {
        botDebugLog('SECRET CHECK FAILED +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
        http_response_code(403);
        exit('Forbidden');
    }
}
botDebugLog('secret ok +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');

$raw = file_get_contents('php://input');
botDebugLog('input read bytes=' . strlen((string)$raw) . ' +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
$update = json_decode($raw ?: '', true);

if (!is_array($update)) {
    botDebugLog('BAD UPDATE +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
    http_response_code(400);
    exit('Bad Request');
}

$type = isset($update['message']) ? 'message' : (isset($update['callback_query']) ? 'callback' : (isset($update['inline_query']) ? 'inline' : (isset($update['chat_member']) ? 'chat_member' : 'other')));
botDebugLog('update type=' . $type . ' +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');

http_response_code(200);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);

if (function_exists('fastcgi_finish_request')) {
    @fastcgi_finish_request();
    botDebugLog('fastcgi_finish_request called +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
} else {
    botDebugLog('fastcgi_finish_request NOT available +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
}

try {
    botDebugLog('handler start +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
    if (isset($update['chat_member'])) {
        handleChannelMemberUpdate($update['chat_member']);
    } elseif (isset($update['callback_query'])) {
        handleCallback($update['callback_query']);
    } elseif (isset($update['inline_query'])) {
        handleInlineQuery($update['inline_query']);
    } elseif (isset($update['message'])) {
        handleMessage($update['message']);
    }
    botDebugLog('handler end +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's');
} catch (Throwable $e) {
    botDebugLog('EXCEPTION +' . number_format(microtime(true)-$__bot_debug_start, 4) . 's ' . $e->getMessage());
    error_log('BOT WEBHOOK UPDATE ERROR: ' . $e->getMessage() . ' | update=' . json_encode($update, JSON_UNESCAPED_UNICODE));
}
botDebugLog('--- REQUEST END total=' . number_format(microtime(true)-$__bot_debug_start, 4) . 's ---');
