<?php

$botToken = "8207042911:AAE81tQmRp6QkoXXXi4Ffqupn8-upfxt1eA";
$apiURL = "https://api.telegram.org/bot$botToken/";

$content = file_get_contents("php://input");
$update = json_decode($content, true);

// Exit if not text message
if (!isset($update["message"]["text"])) {
    exit;
}

$chatId = $update["message"]["chat"]["id"];
$text = trim($update["message"]["text"]);
$incomingMessageId = $update["message"]["message_id"];

// Handle /start command
if ($text === "/start") {
    $welcomeMessage = "👋 *Welcome to Terabox Direct Downloader Bot!*\n\n";
    $welcomeMessage .= "Just send me any valid *Terabox file URL* and I'll fetch:\n";
    $welcomeMessage .= "📁 File name\n📦 File size\n🔗 Direct download link\n📺 Streaming link (for videos)\n\n";
    $welcomeMessage .= "Example:\nhttps://www.terabox.com/s/abc123xyz";

    file_get_contents($apiURL . "sendMessage", false, stream_context_create([
        "http" => [
            "method" => "POST",
            "header" => "Content-Type: application/json",
            "content" => json_encode([
                "chat_id" => $chatId,
                "text" => $welcomeMessage,
                "parse_mode" => "Markdown"
            ])
        ]
    ]));
    exit;
}

// Check if valid Terabox URL
if (filter_var($text, FILTER_VALIDATE_URL) && strpos($text, 'terabox') !== false) {

    // Step 1: Send "processing" message replying to user
    $processingResponse = file_get_contents($apiURL . "sendMessage", false, stream_context_create([
        "http" => [
            "method" => "POST",
            "header" => "Content-Type: application/json",
            "content" => json_encode([
                "chat_id" => $chatId,
                "text" => "⏳ Processing your URL...",
                "reply_to_message_id" => $incomingMessageId
            ])
        ]
    ]));

    $processingData = json_decode($processingResponse, true);
    $processingMessageId = $processingData['result']['message_id'] ?? null;

    $encodedUrl = urlencode($text);

    // Call external API to get Terabox info
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://terabox-downloader-direct-download-link-generator2.p.rapidapi.com/url?url=$encodedUrl",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: terabox-downloader-direct-download-link-generator2.p.rapidapi.com",
            "x-rapidapi-key: c703eef4cdmsh37e41bd8403c00cp18db7ejsncfdd0fe5192d"
        ],
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    // Debug (uncomment if needed)
    // error_log("Terabox API Response: " . $response);

    $data = json_decode($response, true);

    if (json_last_error() === JSON_ERROR_NONE && is_array($data) && count($data) > 0) {
        $file = $data[0];

        $fileName = $file['file_name'] ?? 'Unknown';
        $fileSize = $file['size'] ?? 'Unknown size';
        $directLink = $file['direct_link'] ?? '';
        $backupLink = $file['link'] ?? '';
        $thumb = $file['thumb'] ?? '';

        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $videoTypes = ['mp4', 'webm', 'mkv', 'mov', 'avi'];

        $msg = "📁 *File Name:* `$fileName`\n";
        $msg .= "📦 *Size:* $fileSize\n";

        if ($directLink) {
            $msg .= "🔗 [Download Now]($directLink)\n";
        }

        if ($backupLink) {
            $msg .= "🔄 [Backup Link]($backupLink)\n";
        }

        if (in_array($fileExt, $videoTypes) && $directLink) {
            $msg .= "📺 *Preview:* [Stream Video]($directLink)";
        }

        // Send thumbnail if available
        if (!empty($thumb)) {
            file_get_contents($apiURL . "sendPhoto", false, stream_context_create([
                "http" => [
                    "method" => "POST",
                    "header" => "Content-Type: application/json",
                    "content" => json_encode([
                        "chat_id" => $chatId,
                        "photo" => $thumb,
                        "caption" => "🎞️ Thumbnail Preview"
                    ])
                ]
            ]));
        }

        // Send main message
        file_get_contents($apiURL . "sendMessage", false, stream_context_create([
            "http" => [
                "method" => "POST",
                "header" => "Content-Type: application/json",
                "content" => json_encode([
                    "chat_id" => $chatId,
                    "text" => $msg,
                    "parse_mode" => "Markdown",
                    "disable_web_page_preview" => false
                ])
            ]
        ]));

        // Delete the "processing" message after final response
        if ($processingMessageId !== null) {
            file_get_contents($apiURL . "deleteMessage", false, stream_context_create([
                "http" => [
                    "method" => "POST",
                    "header" => "Content-Type: application/json",
                    "content" => json_encode([
                        "chat_id" => $chatId,
                        "message_id" => $processingMessageId
                    ])
                ]
            ]));
        }

    } else {
        // Send error message
        file_get_contents($apiURL . "sendMessage", false, stream_context_create([
            "http" => [
                "method" => "POST",
                "header" => "Content-Type: application/json",
                "content" => json_encode([
                    "chat_id" => $chatId,
                    "text" => "⚠️ Could not fetch file data. Try again later."
                ])
            ]
        ]));

        // Delete processing message on error
        if ($processingMessageId !== null) {
            file_get_contents($apiURL . "deleteMessage", false, stream_context_create([
                "http" => [
                    "method" => "POST",
                    "header" => "Content-Type: application/json",
                    "content" => json_encode([
                        "chat_id" => $chatId,
                        "message_id" => $processingMessageId
                    ])
                ]
            ]));
        }
    }

} else {
    // If invalid message
    file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=❌ Please send a valid Terabox URL or type /start for help.");
}
