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

function transferFileBetweenPlatforms(string $source_file_id, string $source_platform): array {
    $result = ['telegram_id' => null, 'bale_id' => null];
    $temp_local_path = null;
    $download_platform = null;
    $upload_platform = null;
    $download_token = null;
    $download_api_base = null;
    $upload_chat_id = null;
    // --- START FIX: Remove verbose log handle ---
    // $verbose_log_handle = null; // No longer needed
    // --- END FIX ---

    try {
        $admin_target = getFirstAdminChatId();
        if (!$admin_target) {
          throw new Exception("No active admin with a chat ID found to receive transferred files.");
        }

        if ($source_platform === 'telegram') {
            $result['telegram_id'] = $source_file_id;
            $download_platform = 'telegram';
            $download_token = defined('TELEGRAM_BOT_TOKEN') ? TELEGRAM_BOT_TOKEN : null;
            $download_api_base = 'https://api.telegram.org/file/bot';
            $upload_platform = 'bale';
             $upload_chat_id = ($admin_target['platform'] === 'bale') ? $admin_target['chat_id'] : null;
            if (!$upload_chat_id) {
                $admin_target_bale = pdo()->query("SELECT bale_chat_id FROM users WHERE is_admin = TRUE AND is_active = TRUE AND bale_chat_id IS NOT NULL LIMIT 1")->fetchColumn();
                if (!$admin_target_bale) throw new Exception("No active Bale admin chat ID found for file transfer upload.");
                $upload_chat_id = $admin_target_bale;
            }
        } elseif ($source_platform === 'bale') {
            $result['bale_id'] = $source_file_id;
            $download_platform = 'bale';
            $download_token = defined('BALE_BOT_TOKEN') ? BALE_BOT_TOKEN : null;
            $download_api_base = 'https://tapi.bale.ai/file/bot';
            $upload_platform = 'telegram';
             $upload_chat_id = ($admin_target['platform'] === 'telegram') ? $admin_target['chat_id'] : null;
             if (!$upload_chat_id) {
                 $admin_target_tg = pdo()->query("SELECT telegram_chat_id FROM users WHERE is_admin = TRUE AND is_active = TRUE AND telegram_chat_id IS NOT NULL LIMIT 1")->fetchColumn();
                 if (!$admin_target_tg) throw new Exception("No active Telegram admin chat ID found for file transfer upload.");
                 $upload_chat_id = $admin_target_tg;
             }
        } else {
             throw new Exception("Invalid source platform '{$source_platform}'.");
        }

        if (!$download_token) {
             throw new Exception("Missing configuration: Download token for platform '{$download_platform}'.");
        }

        error_log("FileTransfer: Attempting getFile for {$source_file_id} on {$download_platform}.");
        $getFileResponse = apiRequest('getFile', ['file_id' => $source_file_id], $download_platform);
        error_log("FileTransfer: getFile response for {$source_file_id} on {$download_platform}: " . json_encode($getFileResponse));

        if (!($getFileResponse['ok'] ?? false) || empty($getFileResponse['result']['file_path'])) {
          throw new Exception("Failed to getFile info from {$download_platform}: " . ($getFileResponse['description'] ?? 'No file_path found'));
        }
         $file_path_on_server = $getFileResponse['result']['file_path'];
        error_log("FileTransfer: Extracted file_path = " . $file_path_on_server);

        $download_url = rtrim($download_api_base, '/') . '/' . $download_token . '/' . ltrim($file_path_on_server, '/');
        error_log("FileTransfer: Attempting download from: " . $download_url);

        $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_MAXREDIRS, 5);
        curl_setopt($ch_dl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch_dl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch_dl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
        
        // --- Force HTTP/1.1 ---
        curl_setopt($ch_dl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        // --- End Force HTTP/1.1 ---

        // --- START FIX: Remove verbose logging that leaks tokens ---
        // curl_setopt($ch_dl, CURLOPT_VERBOSE, true);
        // $verbose_log_path = defined('ERROR_LOG_PATH') ? str_replace('.log', '_curl_verbose.log', ERROR_LOG_PATH) : 'curl_verbose.log';
        // $verbose_log_handle = fopen($verbose_log_path, 'a');
        // if ($verbose_log_handle) {
        //     curl_setopt($ch_dl, CURLOPT_STDERR, $verbose_log_handle);
        //     error_log("FileTransfer: cURL verbose log will be written to: " . $verbose_log_path);
        // } else {
        //      error_log("FileTransfer: WARNING - Could not open verbose log file for writing: " . $verbose_log_path);
        // }
        // --- END FIX ---
          
        $file_content = curl_exec($ch_dl);
        $curl_info = curl_getinfo($ch_dl);
        $dl_http_code = $curl_info['http_code'];
        $dl_curl_error = curl_error($ch_dl);

        error_log("FileTransfer: Download finished. HTTP: {$dl_http_code}, cURL Error: " . ($dl_curl_error ?: 'None') . ", Content Length Received: " . ($curl_info['size_download'] ?? 'N/A') . ", Total Time: " . ($curl_info['total_time'] ?? 'N/A') . "s");

        curl_close($ch_dl);
        // --- START FIX: Remove verbose log handle ---
        // if ($verbose_log_handle) {
        //     fclose($verbose_log_handle);
        // }
        // --- END FIX ---

        if ($dl_curl_error || $dl_http_code !== 200 || $file_content === false || empty($file_content)) {
            $effective_url = $curl_info['url'] ?? $download_url;
            throw new Exception("Failed download from {$effective_url} (Original: {$download_url}) - HTTP: {$dl_http_code}, cURL Error: {$dl_curl_error}");
        }

        if (!defined('TMP_UPLOAD_DIR')) {
            throw new Exception("TMP_UPLOAD_DIR is not defined in config.");
        }
        $temp_dir = TMP_UPLOAD_DIR;
        if (!is_dir($temp_dir)) {
            if (!@mkdir($temp_dir, 0777, true)) {
                 throw new Exception("Failed to create temporary directory: {$temp_dir} (Check permissions)");
            }
        } elseif (!is_writable($temp_dir)) {
             throw new Exception("Temporary directory is not writable: {$temp_dir}");
        }

        $extension = pathinfo($file_path_on_server, PATHINFO_EXTENSION) ?: 'tmp';
        $temp_local_path = $temp_dir . '/sync_' . uniqid('', true) . '.' . $extension;

        if (file_put_contents($temp_local_path, $file_content) === false) {
          throw new Exception("Failed to write temporary file: {$temp_local_path} (Check permissions/disk space)");
        }
        unset($file_content);
        error_log("FileTransfer: File saved temporarily to: " . $temp_local_path);

        $mime_type = mime_content_type($temp_local_path) ?: 'application/octet-stream';
        $upload_filename = basename($file_path_on_server);
        $curl_file = new CURLFile(realpath($temp_local_path), $mime_type, $upload_filename);

        $upload_method = 'sendDocument';
        $file_param_key = 'document';
        if (strpos($mime_type, 'image/') === 0) { $upload_method = 'sendPhoto'; $file_param_key = 'photo'; }
        elseif (strpos($mime_type, 'video/') === 0) { $upload_method = 'sendVideo'; $file_param_key = 'video'; }
        elseif (strpos($mime_type, 'audio/') === 0) { $upload_method = 'sendAudio'; $file_param_key = 'audio'; }

        $params = ['chat_id' => $upload_chat_id, $file_param_key => $curl_file];
         error_log("FileTransfer: Attempting upload to {$upload_platform} admin chat {$upload_chat_id} using method {$upload_method}.");

        $uploadResponse = apiRequest($upload_method, $params, $upload_platform);
        error_log("FileTransfer: Upload response from {$upload_platform}: " . json_encode($uploadResponse));

        if (!($uploadResponse['ok'] ?? false)) {
            throw new Exception("Upload failed ({$upload_method} to {$upload_platform}): " . ($uploadResponse['description'] ?? 'Unknown API error'));
        }

        $new_file_id = null;
        if (isset($uploadResponse['result'])) {
            if ($upload_method === 'sendPhoto') {
                $photo_array = $uploadResponse['result']['photo'] ?? [];
                if (!empty($photo_array)) { $new_file_id = end($photo_array)['file_id']; }
            } elseif (isset($uploadResponse['result'][$file_param_key]['file_id'])) {
                $new_file_id = $uploadResponse['result'][$file_param_key]['file_id'];
            }
        }

        if (!$new_file_id) {
            throw new Exception("Could not extract file_id from {$upload_platform} response. Method: {$upload_method}. Resp: " . json_encode($uploadResponse));
        }
        error_log("FileTransfer: Extracted new file_id = " . $new_file_id);
        

          if ($upload_platform === 'bale') {
              $result['bale_id'] = $new_file_id;
        } else {
             $result['telegram_id'] = $new_file_id;
        }

    } catch (Exception $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - File Transfer Error: " . $e->getMessage() . "\n", FILE_APPEND); }
        if ($source_platform === 'telegram') { $result['telegram_id'] = $source_file_id; }
        if ($source_platform === 'bale') { $result['bale_id'] = $source_file_id; }
    } finally {
        // --- START FIX: Remove verbose log handle ---
        // if ($verbose_log_handle && is_resource($verbose_log_handle)) {
        //     fclose($verbose_log_handle);
        // }
        // --- END FIX ---
        if ($temp_local_path && file_exists($temp_local_path)) {
            if (@unlink($temp_local_path)) {
                error_log("FileTransfer: Successfully deleted temporary file: " . $temp_local_path);
            } else {
                 error_log("FileTransfer: WARNING - Failed to delete temporary file: " . $temp_local_path);
            }
        }
    }

    return $result;
}
?>