<?php
/**
 * Telegram Webhook entry point.
 * Upload this project to a public HTTPS location and point Telegram's
 * webhook URL to /v32/webhook.php (or your chosen public path).
 */

require __DIR__ . '/config.php';
require __DIR__ . '/functions.php';
require __DIR__ . '/handlers.php';

// Optional secret token protection. Telegram sends this in the
// X-Telegram-Bot-Api-Secret-Token header when configured via setWebhook.
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)) {
        http_response_code(403);
        exit('Forbidden');
    }
}

// Telegram expects a fast HTTP response. Read and decode the update first,
// then acknowledge the request before doing the bot work.
$raw = file_get_contents('php://input');
$update = json_decode($raw ?: '', true);

if (!is_array($update)) {
    http_response_code(400);
    exit('Bad Request');
}

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

// Finish the HTTP response before processing the update when the host allows
// it. This keeps Telegram from waiting for the whole handler execution.
if (function_exists('fastcgi_finish_request')) {
    @fastcgi_finish_request();
}

try {
    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']);
    }
} catch (Throwable $e) {
    error_log('BOT WEBHOOK UPDATE ERROR: ' . $e->getMessage() . ' | update=' . json_encode($update, JSON_UNESCAPED_UNICODE));
}
