<?php
/**
 * Auto-extracted module from the old large bot.php.
 * Loaded by bot.php in the original execution order.
 */
function bot_telegram_normalize_method($method){
    $m = trim((string)$method);
    $map = [
        'sendmessage' => 'sendMessage',
        'sendphoto' => 'sendPhoto',
        'senddocument' => 'sendDocument',
        'forwardmessage' => 'forwardMessage',
        'copymessage' => 'copyMessage',
        'editmessagetext' => 'editMessageText',
        'editmessagereplymarkup' => 'editMessageReplyMarkup',
        'deletemessage' => 'deleteMessage',
        'answercallbackquery' => 'answerCallbackQuery',
        'answerinlinequery' => 'answerInlineQuery',
        'answerprecheckoutquery' => 'answerPreCheckoutQuery',
        'getfile' => 'getFile',
        'getchat' => 'getChat',
        'getchatmember' => 'getChatMember',
        'getchatadministrators' => 'getChatAdministrators',
        'getme' => 'getMe',
        'setwebhook' => 'setWebhook',
        'deletewebhook' => 'deleteWebhook',
    ];
    $key = strtolower($m);
    return $map[$key] ?? $m;
}
function bot_telegram_markdown_to_html($text){
    $text = (string)$text;
    // The old Bale build used **bold** heavily. Telegram HTML is more predictable.
    $text = preg_replace('/\*\*(.*?)\*\*/su', '<b>$1</b>', $text);
    return $text;
}
function bot_telegram_normalize_payload(array $datas): array{
    foreach(['reply_markup','prices','shipping_options','errors','results'] as $field){
        if(isset($datas[$field]) && (is_array($datas[$field]) || is_object($datas[$field]))){
            $datas[$field] = json_encode($datas[$field], JSON_UNESCAPED_UNICODE);
        }
    }
    if(isset($datas['parse_mode'])){
        $pm = strtolower(trim((string)$datas['parse_mode']));
        if($pm === 'html'){
            $datas['parse_mode'] = 'HTML';
        }elseif(in_array($pm, ['markdown','markdownv2','markdown v2','markdownv2'], true)){
            foreach(['text','caption'] as $field){
                if(isset($datas[$field]) && is_string($datas[$field])) $datas[$field] = bot_telegram_markdown_to_html($datas[$field]);
            }
            $datas['parse_mode'] = 'HTML';
        }else{
            $datas['parse_mode'] = 'HTML';
        }
    }
    foreach(['disable_web_page_preview','protect_content','show_alert','ok','allow_sending_without_reply'] as $field){
        if(isset($datas[$field]) && is_bool($datas[$field])) $datas[$field] = $datas[$field] ? 'true' : 'false';
    }
    return $datas;
}

function bot_is_same_chat_id_for_guard($a, $b){
    $a = trim((string)$a);
    $b = trim((string)$b);
    if($a === '' || $b === '') return false;
    return $a === $b;
}
function bot_channel_write_guard($method, array $datas): bool{
    $method = bot_telegram_normalize_method($method);
    $writeMethods = ['sendMessage','sendPhoto','sendDocument','sendVideo','sendAudio','sendVoice','sendAnimation','editMessageText','editMessageCaption','editMessageMedia','editMessageReplyMarkup','forwardMessage','copyMessage'];
    if(!in_array($method, $writeMethods, true)) return false;
    if(empty($GLOBALS['BOT_INBOUND_NON_PRIVATE_CHAT_ID'])) return false;
    if(empty($datas['chat_id'])) return false;
    if(!bot_is_same_chat_id_for_guard($datas['chat_id'], $GLOBALS['BOT_INBOUND_NON_PRIVATE_CHAT_ID'])) return false;
    $dir = defined('BOT_ROOT_DIR') ? BOT_ROOT_DIR . '/cache' : __DIR__ . '/../../cache';
    if(!is_dir($dir)) @mkdir($dir, 0755, true);
    $line = date('Y-m-d H:i:s') . ' | blocked_channel_write | method=' . $method . ' | chat_id=' . (string)$datas['chat_id'] . "\n";
    @file_put_contents($dir . '/channel_write_guard.log', $line, FILE_APPEND);
    return true;
}

function bot($method,$datas=[]){
    $method = bot_telegram_normalize_method($method);
    if(!is_array($datas)) $datas = [];
    $datas = bot_telegram_normalize_payload($datas);
    if(function_exists('bot_channel_write_guard') && bot_channel_write_guard($method, $datas)){
        return (object)['ok'=>true, 'blocked_by_channel_guard'=>true, 'description'=>'channel_write_blocked'];
    }
    $url = TELEGRAM_API_BASE . API_KEY . '/' . $method;

    // Prefer cURL when available, because multipart uploads (CURLFile) need it.
    if(function_exists('curl_init')){
        $hasFile = false;
        foreach($datas as $v){
            if(class_exists('CURLFile', false) && $v instanceof CURLFile){ $hasFile = true; break; }
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, defined('BOT_TELEGRAM_CONNECT_TIMEOUT') ? BOT_TELEGRAM_CONNECT_TIMEOUT : 8);
        curl_setopt($ch, CURLOPT_TIMEOUT, defined('BOT_TELEGRAM_TIMEOUT') ? BOT_TELEGRAM_TIMEOUT : 18);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        if(!empty($datas)){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $hasFile ? $datas : http_build_query($datas));
        }
        $res = curl_exec($ch);
        if($res === false){
            if(function_exists('bot_scale_log_api_error')) bot_scale_log_api_error($method, 0, 'CURL: '.curl_error($ch)); else error_log('Telegram API CURL error ['.$method.']: '.curl_error($ch));
            curl_close($ch);
            return (object)['ok'=>false, 'description'=>'curl_error'];
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
    }else{
        foreach($datas as $v){
            if(class_exists("CURLFile", false) && $v instanceof CURLFile){
                error_log('Telegram API error ['.$method.']: curl extension is required for file upload');
                return (object)['ok'=>false, 'description'=>'curl_required_for_upload'];
            }
        }
        $context = stream_context_create([
            'http' => [
                'method' => empty($datas) ? 'GET' : 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'content' => empty($datas) ? '' : http_build_query($datas),
                'timeout' => (defined('BOT_TELEGRAM_TIMEOUT') ? BOT_TELEGRAM_TIMEOUT : 18),
                'ignore_errors' => true,
            ],
            'ssl' => [
                'verify_peer' => true,
                'verify_peer_name' => true,
            ],
        ]);
        $res = @file_get_contents($url, false, $context);
        $httpCode = 0;
        if(isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)){
            $httpCode = (int)$m[1];
        }
        if($res === false){
            if(function_exists('bot_scale_log_api_error')) bot_scale_log_api_error($method, 0, 'HTTP: file_get_contents failed'); else error_log('Telegram API HTTP error ['.$method.']: file_get_contents failed');
            return (object)['ok'=>false, 'description'=>'http_error'];
        }
    }

    $decoded = json_decode($res);
    if(!is_object($decoded)){
        if(function_exists('bot_scale_log_api_error')) bot_scale_log_api_error($method, $httpCode, 'invalid_json: '.substr($res,0,300)); else error_log('Telegram API invalid JSON ['.$method.'] HTTP '.$httpCode.': '.substr($res,0,500));
        return (object)['ok'=>false, 'description'=>'invalid_json', 'raw'=>$res];
    }
    if(isset($decoded->ok) && !$decoded->ok){
        if(function_exists('bot_scale_log_api_error')) bot_scale_log_api_error($method, $httpCode, $res); else error_log('Telegram API error ['.$method.'] HTTP '.$httpCode.': '.$res);
    }
    return $decoded;
}
//========================== // perti // ==============================
function perti($methode,$datase=[]){
    // Security fix: the original source sent settlement/card data to a hardcoded
    // third-party Telegram bot token. In this Telegram build, the report is sent only
    // to your configured admin account.
    global $admin;
    if(strtolower($methode) === 'sendmessage'){
        $datase['chat_id'] = $admin;
        return bot('sendMessage', $datase);
    }
    return bot($methode, $datase);
}
//----------------------------------------//
function SM($chatID,$msg,$mode,$reply = null,$keyboard = null){
$data = bot('SendMessage',['chat_id'=>$chatID,'text'=>$msg,'parse_mode'=>$mode,'reply_to_message_id'=>$reply,'reply_markup'=>$keyboard]);
return $data;
}
//////////------------------------\\\\\\\\\\\\\\
function Editmessagetext($chatID, $msg_id, $msg, $keyboard){
 bot('editmessagetext',['chat_id' => $chatID,'message_id' => $msg_id,'text' => $msg,'parse_mode' => 'MarkDown','reply_markup' => $keyboard]);
}
//////////------------------------\\\\\\\\\\\\\\ 
function sendmessage($chatID,$msg){
bot('sendMessage',['chat_id'=>$chatID,'text'=>$msg,'parse_mode'=>"html"]);
}
//////////------------------------\\\\\\\\\\\\\\
function save($filename, $data){
if(function_exists('bot_cache_invalidate_for_path')) bot_cache_invalidate_for_path($filename);
if(function_exists('bot_data_put_raw') && bot_storage_is_managed_path($filename)){ bot_data_put_raw($filename, $data); return; }
$file = fopen($filename, 'w');fwrite($file, $data);fclose($file);
}
//////////------------------------\\\\\\\\\\\\\\
function saveJson($file,$data){
if(function_exists('bot_cache_invalidate_for_path')) bot_cache_invalidate_for_path($file);
if(function_exists('bot_data_put_json') && bot_storage_is_managed_path($file)){ bot_data_put_json($file,$data); return; }
$new_data = json_encode($data,true);file_put_contents($file,$new_data);
}
