<?php
$telegramToken = '7416812034:AAFOvIAtAcsyskzJvrvd-lCBk9OB9vrITQI';
$apiURL = "https://api.telegram.org/bot$telegramToken/";
$databaseFile = 'database.txt';

// Set the admin chat ID
$adminChatId = '6742022802'; // Replace with your admin chat ID

// Load input and decode the update
$input = file_get_contents('php://input');
$update = json_decode($input, TRUE);

// Check for valid update and handle incoming messages
if (isset($update['message'])) {
    $chatId = $update['message']['chat']['id'];

    // Check if the user is forced to subscribe
    if (isUserForcedToSubscribe($chatId)) {
        sendForceSubscribeMessage($chatId);
        return;
    }

    if (isset($update['message']['document'])) {
        handleFileUpload($update['message'], 'document', $chatId);
    } elseif (isset($update['message']['photo'])) {
        handleFileUpload($update['message'], 'photo', $chatId);
    } elseif (isset($update['message']['video'])) {
        handleFileUpload($update['message'], 'video', $chatId);
    } elseif (isset($update['message']['audio'])) {
        handleFileUpload($update['message'], 'audio', $chatId);
    } elseif (isset($update['message']['sticker'])) {
        handleFileUpload($update['message'], 'sticker', $chatId);
    } elseif (isset($update['message']['text'])) {
        handleTextMessage($update['message'], $chatId);
    }
}

function isUserForcedToSubscribe($chatId) {
    global $databaseFile;

    // Get the channel usernames from the database
    $channelUsernames = getForceSubscribeChannels();
    if (empty($channelUsernames)) {
        return false; // No channels set for force subscribe
    }

    // Check if the user is a member of each channel
    foreach ($channelUsernames as $channelUsername) {
        $response = file_get_contents("https://api.telegram.org/botYOUR_TELEGRAM_BOT_TOKEN/getChatMember?chat_id=$channelUsername&user_id=$chatId");
        $data = json_decode($response, true);
        if (isset($data['result']['status']) && $data['result']['status'] === 'left') {
            return true; // User is not subscribed to this channel
        }
    }
    return false; // User is subscribed to all channels
}

function getForceSubscribeChannels() {
    global $databaseFile;

    $data = json_decode(file_get_contents($databaseFile), true);
    return $data['force_subscribe_channels'] ?? []; // Return the array of channel usernames or empty array if not set
}

function sendForceSubscribeMessage($chatId) {
    global $apiURL;
    $channelUsernames = getForceSubscribeChannels();
    $message = "🚫 You must subscribe to our channels to use this bot. Please subscribe to:\n" . implode("\n", $channelUsernames);
    file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=$message");
}

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

    $fileId = '';
    $fileName = '';

    // Extract file info based on type
    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 when done.");
}

function handleTextMessage($message, $chatId) {
    global $apiURL, $adminChatId;

    $text = $message['text'];

    switch ($text) {
        case '/start':
            sendWelcomeMessage($chatId);
            break;
        case (strpos($text, '/start') === 0):
            $linkId = substr($text, 7);
            sendFilesFromLink($chatId, $linkId);
            break;
        case '/finish':
            $linkId = finishUploadSession($chatId);
            if ($linkId) {
                $shareableLink = "https://t.me/FILESHAREx_XBot?start=$linkId";
                file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=🔗 Shareable link: $shareableLink");
            }
            break;
        case '/setforcechannel':
            if ($chatId == $adminChatId) {
                // Expect the next message to be the channel username
                file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=🔧 Please send the username of the channel to set for force subscribe (e.g., @channel_username).");
                setAwaitingChannel($chatId);
            } else {
                file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=🚫 You are not authorized to use this feature.");
            }
            break;
        case (strpos($text, '@') === 0): // Check if the text starts with '@'
            if (isAwaitingChannel($chatId)) {
                addForceSubscribeChannel($text);
                clearAwaitingChannel($chatId);
                file_get_contents($apiURL . "sendMessage?chat_id=$chatId&text=✅ Force subscribe channel added: $text.");
            }
            break;
    }
}

function sendWelcomeMessage($chatId) {
    global $apiURL;
    $welcomeText = "👋 Welcome! Send me any content to share! 📤\n\n🔔 Make sure to subscribe to our channels:\n" . implode("\n", getForceSubscribeChannels());
    $welcomeImageURL = "https://graph.org/file/23ce0effcf6b49297d0e0-d377f405d6698d2080.jpg"; // Replace with your welcome image URL
    file_get_contents($apiURL . "sendPhoto?chat_id=$chatId&photo=$welcomeImageURL&caption=$welcomeText");
}

function getOrCreateLinkId($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);
    if ($database === null) {
        $database = []; // Initialize if the file is empty or invalid
    }

    // Check for an active link ID for the chat
    foreach ($database as $entry) {
        if ($entry['chat_id'] == $chatId && $entry['active']) {
            return $entry['link_id'];
        }
    }

    // Create a new link ID if none exists
    $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'] . '_id' => $file['file_id'],
                    'caption' => $file['caption']
                ];
                file_get_contents($apiURL . "send" . ucfirst($file['type']) . "?" . http_build_query($params));
            }
            break;
        }
    }
}

// Placeholder functions for awaiting channel
function setAwaitingChannel($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);
    foreach ($database as &$entry) {
        if ($entry['chat_id'] == $chatId) {
            $entry['awaiting_channel'] = true;
            break;
        }
    }
    file_put_contents($databaseFile, json_encode($database));
}

function isAwaitingChannel($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);
    foreach ($database as $entry) {
        if ($entry['chat_id'] == $chatId && isset($entry['awaiting_channel'])) {
            return true;
        }
    }
    return false;
}

function clearAwaitingChannel($chatId) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);
    foreach ($database as &$entry) {
        if ($entry['chat_id'] == $chatId) {
            unset($entry['awaiting_channel']);
            break;
        }
    }
    file_put_contents($databaseFile, json_encode($database));
}

function addForceSubscribeChannel($channel) {
    global $databaseFile;

    $database = json_decode(file_get_contents($databaseFile), true);
    if ($database === null) {
        $database = []; // Initialize if the file is empty or invalid
    }

    // Add the channel to the force subscribe channels list
    $database['force_subscribe_channels'][] = $channel;
    file_put_contents($databaseFile, json_encode($database));
}
?>
