<?php
// ============================================================
//  MadelineProto UserBot Uploader (CLI)
//  Maqsad: 50 MB dan katta fayllarni UserBot orqali yuklash,
//           so'ng file_id ni Bot API orqali yuborish
//  Ishlatilishi: php madeline_uploader.php <chat_id> <file_path> <caption> [wait_msg_id]
// ============================================================

set_time_limit(0);

if (PHP_SAPI !== 'cli') {
    exit('Only CLI');
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/helpers.php';

// ── Argumentlar ───────────────────────────────────────────────
$chatId    = (string)($argv[1] ?? '');
$filePath  = (string)($argv[2] ?? '');
$caption   = (string)($argv[3] ?? '');
$waitMsgId = (int)($argv[4] ?? 0);

if (!$chatId || !$filePath || !file_exists($filePath)) {
    logMessage("madeline_uploader: argumentlar noto'g'ri. chat_id={$chatId}, file={$filePath}");
    exit(1);
}

logMessage("MadelineProto uploader START | chat_id={$chatId} | file=" . basename($filePath));

// ── MadelineProto Autoloader ──────────────────────────────────
$autoloader = __DIR__ . '/vendor/autoload.php';
if (!file_exists($autoloader)) {
    $errMsg = "❌ <b>MadelineProto o'rnatilmagan!</b>\n\n"
        . "Quyidagi buyruqni ishga tushiring:\n"
        . "<code>composer require danog/madelineproto</code>";
    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId, $errMsg);
    } else {
        sendMessage($chatId, $errMsg);
    }
    logMessage("MadelineProto vendor/autoload.php topilmadi!");
    exit(1);
}

require_once $autoloader;

use danog\MadelineProto\API;
use danog\MadelineProto\Settings;
use danog\MadelineProto\Settings\AppInfo;

// ── Session fayl yo'li ────────────────────────────────────────
$sessionFile = __DIR__ . '/madeline_session/' . MADELINE_SESSION_NAME . '.madeline';

if (!is_dir(dirname($sessionFile))) {
    mkdir(dirname($sessionFile), 0755, true);
}

try {
    // ── MadelineProto ni ishga tushirish ─────────────────────
    $settings = (new Settings)
        ->setAppInfo(
            (new AppInfo)
                ->setApiId(MADELINE_API_ID)
                ->setApiHash(MADELINE_API_HASH)
        );

    $MadelineProto = new API($sessionFile, $settings);

    // ── Foydalanuvchi kirganligini tekshirish ─────────────────
    // Agar session yo'q bo'lsa, login kerak — bu interaktiv jarayon
    // Bot birinchi marta ishga tushirilganda 'php setup_session.php' chaqiriladi
    $self = $MadelineProto->getSelf();
    if (!$self) {
        $errMsg = "❌ <b>UserBot sessiyasi yo'q!</b>\n\n"
            . "Birinchi marta login qilish uchun:\n"
            . "<code>php setup_session.php</code>\n"
            . "buyrug'ini terminalda ishga tushiring.";
        if ($waitMsgId) editMessage($chatId, $waitMsgId, $errMsg);
        else sendMessage($chatId, $errMsg);
        logMessage("MadelineProto: session yo'q");
        exit(1);
    }

    logMessage("MadelineProto: logged in as @" . ($self['username'] ?? $self['id']));

    // ── Progress xabari ───────────────────────────────────────
    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId,
            "📤 <b>Yuklanmoqda (UserBot)...</b>\n\n"
            . "📦 Hajm: <b>" . formatBytes(filesize($filePath)) . "</b>\n"
            . "⏳ Telegram serveriga upload qilinmoqda...\n"
            . "<i>Bu bir necha daqiqa vaqt olishi mumkin</i>"
        );
    }

    // ── Faylni Telegram ga yuklash (UserBot orqali) ───────────
    // messages.sendMedia → file_id qaytaradi
    $fileSize = filesize($filePath);

    // InputFile sifatida yuklash
    $inputFile = $MadelineProto->uploadFile($filePath);

    // media obyektini qurish
    $media = [
        '_'              => 'inputMediaUploadedDocument',
        'file'           => $inputFile,
        'attributes'     => [
            ['_' => 'documentAttributeFilename', 'file_name' => basename($filePath)],
            ['_' => 'documentAttributeVideo', 'supports_streaming' => true],
        ],
        'mime_type'      => 'video/mp4',
        'nosound_video'  => false,
    ];

    // UserBot orqali o'ziga (Saved Messages) yuborish → file_id olish
    $result = $MadelineProto->messages->sendMedia([
        'peer'    => 'me',    // Saved Messages ga yuborish
        'media'   => $media,
        'message' => '',
        'random_id' => random_int(PHP_INT_MIN, PHP_INT_MAX),
    ]);

    logMessage("MadelineProto: Saved Messages ga yuborildi");

    // ── file_id ni ajratib olish ──────────────────────────────
    $fileId    = null;
    $accessHash = null;

    $updates = $result['updates'] ?? [];
    foreach ($updates as $upd) {
        $msg = $upd['message'] ?? null;
        if (!$msg) continue;

        $document = $msg['media']['document'] ?? null;
        if ($document) {
            $fileId    = $document['id'];
            $accessHash = $document['access_hash'];
            break;
        }
    }

    if (!$fileId) {
        throw new \Exception("file_id ajratib olinmadi!");
    }

    logMessage("file_id olindi: {$fileId}");

    // ── Bot API orqali foydalanuvchiga yuborish ───────────────
    // Saved Messages dagi xabarni forward qilish
    // Yoki file_id ni ishlatib sendDocument

    // Forward: UserBot orqali foydalanuvchiga forward qilamiz
    $forwardResult = $MadelineProto->messages->forwardMessages([
        'from_peer' => 'me',
        'to_peer'   => (int)$chatId,
        'id'        => [$result['updates'][0]['message']['id'] ?? 0],
        'random_id' => [random_int(PHP_INT_MIN, PHP_INT_MAX)],
        'drop_author' => true,
    ]);

    logMessage("MadelineProto: foydalanuvchiga yuborildi (forward)");

    // ── Kutish xabarini o'chirish ─────────────────────────────
    if ($waitMsgId) {
        telegramRequest('deleteMessage', [
            'chat_id'    => $chatId,
            'message_id' => $waitMsgId,
        ]);
    }

    // ── Bot orqali caption xabari yuborish ───────────────────
    sendMessage($chatId, $caption . "\n\n✅ <i>UserBot orqali yuborildi</i>");

    // ── Saved Messages dagi xabarni o'chirish ─────────────────
    $msgId = $result['updates'][0]['message']['id'] ?? null;
    if ($msgId) {
        $MadelineProto->messages->deleteMessages([
            'revoke' => true,
            'id'     => [$msgId],
        ]);
    }

    logMessage("MadelineProto uploader SUCCESS | chat_id={$chatId}");

} catch (\Throwable $e) {
    $errText = $e->getMessage();
    logMessage("MadelineProto ERROR: {$errText}");

    $errMsg = "❌ <b>UserBot yuborishda xato:</b>\n<code>"
        . htmlspecialchars(substr($errText, 0, 300)) . "</code>";

    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId, $errMsg);
    } else {
        sendMessage($chatId, $errMsg);
    }
}

// ── Vaqtincha faylni o'chirish ────────────────────────────────
if (file_exists($filePath)) {
    unlink($filePath);
    logMessage("Temp file deleted: {$filePath}");
}
