<?php
// ============================================================
//  M3U8 → MP4 Telegram Bot — Asosiy Webhook Handler
//  URL: https://yoursite.com/videoupload/bot.php?secret=WEBHOOK_SECRET
// ============================================================

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

// ── 1. Webhook maxfiy kalitni tekshirish ──────────────────────
$secret = $_GET['secret'] ?? '';
if ($secret !== WEBHOOK_SECRET) {
    http_response_code(403);
    exit('Forbidden');
}

// ── 2. JSON so'rovni o'qish ───────────────────────────────────
$rawInput = file_get_contents('php://input');
$update   = json_decode($rawInput, true);

if (!$update) {
    http_response_code(200);
    exit('OK');
}

logMessage('Update: ' . substr($rawInput, 0, 500));

// ── 3. Callback query (inline button bosish) ──────────────────
if (!empty($update['callback_query'])) {
    $cb     = $update['callback_query'];
    $chatId = $cb['message']['chat']['id'];
    $data   = $cb['data'] ?? '';

    telegramRequest('answerCallbackQuery', ['callback_query_id' => $cb['id']]);

    if ($data === 'help') {
        sendHelp($chatId);
    } elseif ($data === 'status') {
        sendStatus($chatId);
    }

    http_response_code(200);
    exit('OK');
}

// ── 4. Xabarni ajratish ───────────────────────────────────────
$message = $update['message'] ?? $update['channel_post'] ?? null;
if (!$message) {
    http_response_code(200);
    exit('OK');
}

$chatId    = $message['chat']['id'];
$text      = trim($message['text'] ?? '');
$firstName = $message['from']['first_name'] ?? 'Do\'st';

if (!$text) {
    http_response_code(200);
    exit('OK');
}

// ── 5. /start ─────────────────────────────────────────────────
if ($text === '/start') {
    $welcome = "👋 <b>Salom, {$firstName}!</b>\n\n"
        . "🎬 <b>M3U8 → MP4 1080p Konvertor Bot</b>\n\n"
        . "Men sizga m3u8 havolasini <b>1080p MP4</b> videoga o'girib beraman.\n\n"
        . "📤 <b>Ishlatish juda oddiy:</b>\n"
        . "Menga m3u8 havolasini yuboring — xolos!\n\n"
        . "<code>https://example.com/stream/playlist.m3u8</code>";

    telegramRequest('sendMessage', [
        'chat_id'      => $chatId,
        'text'         => $welcome,
        'parse_mode'   => 'HTML',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [
                    ['text' => '❓ Qo\'llanma', 'callback_data' => 'help'],
                    ['text' => '🖥 Server holati', 'callback_data' => 'status'],
                ]
            ]
        ]),
    ]);

    http_response_code(200);
    exit('OK');
}

// ── 6. /help ─────────────────────────────────────────────────
if ($text === '/help') {
    sendHelp($chatId);
    http_response_code(200);
    exit('OK');
}

// ── 7. /status ───────────────────────────────────────────────
if ($text === '/status') {
    sendStatus($chatId);
    http_response_code(200);
    exit('OK');
}

// ── 8. m3u8 URL ni aniqlash ───────────────────────────────────
$m3u8Url = extractM3u8Url($text);

if (!$m3u8Url) {
    telegramRequest('sendMessage', [
        'chat_id'             => $chatId,
        'text'                => "❌ <b>M3U8 havola topilmadi.</b>\n\n"
            . "To'g'ri havola yuboring:\n"
            . "<code>https://example.com/stream/playlist.m3u8</code>\n\n"
            . "Havola <code>.m3u8</code> bilan tugashi kerak.",
        'parse_mode'          => 'HTML',
        'reply_to_message_id' => $message['message_id'],
        'reply_markup'        => json_encode([
            'inline_keyboard' => [[
                ['text' => '❓ Qo\'llanma', 'callback_data' => 'help'],
            ]]
        ]),
    ]);
    http_response_code(200);
    exit('OK');
}

// ── 9. FFmpeg mavjudligini tekshirish ─────────────────────────
if (!file_exists(FFMPEG_PATH)) {
    sendMessage($chatId,
        "⚠️ <b>Server xatosi:</b> FFmpeg o'rnatilmagan.\n"
        . "Administrator bilan bog'laning."
    );
    logMessage("FFmpeg not found: " . FFMPEG_PATH);
    http_response_code(200);
    exit('OK');
}

// ── 10. Kutish xabari ────────────────────────────────────────
$waitResult = sendMessage($chatId,
    "⏳ <b>Qabul qilindi!</b>\n\n"
    . "🔗 <b>Havola:</b>\n"
    . "<code>" . htmlspecialchars(substr($m3u8Url, 0, 100)) . (strlen($m3u8Url) > 100 ? '...' : '') . "</code>\n\n"
    . "🔄 <b>Jarayon:</b>\n"
    . "├ ✅ Havola aniqlandi\n"
    . "├ 🔄 FFmpeg yuklamoqda...\n"
    . "└ ⏳ 1080p MP4 ga o'tkazilmoqda...\n\n"
    . "⌛ <i>Video hajmiga qarab 1–15 daqiqa vaqt ketadi</i>"
);

$waitMsgId = $waitResult['result']['message_id'] ?? null;

// ── 11. Worker.php ni background da ishga tushirish ──────────
$phpPath    = PHP_PATH;
$workerPath = __DIR__ . DIRECTORY_SEPARATOR . 'worker.php';
$escapedUrl = escapeshellarg($m3u8Url);
$escapedCid = escapeshellarg((string)$chatId);
$escapedMid = escapeshellarg((string)($waitMsgId ?? 0));

if (PHP_OS_FAMILY === 'Windows') {
    // Windows: start /B fon jarayoni
    $cmd = "start /B \"\" \"{$phpPath}\" \"{$workerPath}\" {$escapedCid} {$escapedUrl} {$escapedMid}";
    pclose(popen($cmd, 'r'));
} else {
    // Linux: to'g'ridan-to'g'ri fon jarayon
    $cmd = "\"{$phpPath}\" \"{$workerPath}\" {$escapedCid} {$escapedUrl} {$escapedMid} > /dev/null 2>&1 &";
    exec($cmd);
}

logMessage("Worker started | chat_id={$chatId} | url={$m3u8Url}");

http_response_code(200);
echo 'OK';

// ============================================================
//  Yordamchi funksiyalar
// ============================================================

function sendHelp(int|string $chatId): void
{
    $text = "📖 <b>Qo'llanma</b>\n\n"
        . "<b>Ishlatish:</b>\n"
        . "Telegram da menga m3u8 havolasini yuboring:\n"
        . "<code>https://example.com/video/playlist.m3u8</code>\n\n"
        . "<b>📊 Video sifati:</b>\n"
        . "• 🎬 Sifat: 1080p (1920×1080)\n"
        . "• 🎵 Audio: AAC 192kbps\n"
        . "• 📦 Format: MP4 (H.264)\n\n"
        . "<b>📦 Yuborish usuli:</b>\n"
        . "• ≤ 50 MB → Video sifatida yuboriladi\n"
        . "• > 50 MB → UserBot (MadelineProto) orqali yuboriladi\n\n"
        . "<b>⏱ Taxminiy vaqt:</b>\n"
        . "• 10 daqiqali video → ~1–2 daqiqa\n"
        . "• 60 daqiqali video → ~5–10 daqiqa\n\n"
        . "<b>📋 Buyruqlar:</b>\n"
        . "/start — Bosh menyu\n"
        . "/status — Server holati\n"
        . "/help — Shu qo'llanma";

    telegramRequest('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => 'HTML',
    ]);
}

function sendStatus(int|string $chatId): void
{
    $ffmpegOk   = file_exists(FFMPEG_PATH);
    $diskFree   = disk_free_space(DOWNLOAD_DIR);
    $diskOk     = $diskFree !== false && $diskFree > 512 * 1024 * 1024; // 512 MB
    $writeOk    = is_writable(DOWNLOAD_DIR);
    $vendorOk   = file_exists(__DIR__ . '/vendor/autoload.php');
    $sessionOk  = !empty(glob(__DIR__ . '/madeline_session/*.madeline'));

    $ffmpegVer = '';
    if ($ffmpegOk) {
        exec('"' . FFMPEG_PATH . '" -version 2>&1', $out);
        if (!empty($out[0])) {
            preg_match('/ffmpeg version ([^\s]+)/', $out[0], $m);
            $ffmpegVer = $m[1] ?? '';
        }
    }

    $text = "🖥 <b>Server Holati</b>\n\n"
        . ($ffmpegOk  ? "✅" : "❌") . " FFmpeg" . ($ffmpegVer ? " <code>{$ffmpegVer}</code>" : '') . "\n"
        . ($writeOk   ? "✅" : "❌") . " Downloads papkasi\n"
        . ($diskOk    ? "✅" : "⚠️") . " Disk bo'sh joy: <b>" . formatBytes($diskFree ?: 0) . "</b>\n"
        . ($vendorOk  ? "✅" : "❌") . " MadelineProto\n"
        . ($sessionOk ? "✅" : "⚠️") . " UserBot sessiyasi" . ($sessionOk ? '' : ' (setup_session.php kerak)') . "\n\n"
        . "🕐 <i>" . date('d.m.Y H:i:s') . "</i>";

    telegramRequest('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => 'HTML',
    ]);
}
