<?php
// ============================================================
//  Telegram API yordamchi funksiyalar
// ============================================================

require_once __DIR__ . '/config.php';

/**
 * Telegram API ga so'rov yuboradi
 */
function telegramRequest(string $method, array $params = []): array
{
    $url = API_URL . $method;
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $params,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $err      = curl_error($ch);
    curl_close($ch);

    if ($err) {
        logMessage("CURL error [{$method}]: {$err}");
        return [];
    }

    return json_decode($response, true) ?? [];
}

/**
 * Foydalanuvchiga matn xabar yuboradi
 */
function sendMessage(int|string $chatId, string $text, string $parseMode = 'HTML'): array
{
    return telegramRequest('sendMessage', [
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => $parseMode,
    ]);
}

/**
 * Foydalanuvchiga video yuboradi (≤50 MB)
 */
function sendVideo(int|string $chatId, string $filePath, string $caption = ''): array
{
    $params = [
        'chat_id'            => $chatId,
        'video'              => new CURLFile($filePath, 'video/mp4', basename($filePath)),
        'caption'            => $caption,
        'parse_mode'         => 'HTML',
        'supports_streaming' => 'true',
    ];
    return telegramRequest('sendVideo', $params);
}

/**
 * Foydalanuvchiga hujjat sifatida fayl yuboradi (katta fayllar uchun)
 */
function sendDocument(int|string $chatId, string $filePath, string $caption = ''): array
{
    $params = [
        'chat_id'    => $chatId,
        'document'   => new CURLFile($filePath, 'video/mp4', basename($filePath)),
        'caption'    => $caption,
        'parse_mode' => 'HTML',
    ];
    return telegramRequest('sendDocument', $params);
}

/**
 * "upload_video" holatini ko'rsatadi
 */
function sendUploadAction(int|string $chatId): void
{
    telegramRequest('sendChatAction', [
        'chat_id' => $chatId,
        'action'  => 'upload_video',
    ]);
}

/**
 * Mavjud xabarni tahrirlaydi
 */
function editMessage(int|string $chatId, int $messageId, string $text): array
{
    return telegramRequest('editMessageText', [
        'chat_id'    => $chatId,
        'message_id' => $messageId,
        'text'       => $text,
        'parse_mode' => 'HTML',
    ]);
}

/**
 * Matndan m3u8 URL ni ajratib oladi
 */
function extractM3u8Url(string $text): ?string
{
    // http yoki https bilan boshlanib, .m3u8 bilan tugaydigan yoki /m3u8 bo'limini o'z ichiga olgan URL
    $pattern = '/https?:\/\/[^\s<>"\']+?(?:\.m3u8|\/playlist\.m3u8|\/index\.m3u8)(?:\?[^\s<>"\']*)?/i';
    if (preg_match($pattern, $text, $matches)) {
        return $matches[0];
    }
    // Ba'zi URL larda kengaytma bo'lmaydi, lekin m3u8 so'zi bor
    $pattern2 = '/https?:\/\/[^\s<>"\']*m3u8[^\s<>"\']*/i';
    if (preg_match($pattern2, $text, $matches)) {
        return $matches[0];
    }
    return null;
}

/**
 * Log yozadi
 */
function logMessage(string $message): void
{
    $date    = date('Y-m-d H:i:s');
    $logFile = LOG_DIR . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log';
    file_put_contents($logFile, "[{$date}] {$message}" . PHP_EOL, FILE_APPEND | LOCK_EX);
}

/**
 * Fayl hajmini o'qilishi oson formatda qaytaradi
 */
function formatBytes(int $bytes): string
{
    if ($bytes >= 1073741824) {
        return round($bytes / 1073741824, 2) . ' GB';
    }
    if ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    }
    if ($bytes >= 1024) {
        return round($bytes / 1024, 2) . ' KB';
    }
    return $bytes . ' B';
}

/**
 * Xavfsiz fayl nomini generatsiya qiladi
 */
function generateFilename(int|string $chatId): string
{
    return 'video_' . $chatId . '_' . time() . '_' . rand(1000, 9999) . '.mp4';
}
