<?php
$telegramToken = '7625505683:AAFzH-W56MSNKcd1AWAMaWY5WeP84Ah9_LI';
$apiURL = "https://api.telegram.org/bot$telegramToken/";
$databaseFile = 'database.txt';

// Define multiple channels for force subscribe
$requiredChannels = ['xyz_lbni', 'NOOBPrivate', 'NOOBPrivateChats'];

// Get and decode incoming updates
$input = file_get_contents('php://input');
$update = json_decode($input, TRUE);

if (isset($update['message']['chat']['id'])) {
    $chatId = $update['message']['chat']['id'];

    // Handle /start command with Welcome Message and Force Subscribe Check
    if (isset($update['message']['text']) && $update['message']['text'] == '/start') {
        sendWelcomeMessage($chatId);
        if (!isUserSubscribedToAllChannels($chatId, $requiredChannels)) {
            promptForceSubscribe($chatId, $requiredChannels);
            exit;
        }
    }

    // Ensure force subscribe check before processing other messages
    if (!isUserSubscribedToAllChannels($chatId, $requiredChannels)) {
        promptForceSubscribe($chatId, $requiredChannels);
        exit;
    }

    // Handle various content types
    if (isset($update['message']['document'])) {
        handleFileUpload($update['message'], 'document');
    } elseif (isset($update['message']['photo'])) {
        handleFileUpload($update['message'], 'photo');
    } elseif (isset($update['message']['video'])) {
        handleFileUpload($update['message'], 'video');
    } elseif (isset($update['message']['audio'])) {
        handleFileUpload($update['message'], 'audio');
    } elseif (isset($update['message']['sticker'])) {
        handleFileUpload($update['message'], 'sticker');
    } elseif (isset($update['message']['text'])) {
        handleTextMessage($update['message']);
    }
}

function sendWelcomeMessage($chatId) {
    global $apiURL;
    
    $welcomeText = "👋 Welcome! I'm here to help you share content easily. Send me any file or media to start! 😊";
    $welcomeImage = "https://graph.org/file/23ce0effcf6b49297d0e0-d377f405d6698d2080.jpg";  // Replace with your image URL
    
    // Send Welcome Image and Message
    file_get_contents($apiURL . "sendPhoto?chat_id=$chatId&photo=" . urlencode($welcomeImage) . "&caption=" . urlencode($welcomeText));
}

function promptForceSubscribe($chatId, $channels) {
    global $apiURL;
    
    $forceSubscribeText = "🚨 Please subscribe to the channels below to use this bot:";
    
    $buttons = [];
    foreach ($channels as $channel) {
        $buttons[] = [['text' => "Subscribe to $channel", 'url' => "https://t.me/$channel"]];
    }
    $replyMarkup = json_encode(['inline_keyboard' => $buttons]);

    file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=" . urlencode($forceSubscribeText) . "&reply_markup=" . urlencode($replyMarkup));
}

function isUserSubscribedToAllChannels($chatId, $channels) {
    global $apiURL;
    
    foreach ($channels as $channel) {
        $url = $apiURL . "getChatMember?chat_id=$channel&user_id=$chatId";
        $response = json_decode(file_get_contents($url), true);
        
        if (!isset($response['result']['status']) || !in_array($response['result']['status'], ['member', 'administrator', 'creator'])) {
            return false;
        }
    }
    
    return true;
}

function handleFileUpload($message, $type) {
    global $apiURL;

    $chatId = $message['chat']['id'];
    $fileId = '';
    $fileName = '';

    switch ($type) {
        case 'document':
            $fileId = $message['document']['file_id'];
            $fileName = $message['document']['file_name'];
            break;
        case 'photo':
            $fileId = end($message['photo'])['file_id'];
            $fileName = "photo_" . uniqid() . ".jpg";
            break;
        case 'video':
            $fileId = $message['video']['file_id'];
            $fileName = $message['video']['file_name'];
            break;
        case 'audio':
            $fileId = $message['audio']['file_id'];
            $fileName = $message['audio']['file_name'];
            break;
        case 'sticker':
            $fileId = $message['sticker']['file_id'];
            $fileName = "sticker_" . uniqid() . ".webp";
            break;
    }

    $caption = isset($message['caption']) ? $message['caption'] : '';

    $linkId = getOrCreateLinkId($chatId);
    saveFileInfo($fileId, $fileName, $type, $caption, $linkId);

    file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=✅ File uploaded successfully! Send /finish after uploading all files.");
}

function handleTextMessage($message) {
    global $apiURL;

    $chatId = $message['chat']['id'];
    $text = $message['text'];

    if ($text == '/start') {
        sendWelcomeMessage($chatId);
    } elseif (strpos($text, '/start') === 0) {
        $linkId = substr($text, 7);
        sendFilesFromLink($chatId, $linkId);
    } elseif ($text == '/finish') {
        $linkId = finishUploadSession($chatId);
        if ($linkId) {
            $shareableLink = "https://t.me/Iix4_BoT?start=$linkId";
            file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=📎 Shareable link: $shareableLink");
        }
    }
}

function getOrCreateLinkId($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);

    foreach ($database as $entry) {
        if ($entry['chat_id'] == $chatId && $entry['active']) {
            return $entry['link_id'];
        }
    }

    $linkId = uniqid();
    $database[] = [
        'link_id' => $linkId,
        'chat_id' => $chatId,
        'active' => true,
        'files' => []
    ];
    file_put_contents($databaseFile, json_encode($database));

    return $linkId;
}

function saveFileInfo($fileId, $fileName, $type, $caption, $linkId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);

    foreach ($database as &$entry) {
        if ($entry['link_id'] == $linkId) {
            $entry['files'][] = [
                'file_id' => $fileId,
                'file_name' => $fileName,
                'type' => $type,
                'caption' => $caption
            ];
            break;
        }
    }

    file_put_contents($databaseFile, json_encode($database));
}

function finishUploadSession($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);

    foreach ($database as &$entry) {
        if ($entry['chat_id'] == $chatId && $entry['active']) {
            $entry['active'] = false;
            file_put_contents($databaseFile, json_encode($database));
            return $entry['link_id'];
        }
    }

    return false;
}

function sendFilesFromLink($chatId, $linkId) {
    global $databaseFile, $apiURL;

    $database = json_decode(file_get_contents($databaseFile), true);

    foreach ($database as $entry) {
        if ($entry['link_id'] == $linkId) {
            foreach ($entry['files'] as $file) {
                $params = [
                    'chat_id' => $chatId,
                    $file['type'] => $file['file_id']
                ];
                if (!empty($file['caption'])) {
                    $params['caption'] = $file['caption'];
                }

                $url = $apiURL . "send" . ucfirst($file['type']);
                file_get_contents($url . '?' . http_build_query($params));
            }
            break;
        }
    }
}
?>
