<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function apiRequest(string $method, array $parameters = [], ?string $platform_override = null): ?array {
    if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true) {
        if (!isset($GLOBALS['bridge_api_actions']) || !is_array($GLOBALS['bridge_api_actions'])) {
            $GLOBALS['bridge_api_actions'] = [];
        }
        $GLOBALS['bridge_api_actions'][] = ['method' => $method, 'params' => $parameters];
        return null;
    }

    $current_platform = $platform_override ?? ($GLOBALS['platform'] ?? 'telegram');

    if ($current_platform === 'bale') {
        $api_base_url = defined('BALE_API_BASE_URL') ? BALE_API_BASE_URL : 'https://tapi.bale.ai';
        $bot_token = defined('BALE_BOT_TOKEN') ? BALE_BOT_TOKEN : '';
    } else {
        $api_base_url = defined('TELEGRAM_API_BASE_URL') ? TELEGRAM_API_BASE_URL : 'https://api.telegram.org';
        $bot_token = defined('TELEGRAM_BOT_TOKEN') ? TELEGRAM_BOT_TOKEN : '';
    }

    // لاگ اطلاعات پیکربندی
    if (defined('ERROR_LOG_PATH')) { 
        file_put_contents(
            ERROR_LOG_PATH, 
            date('Y-m-d H:i:s') . " - API Config Debug - Platform: {$current_platform}, Base URL: {$api_base_url}, Token: " . (strlen($bot_token) > 10 ? substr($bot_token, 0, 10) . '...' : 'empty') . "\n", 
            FILE_APPEND
        ); 
    }

    if (empty($api_base_url) || empty($bot_token)) {
        if (defined('ERROR_LOG_PATH')) { 
            file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - API Request Error ({$current_platform}, Method: {$method}): Base URL or Bot Token is empty.\n", FILE_APPEND); 
        }
        return ['ok' => false, 'description' => "API Base URL or Bot Token is missing for {$current_platform}.", 'error_code' => -3];
    }

    // ساخت URL با فرمت صحیح برای هر پلتفرم
    if ($current_platform === 'bale') {
        $url = rtrim($api_base_url, '/') . '/bot' . $bot_token . '/' . $method;
    } else {
        $url = rtrim($api_base_url, '/') . '/bot' . ltrim($bot_token, '/') . '/' . $method;
    }

    $is_multipart = false;
    foreach ($parameters as $key => $value) {
        if ($value instanceof CURLFile) {
            $is_multipart = true;
            break;
        }
    }

    // لاگ اطلاعات درخواست
    if (defined('ERROR_LOG_PATH')) { 
        $log_params = $is_multipart ? '[Multipart Data]' : json_encode($parameters, JSON_UNESCAPED_UNICODE);
        file_put_contents(
            ERROR_LOG_PATH, 
            date('Y-m-d H:i:s') . " - API Request Debug - Platform: {$current_platform}, Method: {$method}, URL: {$url}, Multipart: " . ($is_multipart ? 'Yes' : 'No') . "\n", 
            FILE_APPEND
        ); 
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; BotApiService/1.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // مدیریت هدرها برای حالت‌های مختلف
    if ($is_multipart) {
        if (isset($parameters['reply_markup']) && is_array($parameters['reply_markup'])) {
            $parameters['reply_markup'] = json_encode($parameters['reply_markup'], JSON_UNESCAPED_UNICODE);
        }
        
        if ($current_platform === 'bale' && isset($parameters['media'])) {
            unset($parameters['media']);
        } elseif (isset($parameters['media']) && is_array($parameters['media'])) {
            $parameters['media'] = json_encode($parameters['media'], JSON_UNESCAPED_UNICODE);
        }
        
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
    } else {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $json_payload = json_encode($parameters, JSON_UNESCAPED_UNICODE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
    }

    $response_json = curl_exec($ch);
    $curl_error = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // لاگ پاسخ کامل
    if (defined('ERROR_LOG_PATH')) { 
        $response_length = is_string($response_json) ? strlen($response_json) : 0;
        $response_preview = is_string($response_json) ? substr($response_json, 0, 1000) : '[Non-string response]';
        file_put_contents(
            ERROR_LOG_PATH, 
            date('Y-m-d H:i:s') . " - API Response Debug - Platform: {$current_platform}, Method: {$method}, HTTP Code: {$http_code}, Response Length: {$response_length}, cURL Error: " . ($curl_error ?: 'None') . "\nResponse Preview: {$response_preview}\n", 
            FILE_APPEND
        ); 
    }

    if ($curl_error) {
        $log_curl_error = is_string($curl_error) ? $curl_error : json_encode($curl_error);
        if (defined('ERROR_LOG_PATH')) { 
            $log_message = date('Y-m-d H:i:s') . " - cURL Error ({$current_platform}, Method: {$method}): {$log_curl_error} | URL: {$url}\n";
            file_put_contents(ERROR_LOG_PATH, $log_message, FILE_APPEND); 
        }
        return ['ok' => false, 'description' => "cURL Error: " . $log_curl_error, 'error_code' => $http_code ?: -1];
    }

    $response_data = json_decode($response_json, true);
    if ($response_data === null && json_last_error() !== JSON_ERROR_NONE) {
        $raw_response_full = is_string($response_json) ? $response_json : '[Non-string response]';
        $json_error = json_last_error_msg();
        if (defined('ERROR_LOG_PATH')) { 
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - API JSON Decode Error ({$current_platform}, Method: {$method}, HTTP: {$http_code}, JSON Error: {$json_error})\nFull Response: {$raw_response_full}\n", 
                FILE_APPEND
            ); 
        }
        return ['ok' => false, 'description' => "Failed to decode API JSON response: " . $json_error, 'error_code' => -2, 'raw_response' => $raw_response_full];
    }

    if ($http_code !== 200 || !($response_data['ok'] ?? false)) {
        $error_message_raw = $response_data['description'] ?? 'Unknown API Error or non-OK response';
        $error_code = $response_data['error_code'] ?? $http_code;

        $error_message_log = is_string($error_message_raw) ? $error_message_raw : json_encode($error_message_raw, JSON_UNESCAPED_UNICODE);

        $log_data = [
            'platform' => $current_platform,
            'method' => $method,
            'http_code' => $http_code,
            'error_code' => $error_code,
            'error_message' => $error_message_log,
            'url' => $url
        ];
        
        if (defined('ERROR_LOG_PATH')) { 
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - Bot API Error: " . json_encode($log_data, JSON_UNESCAPED_UNICODE) . "\n", 
                FILE_APPEND
            ); 
        }

        return ['ok' => false, 'description' => $error_message_log, 'error_code' => $error_code];
    }

    return $response_data;
}

function sendMessage(int $chat_id, string $text, ?array $reply_markup = null, ?string $platform = null): ?array {
    $target_platform = $platform ?? ($GLOBALS['platform'] ?? 'telegram');

    $params = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'Markdown'];
    if ($reply_markup !== null) {
        $params['reply_markup'] = $reply_markup;
    }
    
    if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true && $target_platform === 'telegram') {
        return apiRequest('sendMessage', $params, $target_platform);
    }
    
    return sendPushMessage($target_platform, $chat_id, $text, $reply_markup);
}

function editMessage(int $chat_id, int $message_id, string $text, ?array $reply_markup = null, bool $is_caption = false, ?string $platform = null): ?array {
    $target_platform = $platform ?? ($GLOBALS['platform'] ?? 'telegram');
    $params = ['chat_id' => $chat_id, 'message_id' => $message_id, 'parse_mode' => 'Markdown'];
    if ($reply_markup !== null) {
        $params['reply_markup'] = ['inline_keyboard' => $reply_markup['inline_keyboard'] ?? []];
    }

    $method = $is_caption ? 'editMessageCaption' : 'editMessageText';
    if ($is_caption) {
        $params['caption'] = $text;
    } else {
        $params['text'] = $text;
    }

    if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true && $target_platform === 'telegram') {
        return apiRequest($method, $params, $target_platform);
    }

    return sendPushMessage($target_platform, $chat_id, $text, $reply_markup, $method, null, $message_id, $is_caption);
}

function sendDocument(int $chat_id, string $file_path_or_id, string $caption = '', ?string $platform = null): bool {
    $target_platform = $platform ?? ($GLOBALS['platform'] ?? 'telegram');
    $document_payload = null;

    if (filter_var($file_path_or_id, FILTER_VALIDATE_URL)) {
        $document_payload = $file_path_or_id;
    } elseif (is_file($file_path_or_id) && is_readable($file_path_or_id)) {
        $document_payload = new CURLFile(realpath($file_path_or_id));
    } else {
        $document_payload = $file_path_or_id;
    }
    
    if ($document_payload === null) {
        if (defined('ERROR_LOG_PATH')) { 
            $safe_file_path = is_string($file_path_or_id) ? $file_path_or_id : json_encode($file_path_or_id);
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - File Error: Document is not a valid file, URL, or file_id: {$safe_file_path}\n", 
                FILE_APPEND
            ); 
        }
        return false;
    }

    $response = null;
    
    if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true && $target_platform === 'telegram') {
        $response = sendPushMessage($target_platform, $chat_id, $caption, null, 'sendDocument', $document_payload);
    } else {
        $response = sendPushMessage($target_platform, $chat_id, $caption, null, 'sendDocument', $document_payload);
    }

    return ($response['ok'] ?? false);
}

function sendPhotoWithButtons(int $chat_id, $file_id_or_url, string $caption, array $inline_keyboard_rows, ?string $platform = null): ?array {
    $target_platform = $platform ?? ($GLOBALS['platform'] ?? 'telegram');
    $reply_markup = ['inline_keyboard' => $inline_keyboard_rows];

    if (empty($file_id_or_url)) {
        $safe_platform = is_string($target_platform) ? htmlspecialchars($target_platform) : 'unknown';
        $error_caption = $caption . "\n\n⚠️ *خطا: تصویر برای نمایش در این پلتفرم ({$safe_platform}) یافت نشد.*";
        return sendMessage($chat_id, $error_caption, $reply_markup, $target_platform);
    }

    // پارامترهای استاندارد برای sendPhoto
    $params = [
        'chat_id' => $chat_id,
        'caption' => $caption,
        'parse_mode' => 'Markdown'
    ];

    // افزودن reply_markup اگر وجود دارد
    if (!empty($reply_markup['inline_keyboard'])) {
        $params['reply_markup'] = $reply_markup;
    }

    // تنظیم پارامتر photo
    $params['photo'] = $file_id_or_url;

    // برای دیباگ
    if (defined('ERROR_LOG_PATH')) { 
        $file_type = gettype($file_id_or_url);
        $file_preview = is_string($file_id_or_url) ? (strlen($file_id_or_url) > 50 ? substr($file_id_or_url, 0, 50) . '...' : $file_id_or_url) : $file_type;
        file_put_contents(
            ERROR_LOG_PATH, 
            date('Y-m-d H:i:s') . " - sendPhotoWithButtons Debug - Platform: {$target_platform}, Chat ID: {$chat_id}, File: {$file_preview}\n", 
            FILE_APPEND
        ); 
    }

    // استفاده مستقیم از apiRequest برای هر دو پلتفرم
    return apiRequest('sendPhoto', $params, $target_platform);
}

function notifyAdmins(string $message, ?array $reply_markup = null): void {
    try {
        $stmt = pdo()->query("SELECT telegram_chat_id, bale_chat_id FROM users WHERE is_admin = TRUE AND is_active = TRUE AND (telegram_chat_id IS NOT NULL OR bale_chat_id IS NOT NULL)");
        $admins = $stmt->fetchAll();

        if (empty($admins)) {
            if (defined('ERROR_LOG_PATH')) { 
                file_put_contents(
                    ERROR_LOG_PATH, 
                    date('Y-m-d H:i:s') . " - Admin Notification Warning: No active admins with chat IDs found to notify.\n", 
                    FILE_APPEND
                ); 
            }
            return;
        }

        foreach ($admins as $admin) {
            if (!empty($admin['telegram_chat_id'])) {
                sendPushMessage('telegram', $admin['telegram_chat_id'], $message, $reply_markup);
                usleep(50000);
            }
            if (!empty($admin['bale_chat_id'])) {
                sendPushMessage('bale', $admin['bale_chat_id'], $message, $reply_markup);
                usleep(50000);
            }
        }
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { 
            $error_msg = is_string($e->getMessage()) ? $e->getMessage() : json_encode($e->getMessage());
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - DB Error fetching admins for notification: {$error_msg}\n", 
                FILE_APPEND
            ); 
        }
    } catch (Exception $e) {
        if (defined('ERROR_LOG_PATH')) { 
            $error_msg = is_string($e->getMessage()) ? $e->getMessage() : json_encode($e->getMessage());
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - Error notifying admins: {$error_msg}\n", 
                FILE_APPEND
            ); 
        }
    }
}

function notifyAdminsWithPhoto(?string $telegram_file_id, ?string $bale_file_id, string $caption, array $inline_keyboard_rows): void {
    try {
        $stmt = pdo()->query("SELECT id, telegram_chat_id, bale_chat_id FROM users WHERE is_admin = TRUE AND is_active = TRUE AND (telegram_chat_id IS NOT NULL OR bale_chat_id IS NOT NULL)");
        $admins = $stmt->fetchAll();
        $reply_markup = ['inline_keyboard' => $inline_keyboard_rows];

        if (empty($admins)) {
            if (defined('ERROR_LOG_PATH')) { 
                file_put_contents(
                    ERROR_LOG_PATH, 
                    date('Y-m-d H:i:s') . " - Admin Photo Notification Warning: No active admins with chat IDs found.\n", 
                    FILE_APPEND
                ); 
            }
            return;
        }

        foreach ($admins as $admin) {
            $admin_internal_id = $admin['id']; 
            
            if (!empty($admin['telegram_chat_id'])) {
                if (!empty($telegram_file_id)) {
                    $response = sendPushMessage('telegram', $admin['telegram_chat_id'], $caption, $reply_markup, 'sendPhoto', $telegram_file_id);
                    
                    if ($response && ($response['ok'] ?? false) && isset($response['result']['message_id']) && isset($GLOBALS['current_pending_request_id'])) {
                        storeAdminRequestMessage($GLOBALS['current_pending_request_id'], $admin_internal_id, 'telegram', $admin['telegram_chat_id'], $response['result']['message_id']);
                    }
                } else {
                    $text_fallback = $caption . "\n\n⚠️ *تصویر در تلگرام موجود نیست.*";
                    $response = sendPushMessage('telegram', $admin['telegram_chat_id'], $text_fallback, $reply_markup);
                    
                    if ($response && ($response['ok'] ?? false) && isset($response['result']['message_id']) && isset($GLOBALS['current_pending_request_id'])) {
                        storeAdminRequestMessage($GLOBALS['current_pending_request_id'], $admin_internal_id, 'telegram', $admin['telegram_chat_id'], $response['result']['message_id']);
                    }
                }
                usleep(50000);
            }

            if (!empty($admin['bale_chat_id'])) {
                if (!empty($bale_file_id)) {
                    $response = sendPushMessage('bale', $admin['bale_chat_id'], $caption, $reply_markup, 'sendPhoto', $bale_file_id);
                    
                    if ($response && ($response['ok'] ?? false) && isset($response['result']['message_id']) && isset($GLOBALS['current_pending_request_id'])) {
                        storeAdminRequestMessage($GLOBALS['current_pending_request_id'], $admin_internal_id, 'bale', $admin['bale_chat_id'], $response['result']['message_id']);
                    }
                } else {
                    $text_fallback = $caption . "\n\n⚠️ *تصویر در بله موجود نیست.*";
                    $response = sendPushMessage('bale', $admin['bale_chat_id'], $text_fallback, $reply_markup);
                    
                    if ($response && ($response['ok'] ?? false) && isset($response['result']['message_id']) && isset($GLOBALS['current_pending_request_id'])) {
                        storeAdminRequestMessage($GLOBALS['current_pending_request_id'], $admin_internal_id, 'bale', $admin['bale_chat_id'], $response['result']['message_id']);
                    }
                }
                usleep(50000);
            }
        }
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { 
            $error_msg = is_string($e->getMessage()) ? $e->getMessage() : json_encode($e->getMessage());
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - DB Error fetching admins for photo notification: {$error_msg}\n", 
                FILE_APPEND
            ); 
        }
    } catch (Exception $e) {
        if (defined('ERROR_LOG_PATH')) { 
            $error_msg = is_string($e->getMessage()) ? $e->getMessage() : json_encode($e->getMessage());
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - Error notifying admins with photo: {$error_msg}\n", 
                FILE_APPEND
            ); 
        }
    }
}

function downloadFileContent(string $source_file_id, string $source_platform): ?string {
    try {
        if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true && $source_platform === 'telegram') {
            
            if (!defined('BRIDGE_SECRET_TOKEN')) {
                throw new Exception("BRIDGE_SECRET_TOKEN is not defined on Iran server.");
            }
            if (!isset($GLOBALS['config']['BRIDGE_DOWNLOAD_URL'])) {
                throw new Exception("BRIDGE_DOWNLOAD_URL is not defined in \$GLOBALS['config'] (set this in telegram_bridge.php).");
            }

            $bridge_url = $GLOBALS['config']['BRIDGE_DOWNLOAD_URL'];
            $data = ['file_id' => $source_file_id];
            
            $ch = curl_init($bridge_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'X-Bridge-Token: ' . BRIDGE_SECRET_TOKEN
            ]);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            
            $file_content = curl_exec($ch);
            $dl_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $dl_curl_error = curl_error($ch);
            curl_close($ch);

            if ($dl_curl_error || $dl_http_code !== 200 || $file_content === false || empty($file_content)) {
                $error_snippet = is_string($file_content) ? substr($file_content, 0, 200) : '[Non-string content]';
                $safe_curl_error = is_string($dl_curl_error) ? $dl_curl_error : json_encode($dl_curl_error);
                 throw new Exception("Failed download from BRIDGE - HTTP: {$dl_http_code}, cURL Error: {$safe_curl_error}, Response Snippet: {$error_snippet}");
            }
            
            return $file_content;

        } else {
            
            $download_token = null;
            $get_file_api_base = null;
            $download_api_base = null;

            if ($source_platform === 'telegram') {
                $download_token = defined('TELEGRAM_BOT_TOKEN') ? TELEGRAM_BOT_TOKEN : null;
                $get_file_api_base = defined('TELEGRAM_API_BASE_URL') ? rtrim(TELEGRAM_API_BASE_URL, '/') . '/' : null; 
                $download_api_base = 'https://api.telegram.org/file/'; 
            } elseif ($source_platform === 'bale') {
                $download_token = defined('BALE_BOT_TOKEN') ? BALE_BOT_TOKEN : null;
                $get_file_api_base = defined('BALE_API_BASE_URL') ? rtrim(BALE_API_BASE_URL, '/') . '/' : null; 
                $download_api_base = 'https://tapi.bale.ai/file/'; 
            } else {
                throw new Exception("Invalid source platform '{$source_platform}'.");
            }

            if (!$download_token || !$get_file_api_base || !$download_api_base) {
                throw new Exception("Missing configuration: Download token or API base URLs for platform '{$source_platform}'.");
            }

            // ساخت URL برای دریافت اطلاعات فایل
            if ($source_platform === 'bale') {
                $get_file_url = $get_file_api_base . 'bot' . $download_token . '/getFile';
            } else {
                $get_file_url = $get_file_api_base . 'bot' . $download_token . '/getFile';
            }
            
            $ch_getfile = curl_init($get_file_url . '?' . http_build_query(['file_id' => $source_file_id]));
            curl_setopt($ch_getfile, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_getfile, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($ch_getfile, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch_getfile, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch_getfile, CURLOPT_SSL_VERIFYHOST, false);
            
            $get_file_response_json = curl_exec($ch_getfile);
            $get_file_http_code = curl_getinfo($ch_getfile, CURLINFO_HTTP_CODE);
            $get_file_curl_error = curl_error($ch_getfile);
            curl_close($ch_getfile);

            if ($get_file_curl_error) {
                $safe_error = is_string($get_file_curl_error) ? $get_file_curl_error : json_encode($get_file_curl_error);
                throw new Exception("cURL Error on getFile: " . $safe_error);
            }
            
            $getFileResponse = json_decode($get_file_response_json, true);
            
            if ($get_file_http_code !== 200 || !($getFileResponse['ok'] ?? false) || empty($getFileResponse['result']['file_path'])) {
                $desc = isset($getFileResponse['description']) ? (is_string($getFileResponse['description']) ? $getFileResponse['description'] : json_encode($getFileResponse['description'])) : 'No file_path found';
                throw new Exception("Failed to getFile info directly from {$source_platform} (HTTP: {$get_file_http_code}): " . $desc);
            }
            
            $file_path_on_server = $getFileResponse['result']['file_path'];
            
            // ساخت URL برای دانلود فایل
            if ($source_platform === 'bale') {
                $download_url = rtrim($download_api_base, '/') . '/bot' . $download_token . '/' . ltrim($file_path_on_server, '/');
            } else {
                $download_url = rtrim($download_api_base, '/') . '/bot' . $download_token . '/' . ltrim($file_path_on_server, '/');
            }
            
            $ch_dl = curl_init($download_url);
            curl_setopt($ch_dl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_dl, CURLOPT_CONNECTTIMEOUT, 15);
            curl_setopt($ch_dl, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch_dl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch_dl, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch_dl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch_dl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            
            $file_content = curl_exec($ch_dl);
            $dl_http_code = curl_getinfo($ch_dl, CURLINFO_HTTP_CODE);
            $dl_curl_error = curl_error($ch_dl);
            curl_close($ch_dl);

            if ($dl_curl_error || $dl_http_code !== 200 || $file_content === false || empty($file_content)) {
                $safe_error = is_string($dl_curl_error) ? $dl_curl_error : json_encode($dl_curl_error);
                throw new Exception("Failed download from API - HTTP: {$dl_http_code}, cURL Error: {$safe_error}");
            }
            
            return $file_content;
        }

    } catch (Exception $e) {
        if (defined('ERROR_LOG_PATH')) { 
            $error_msg = is_string($e->getMessage()) ? $e->getMessage() : json_encode($e->getMessage());
            file_put_contents(
                ERROR_LOG_PATH, 
                date('Y-m-d H:i:s') . " - downloadFileContent Error: {$error_msg}\n", 
                FILE_APPEND
            ); 
        }
        return null;
    }
}

function sendPushMessage(string $platform, int $chat_id, string $text, ?array $reply_markup = null, string $method = 'sendMessage', $file_id = null, ?int $message_id = null, bool $is_caption = false): ?array {
    
    if (defined('IS_BRIDGE_CALL') && IS_BRIDGE_CALL === true) {
        
        if ($platform === 'bale') {
            $params = ['chat_id' => $chat_id, 'parse_mode' => 'Markdown'];
            if ($reply_markup !== null) $params['reply_markup'] = $reply_markup;
            
            if ($method === 'editMessageCaption') {
                $params['message_id'] = $message_id;
                $params['caption'] = $text;
            } elseif ($method === 'editMessageText') {
                $params['message_id'] = $message_id;
                $params['text'] = $text;
            } elseif ($method === 'sendPhoto') {
                $params['photo'] = $file_id;
                $params['caption'] = $text;
            } elseif ($method === 'sendDocument') {
                $params['document'] = $file_id;
                $params['caption'] = $text;
            } else {
                $method = 'sendMessage';
                $params['text'] = $text;
            }
            return apiRequest($method, $params, 'bale');
        }
        
        if ($platform === 'telegram' && ($method === 'sendPhoto' || $method === 'sendDocument')) {
            // ادامه پردازش در بلاک پایین‌تر برای استفاده از بریج
        } else {
            if ($method === 'editMessageCaption') {
                return apiRequest($method, ['chat_id' => $chat_id, 'message_id' => $message_id, 'caption' => $text, 'reply_markup' => $reply_markup, 'parse_mode' => 'Markdown'], $platform);
            } elseif ($method === 'editMessageText') {
                return apiRequest($method, ['chat_id' => $chat_id, 'message_id' => $message_id, 'text' => $text, 'reply_markup' => $reply_markup, 'parse_mode' => 'Markdown'], $platform);
            }
            
            return apiRequest('sendMessage', ['chat_id' => $chat_id, 'text' => $text, 'reply_markup' => $reply_markup, 'parse_mode' => 'Markdown'], $platform);
        }
    }
    
    if ($platform === 'bale') {
        $params = ['chat_id' => $chat_id, 'parse_mode' => 'Markdown'];
        if ($reply_markup !== null) $params['reply_markup'] = $reply_markup;
        
        if ($method === 'editMessageCaption') {
            $params['message_id'] = $message_id;
            $params['caption'] = $text;
        } elseif ($method === 'editMessageText') {
            $params['message_id'] = $message_id;
            $params['text'] = $text;
        } elseif ($method === 'sendPhoto') {
            $params['photo'] = $file_id;
            $params['caption'] = $text;
        } elseif ($method === 'sendDocument') {
            $params['document'] = $file_id;
            $params['caption'] = $text;
        } else {
            $method = 'sendMessage';
            $params['text'] = $text;
        }
        return apiRequest($method, $params, 'bale');
    }

    if ($platform === 'telegram') {
        if (!defined('BRIDGE_PUSH_URL') || !defined('BRIDGE_SECRET_TOKEN')) {
            if (defined('ERROR_LOG_PATH')) { 
                file_put_contents(
                    ERROR_LOG_PATH, 
                    date('Y-m-d H:i:s') . " - sendPushMessage Error: BRIDGE_PUSH_URL or BRIDGE_SECRET_TOKEN not defined in config.php.\n", 
                    FILE_APPEND
                ); 
            }
            return ['ok' => false, 'description' => 'Bridge push configuration missing.'];
        }

        $data = [
            'chat_id' => $chat_id,
            'text' => $text,
            'reply_markup' => $reply_markup,
            'method' => $method,
            'file_id' => $file_id,
            'message_id' => $message_id,
            'is_caption' => $is_caption,
            'parse_mode' => 'Markdown'
        ];
        
        $is_multipart_upload = ($file_id instanceof CURLFile);
        $jsonData = json_encode($data);
        $token = BRIDGE_SECRET_TOKEN;
        $url = BRIDGE_PUSH_URL;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if ($is_multipart_upload) {
            $payload = [
                'json_payload' => $jsonData,
                'file_content' => $file_id
            ];
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'X-Bridge-Token: ' . $token
            ]);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120); 
        } else {
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData),
                'X-Bridge-Token: ' . $token
            ]);
        }

        $response_json = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($curl_error || $http_code !== 200) {
            $safe_curl_error = is_string($curl_error) ? $curl_error : json_encode($curl_error);
            $safe_url = is_string($url) ? $url : json_encode($url);
            if (defined('ERROR_LOG_PATH')) { 
                file_put_contents(
                    ERROR_LOG_PATH, 
                    date('Y-m-d H:i:s') . " - sendPushMessage cURL Error: {$safe_curl_error} (HTTP: {$http_code}) | URL: {$safe_url}\n", 
                    FILE_APPEND
                ); 
            }
            return ['ok' => false, 'description' => "cURL Error: " . $safe_curl_error, 'error_code' => $http_code];
        }
        
        $response_data = json_decode($response_json, true);
        if ($response_data === null) {
            $safe_response = is_string($response_json) ? substr($response_json, 0, 200) : '[Non-string response]';
            if (defined('ERROR_LOG_PATH')) { 
                file_put_contents(
                    ERROR_LOG_PATH, 
                    date('Y-m-d H:i:s') . " - sendPushMessage JSON Decode Error. Raw: {$safe_response}\n", 
                    FILE_APPEND
                ); 
            }
            return ['ok' => false, 'description' => 'Failed to decode bridge push response.'];
        }
        
        return $response_data;
    }

    return ['ok' => false, 'description' => 'Invalid platform for push message.'];
}
?>