const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const path = require('path');

const app = express();
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public')));

// Jika user mengakses root (/), arahkan ke index.html di public/
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 📌 **Konfigurasi koneksi MySQL**
const db = mysql.createPool({
    host: 'localhost',
    user: 'sinyalplay_bot',
    password: '@Makemoney99',
    database: 'sinyalplay_bot',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 📌 **Login - Kirim OTP ke Telegram**
app.post('/login', async (req, res) => {
    const { userId } = req.body;
    if (!userId) return res.status(400).json({ success: false, message: 'ID Telegram diperlukan.' });

    try {
        const [existingUser] = await db.promise().query(
            `SELECT telegram_id FROM users WHERE telegram_id = ?`,
            [userId]
        );

        if (existingUser.length === 0) {
            return res.status(400).json({ success: false, message: 'ID Telegram tidak terdaftar.' });
        }

        const otp = Math.floor(100000 + Math.random() * 900000).toString();
        const otpExpiry = new Date(Date.now() + 5 * 60000); // Berlaku 5 menit

        await db.promise().query(
            `UPDATE users SET otp = ?, otp_expiry = ? WHERE telegram_id = ?`,
            [otp, otpExpiry, userId]
        );

        const [settings] = await db.promise().query('SELECT token FROM setting LIMIT 1');
        if (settings.length === 0) return res.status(500).json({ success: false, message: 'Token tidak ditemukan.' });

        const TOKEN = settings[0].token;

        await axios.post(`https://api.telegram.org/bot${TOKEN}/sendMessage`, {
            chat_id: userId,
            text: `Kode OTP Anda: ${otp}\nBerlaku selama 5 menit.`,
        });

        res.json({ success: true, message: 'OTP telah dikirim ke Telegram Anda.' });
    } catch (error) {
        console.error('Error generating OTP:', error);
        res.status(500).json({ success: false, message: 'Gagal mengirim OTP.' });
    }
});

// 📌 **Verifikasi OTP**
app.post('/verify-otp', async (req, res) => {
    const { userId, otp } = req.body;
    if (!userId || !otp) return res.status(400).json({ success: false, message: 'ID dan OTP diperlukan.' });

    try {
        const [users] = await db.promise().query(
            `SELECT * FROM users WHERE telegram_id = ? AND otp = ? AND otp_expiry > NOW()`,
            [userId, otp]
        );

        if (users.length === 0) {
            return res.status(400).json({ success: false, message: 'OTP tidak valid atau sudah kedaluwarsa.' });
        }

        await db.promise().query(`UPDATE users SET otp = NULL, otp_expiry = NULL WHERE telegram_id = ?`, [userId]);

        res.json({ success: true, message: 'Login berhasil!' });
    } catch (error) {
        console.error('Error verifying OTP:', error);
        res.status(500).json({ success: false, message: 'Terjadi kesalahan.' });
    }
});

// 📌 **GET Daftar User**
app.get('/users', async (req, res) => {
    try {
        const [users] = await db.promise().query('SELECT telegram_id AS id FROM users');
        res.json(users);
    } catch (error) {
        console.error('Error fetching users:', error);
        res.status(500).json({ error: 'Failed to fetch users' });
    }
});

// 📌 **DELETE User**
app.delete('/users/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await db.promise().query('DELETE FROM users WHERE telegram_id = ?', [id]);
        res.json({ success: true, message: 'User berhasil dihapus' });
    } catch (error) {
        console.error('Error deleting user:', error);
        res.status(500).json({ success: false, message: 'Gagal menghapus user' });
    }
});

// 📌 **Update Pengaturan Bot**
app.post('/settings', async (req, res) => {
    const { token, groupId, interval, banned_words, link_whitelist } = req.body;

    try {
        await db.promise().query(
            'UPDATE setting SET token = ?, group_id = ?, `interval` = ?, banned_words = ?, link_whitelist = ? WHERE id = 1',
            [token, groupId, interval, JSON.stringify(banned_words), JSON.stringify(link_whitelist)]
        );
        res.json({ success: true, message: 'Pengaturan berhasil diperbarui.' });
    } catch (error) {
        console.error('Error updating settings:', error);
        res.status(500).json({ success: false, message: 'Gagal menyimpan pengaturan.' });
    }
});

// 📌 **Ambil Banned Words dan Link Whitelist**
app.get('/moderation-settings', async (req, res) => {
    try {
        const [settings] = await db.promise().query('SELECT banned_words, link_whitelist FROM setting LIMIT 1');
        if (settings.length === 0) {
            return res.status(404).json({ success: false, message: 'Pengaturan Moderasi tidak ditemukan.' });
        }

        res.json({
            success: true,
            banned_words: JSON.parse(settings[0].banned_words || '[]'),
            link_whitelist: JSON.parse(settings[0].link_whitelist || '[]')
        });
    } catch (error) {
        console.error('❌ Error fetching Moderation Settings:', error);
        res.status(500).json({ success: false, message: 'Gagal mengambil pengaturan moderasi.' });
    }
});

// 📌 **Tambah Kata Terlarang (`banned_words`)**
app.post('/banned-words', async (req, res) => {
    const { word } = req.body;
    if (!word) return res.status(400).json({ success: false, message: 'Kata terlarang tidak boleh kosong.' });

    try {
        const [settings] = await db.promise().query('SELECT banned_words FROM setting LIMIT 1');
        let bannedWords = JSON.parse(settings[0].banned_words || '[]');

        if (bannedWords.includes(word)) {
            return res.status(400).json({ success: false, message: 'Kata sudah ada dalam daftar.' });
        }

        bannedWords.push(word);
        await db.promise().query('UPDATE setting SET banned_words = ? WHERE id = 1', [JSON.stringify(bannedWords)]);

        res.json({ success: true, message: 'Kata terlarang berhasil ditambahkan.', banned_words: bannedWords });
    } catch (error) {
        console.error('❌ Error adding Banned Word:', error);
        res.status(500).json({ success: false, message: 'Gagal menambahkan kata terlarang.' });
    }
});

// 📌 **Hapus Kata Terlarang**
app.delete('/banned-words/:word', async (req, res) => {
    const { word } = req.params;

    try {
        const [settings] = await db.promise().query('SELECT banned_words FROM setting LIMIT 1');
        let bannedWords = JSON.parse(settings[0].banned_words || '[]');

        bannedWords = bannedWords.filter(w => w !== word);
        await db.promise().query('UPDATE setting SET banned_words = ? WHERE id = 1', [JSON.stringify(bannedWords)]);

        res.json({ success: true, message: 'Kata terlarang berhasil dihapus.', banned_words: bannedWords });
    } catch (error) {
        console.error('❌ Error deleting Banned Word:', error);
        res.status(500).json({ success: false, message: 'Gagal menghapus kata terlarang.' });
    }
});

// 📌 **Tambah Link Whitelist**
app.post('/link-whitelist', async (req, res) => {
    const { link } = req.body;
    if (!link) return res.status(400).json({ success: false, message: 'Link tidak boleh kosong.' });

    try {
        const [settings] = await db.promise().query('SELECT link_whitelist FROM setting LIMIT 1');
        let whitelist = JSON.parse(settings[0].link_whitelist || '[]');

        if (whitelist.includes(link)) {
            return res.status(400).json({ success: false, message: 'Link sudah ada dalam daftar whitelist.' });
        }

        whitelist.push(link);
        await db.promise().query('UPDATE setting SET link_whitelist = ? WHERE id = 1', [JSON.stringify(whitelist)]);

        res.json({ success: true, message: 'Link whitelist berhasil ditambahkan.', link_whitelist: whitelist });
    } catch (error) {
        console.error('❌ Error adding Whitelist Link:', error);
        res.status(500).json({ success: false, message: 'Gagal menambahkan link whitelist.' });
    }
});

// 📌 **Hapus Link dari Whitelist**
app.delete('/link-whitelist/:link', async (req, res) => {
    const { link } = req.params;

    try {
        const [settings] = await db.promise().query('SELECT link_whitelist FROM setting LIMIT 1');
        let whitelist = JSON.parse(settings[0].link_whitelist || '[]');

        whitelist = whitelist.filter(l => l !== link);
        await db.promise().query('UPDATE setting SET link_whitelist = ? WHERE id = 1', [JSON.stringify(whitelist)]);

        res.json({ success: true, message: 'Link whitelist berhasil dihapus.', link_whitelist: whitelist });
    } catch (error) {
        console.error('❌ Error deleting Whitelist Link:', error);
        res.status(500).json({ success: false, message: 'Gagal menghapus link whitelist.' });
    }
});


// 📌 **Ambil Pengaturan Welcome Message**
app.get('/welcome-settings', async (req, res) => {
    try {
        const [settings] = await db.promise().query('SELECT welcome_message, welcome_media, welcome_links FROM setting LIMIT 1');
        if (settings.length === 0) {
            return res.status(404).json({ success: false, message: 'Pengaturan Welcome tidak ditemukan.' });
        }

        res.json({
            success: true,
            welcome_message: settings[0].welcome_message,
            welcome_media: settings[0].welcome_media,
            welcome_links: JSON.parse(settings[0].welcome_links || '[]')
        });
    } catch (error) {
        console.error('❌ Error fetching Welcome Message:', error);
        res.status(500).json({ success: false, message: 'Gagal mengambil pengaturan Welcome.' });
    }
});

// 📌 **Perbarui (Update) Pengaturan Welcome Message**
app.put('/welcome-settings', async (req, res) => {
    const { welcome_message, welcome_media, welcome_links } = req.body;

    try {
        await db.promise().query(
            'UPDATE setting SET welcome_message = ?, welcome_media = ?, welcome_links = ? WHERE id = 1',
            [welcome_message, welcome_media, JSON.stringify(welcome_links)]
        );

        res.json({ success: true, message: 'Pengaturan Welcome berhasil diperbarui.' });
    } catch (error) {
        console.error('❌ Error updating Welcome Message:', error);
        res.status(500).json({ success: false, message: 'Gagal memperbarui pengaturan Welcome.' });
    }
});

// 📌 **Hapus Welcome Message**
app.delete('/welcome-settings', async (req, res) => {
    try {
        await db.promise().query(
            'UPDATE setting SET welcome_message = NULL, welcome_media = NULL, welcome_links = NULL WHERE id = 1'
        );

        res.json({ success: true, message: 'Welcome Message berhasil dihapus.' });
    } catch (error) {
        console.error('❌ Error deleting Welcome Message:', error);
        res.status(500).json({ success: false, message: 'Gagal menghapus Welcome Message.' });
    }
});



// 📌 **API: Ambil Data Statistik Welcome**
app.get('/welcome-stats', async (req, res) => {
    try {
        const [joinedUsers] = await db.promise().query('SELECT COUNT(*) AS total FROM join_history');
        const [totalMembers] = await db.promise().query('SELECT COUNT(*) AS total FROM users'); // Contoh, bisa disesuaikan

        res.json({
            welcomed_users: joinedUsers[0].total || 0,
            total_members: totalMembers[0].total || 0
        });
    } catch (error) {
        console.error("❌ Error fetching stats:", error);
        res.status(500).json({ message: 'Gagal mengambil statistik!' });
    }
});

app.post('/campaigns', async (req, res) => {
    const { type, content, buttons, schedule_time } = req.body;

    try {
        await db.promise().query(
            'INSERT INTO campaigns (content_type, content, buttons, schedule_time) VALUES (?, ?, ?, ?)',
            [type, content, JSON.stringify(buttons), schedule_time]
        );
        res.json({ success: true, message: 'Kampanye berhasil ditambahkan.' });
    } catch (error) {
        console.error('Error menambahkan kampanye:', error);
        res.status(500).json({ success: false, message: 'Gagal menambahkan kampanye.' });
    }
});

app.get('/campaigns', async (req, res) => {
    try {
        const [campaigns] = await db.promise().query('SELECT * FROM campaigns');
        res.json(campaigns.map(campaign => ({
            ...campaign,
            buttons: campaign.buttons ? JSON.parse(campaign.buttons) : []
        })));
    } catch (error) {
        console.error('Error fetching campaigns:', error);
        res.status(500).json({ error: 'Failed to fetch campaigns' });
    }
});

app.put('/campaigns/:id', async (req, res) => {
    const { id } = req.params;
    const { type, content, buttons, schedule_time } = req.body;

    try {
        await db.promise().query(
            'UPDATE campaigns SET content_type = ?, content = ?, buttons = ?, schedule_time = ? WHERE id = ?',
            [type, content, JSON.stringify(buttons), schedule_time, id]
        );
        res.json({ success: true, message: 'Kampanye berhasil diperbarui.' });
    } catch (error) {
        console.error('Error updating campaign:', error);
        res.status(500).json({ success: false, message: 'Gagal memperbarui kampanye.' });
    }
});

app.delete('/campaigns/:id', async (req, res) => {
    const { id } = req.params;
    try {
        await db.promise().query('DELETE FROM campaigns WHERE id = ?', [id]);
        res.json({ success: true, message: 'Kampanye berhasil dihapus' });
    } catch (error) {
        console.error('Error deleting campaign:', error);
        res.status(500).json({ success: false, message: 'Gagal menghapus kampanye.' });
    }
});


async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

app.post('/broadcast', async (req, res) => {
    try {
        const [settings] = await db.promise().query('SELECT token, delay_personal_broadcast FROM setting LIMIT 1');
        if (!settings.length) return res.status(500).json({ success: false, message: 'Token tidak ditemukan.' });

        const TOKEN = settings[0].token;
        const DELAY = settings[0].delay_personal_broadcast || 2; // Default 2 detik jika tidak ada
        const [users] = await db.promise().query('SELECT telegram_id FROM users');

        if (!users.length) return res.status(404).json({ success: false, message: 'Tidak ada user terdaftar.' });

        const [campaign] = await db.promise().query('SELECT * FROM campaigns WHERE status = "pending" ORDER BY schedule_time ASC LIMIT 1');
        if (!campaign.length) return res.status(404).json({ success: false, message: 'Tidak ada kampanye yang tersedia.' });

        const { content, media_url, media_type, buttons } = campaign[0];
        let replyMarkup = buttons ? JSON.parse(buttons) : [];

        let sentCount = 0, failedCount = 0;

        for (const user of users) {
            const chatId = user.telegram_id;

            let requestData = {
                chat_id: chatId,
                parse_mode: "Markdown",
                reply_markup: replyMarkup.length > 0 ? JSON.stringify({ inline_keyboard: replyMarkup.map(btn => [{ text: btn.text, url: btn.url }]) }) : undefined
            };

            try {
                if (media_url && media_type !== 'none') {
                    let sendMediaType = media_type === 'video' ? 'sendVideo' : 'sendPhoto';
                    requestData[media_type] = media_url;
                    requestData.caption = content;
                    await axios.post(`https://api.telegram.org/bot${TOKEN}/${sendMediaType}`, requestData);
                } else {
                    requestData.text = content;
                    await axios.post(`https://api.telegram.org/bot${TOKEN}/sendMessage`, requestData);
                }

                sentCount++;
            } catch (error) {
                failedCount++;
                console.error(`❌ Gagal mengirim ke ${chatId}:`, error);
            }

            // Delay antar pesan agar tidak terkena rate-limit Telegram
            await sleep(DELAY * 1000);
        }

        // Tandai kampanye sebagai "sent" setelah broadcast selesai
        await db.promise().query('UPDATE campaigns SET status = "sent" WHERE id = ?', [campaign[0].id]);

        res.json({ success: true, message: `Pesan terkirim ke ${sentCount} user, gagal ke ${failedCount} user.` });
    } catch (error) {
        console.error('❌ Error broadcasting message:', error);
        res.status(500).json({ success: false, message: 'Gagal mengirim pesan broadcast.' });
    }
});



app.post('/broadcast-group', async (req, res) => {
    try {
        const [settings] = await db.promise().query('SELECT token, group_id, delay_group_broadcast FROM setting LIMIT 1');
        if (!settings.length) return res.status(500).json({ success: false, message: 'Token atau Group ID tidak ditemukan.' });

        const TOKEN = settings[0].token;
        const GROUP_CHAT_ID = settings[0].group_id;
        const DELAY = settings[0].delay_group_broadcast || 10; // Default 10 detik jika tidak ada

        const [campaign] = await db.promise().query('SELECT * FROM campaigns WHERE status = "pending" ORDER BY schedule_time ASC LIMIT 1');
        if (!campaign.length) return res.status(404).json({ success: false, message: 'Tidak ada kampanye yang tersedia.' });

        const { content, media_url, media_type, buttons } = campaign[0];
        let replyMarkup = buttons ? JSON.parse(buttons) : [];

        let requestData = {
            chat_id: GROUP_CHAT_ID,
            parse_mode: "Markdown",
            reply_markup: replyMarkup.length > 0 ? JSON.stringify({ inline_keyboard: replyMarkup.map(btn => [{ text: btn.text, url: btn.url }]) }) : undefined
        };

        try {
            if (media_url && media_type !== 'none') {
                let sendMediaType = media_type === 'video' ? 'sendVideo' : 'sendPhoto';
                requestData[media_type] = media_url;
                requestData.caption = content;
                await axios.post(`https://api.telegram.org/bot${TOKEN}/${sendMediaType}`, requestData);
            } else {
                requestData.text = content;
                await axios.post(`https://api.telegram.org/bot${TOKEN}/sendMessage`, requestData);
            }

            // Tandai kampanye sebagai "sent" setelah berhasil dikirim ke grup
            await db.promise().query('UPDATE campaigns SET status = "sent" WHERE id = ?', [campaign[0].id]);

            // Delay untuk menghindari spam atau rate-limit
            setTimeout(() => {
                console.log(`✅ Broadcast ke grup dikirim dengan delay ${DELAY} detik.`);
            }, DELAY * 1000);

            res.json({ success: true, message: `Pesan broadcast berhasil dikirim ke grup dengan delay ${DELAY} detik.` });
        } catch (error) {
            console.error('❌ Error broadcasting message to group:', error);
            res.status(500).json({ success: false, message: 'Gagal mengirim pesan broadcast ke grup.' });
        }
    } catch (error) {
        console.error('❌ Error broadcasting message:', error);
        res.status(500).json({ success: false, message: 'Gagal mengirim pesan broadcast ke grup.' });
    }
});







async function sendScheduledCampaigns() {
    try {
        const [settings] = await db.promise().query('SELECT token, group_id, interval_campaign FROM setting LIMIT 1');
        if (!settings.length) throw new Error('❌ Token tidak ditemukan di database.');

        const TOKEN = settings[0].token;
        const GROUP_CHAT_ID = settings[0].group_id;
        const INTERVAL = settings[0].interval_campaign || 5; // Default 5 menit jika tidak ada

        const [campaigns] = await db.promise().query(
            'SELECT * FROM campaigns WHERE schedule_time <= NOW() AND status = "pending"'
        );

        for (const campaign of campaigns) {
            const { content, media_url, media_type, buttons } = campaign;
            let replyMarkup = buttons ? JSON.parse(buttons) : [];

            let requestData = {
                chat_id: GROUP_CHAT_ID,
                parse_mode: "Markdown",
                reply_markup: replyMarkup.length > 0 ? JSON.stringify({ inline_keyboard: replyMarkup.map(btn => [{ text: btn.text, url: btn.url }]) }) : undefined
            };

            if (media_url && media_type !== 'none') {
                let sendMediaType = media_type === 'video' ? 'sendVideo' : 'sendPhoto';
                requestData[media_type] = media_url;
                requestData.caption = content;
                await axios.post(`https://api.telegram.org/bot${TOKEN}/${sendMediaType}`, requestData);
            } else {
                requestData.text = content;
                await axios.post(`https://api.telegram.org/bot${TOKEN}/sendMessage`, requestData);
            }

            await db.promise().query('UPDATE campaigns SET status = "sent" WHERE id = ?', [campaign.id]);
        }
    } catch (error) {
        console.error('❌ Error sending scheduled campaigns:', error);
    }
}

// Interval kampanye diambil dari database
setInterval(async () => {
    const [settings] = await db.promise().query('SELECT interval_campaign FROM setting LIMIT 1');
    const INTERVAL = settings[0]?.interval_campaign || 5;
    setTimeout(sendScheduledCampaigns, INTERVAL * 60 * 1000);
}, 5000); // Cek setiap 5 detik untuk mendapatkan nilai terbaru






bot.on('message', async (msg) => {
    const chatId = msg.chat.id;

    // Hanya menangani pesan di dalam grup
    if (msg.chat.type !== 'supergroup' && msg.chat.type !== 'group') return;

    const messageText = msg.text || '';
    const userId = msg.from.id;
    const username = msg.from.username || msg.from.first_name || "User";

    // Ambil pengaturan whitelist link dari database
    const [settings] = await db.promise().query('SELECT link_whitelist FROM setting LIMIT 1');
    const whitelistLinks = JSON.parse(settings[0].link_whitelist || '[]');

    // **Regex untuk deteksi link**
    const linkRegex = /(https?:\/\/[^\s]+)|([a-zA-Z0-9-]+\.[a-zA-Z]{2,}\/[^\s]*)/gi;

    // **Periksa apakah pesan mengandung link**
    if (linkRegex.test(messageText)) {
        const containsWhitelistedLink = whitelistLinks.some(allowedLink => messageText.includes(allowedLink));

        if (!containsWhitelistedLink) {
            // **Hapus pesan dan kick user jika link tidak di-whitelist**
            try {
                await bot.deleteMessage(chatId, msg.message_id);
                await bot.kickChatMember(chatId, userId);

                console.log(`❌ User ${username} di-kick karena mengirim link yang tidak diizinkan.`);
            } catch (error) {
                console.error(`❌ Error saat mencoba menghapus pesan atau kick user:`, error);
            }
        } else {
            console.log(`✅ Link diizinkan dalam pesan dari ${username}.`);
        }
    }
});


// 📌 **Bot Welcome Telegram (Real-Time + Auto-Kick + Logging)**
(async () => {
    try {
        const [settings] = await db.promise().query('SELECT token, group_id, banned_words FROM setting LIMIT 1');
        if (!settings.length) throw new Error('❌ Token tidak ditemukan di database.');

        const TOKEN = settings[0].token;
        const GROUP_CHAT_ID = settings[0].group_id;
        const bannedWords = JSON.parse(settings[0].banned_words || '[]');

        console.log(`✅ Bot Initialized - Group ID: ${GROUP_CHAT_ID}`);

        const bot = new TelegramBot(TOKEN, { polling: true });

        bot.on('new_chat_members', async (msg) => {
            const chatId = msg.chat.id;
            if (chatId.toString() !== GROUP_CHAT_ID.toString()) return;

            const [welcomeSettings] = await db.promise().query('SELECT welcome_message, welcome_media, welcome_links FROM setting LIMIT 1');
            if (!welcomeSettings.length) return;

            const welcomeMessage = welcomeSettings[0].welcome_message || "🎉 Selamat datang di grup!";
            const welcomeMedia = welcomeSettings[0].welcome_media || null;
            const welcomeLinks = JSON.parse(welcomeSettings[0].welcome_links || '[]');

            for (const user of msg.new_chat_members) {
                const username = user.username || user.first_name || "User Baru";
                const userId = user.id;

                // **Cek apakah username mengandung kata terlarang**
                if (bannedWords.some(word => username.toLowerCase().includes(word.toLowerCase()))) {
                    await bot.kickChatMember(chatId, userId);
                    console.log(`❌ User ${username} (${userId}) di-kick karena username mengandung kata terlarang.`);
                    continue;
                }

                // **Simpan history join ke database**
                await db.promise().query(
                    'INSERT INTO join_history (telegram_id, username, first_name) VALUES (?, ?, ?)',
                    [userId, username, user.first_name]
                );

                const message = welcomeMessage.replace(/\{username\}/g, `@${username}`);

                // **Kirim media jika ada**
                let sentMessage;
                if (welcomeMedia) {
                    sentMessage = await bot.sendPhoto(chatId, welcomeMedia, { caption: message, parse_mode: "Markdown" });
                } else {
                    sentMessage = await bot.sendMessage(chatId, message, { parse_mode: "Markdown" });
                }

                // **Kirim tombol link jika ada**
                if (welcomeLinks.length > 0) {
                    const inlineKeyboard = {
                        reply_markup: {
                            inline_keyboard: welcomeLinks.map(link => [{ text: link.text, url: link.url }])
                        }
                    };
                    await bot.sendMessage(chatId, "🔗 Klik link di bawah untuk info lebih lanjut:", inlineKeyboard);
                }

                // **Auto-hapus pesan welcome setelah 6 jam**
                setTimeout(() => {
                    bot.deleteMessage(chatId, sentMessage.message_id).catch(() => { });
                }, 6 * 60 * 60 * 1000); // 6 jam

                console.log(`✅ Pesan welcome dikirim ke @${username}`);
            }
        });

        console.log('🚀 Bot Welcome sudah berjalan...');

    } catch (error) {
        console.error('❌ Error saat inisialisasi bot:', error);
    }
})();

// 🖥 **Menjalankan server**
app.listen(2001, () => console.log('✅ Server berjalan di port 2001'));