<?php
/*
===========================================================
              🔍 USERSCAN AI
       Username Finder & Identity Toolkit
===========================================================

Single PHP Telegram Bot
PHP 8+
SQLite3
cURL

ADMIN ID:
8766027800

CHANNEL:
@LeoforleoV1

DEVELOPER:
@MIRZASTOREVS
===========================================================
*/


/* ========================================================
   CONFIG
======================================================== */

$BOT_TOKEN = 'PUT_YOUR_NEW_BOT_TOKEN_HERE';

$ADMIN_ID = 8766027800;

$CHANNEL_USERNAME = '@LeoforleoV1';
$CHANNEL_LINK = 'https://t.me/LeoforleoV1';

$DEVELOPER_USERNAME = 'MIRZASTOREVS';
$DEVELOPER_LINK = 'https://t.me/MIRZASTOREVS';

$BOT_NAME = '🔍 UserScan AI';

$DB_FILE = __DIR__ . '/userscan.sqlite';


/* ========================================================
   ERROR SETTINGS
======================================================== */

ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');

error_reporting(E_ALL);


/* ========================================================
   DATABASE
======================================================== */

try {

    $db = new SQLite3($DB_FILE);

    $db->exec("
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY,
            username TEXT DEFAULT '',
            first_name TEXT DEFAULT '',
            joined_at INTEGER DEFAULT 0,
            last_seen INTEGER DEFAULT 0,
            banned INTEGER DEFAULT 0,
            searches INTEGER DEFAULT 0,
            generated INTEGER DEFAULT 0
        )
    ");

    $db->exec("
        CREATE TABLE IF NOT EXISTS favorites (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            username TEXT,
            created_at INTEGER
        )
    ");

    $db->exec("
        CREATE TABLE IF NOT EXISTS history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER,
            username TEXT,
            created_at INTEGER
        )
    ");

    $db->exec("
        CREATE TABLE IF NOT EXISTS trending (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT,
            category TEXT,
            created_at INTEGER
        )
    ");

} catch (Throwable $e) {

    http_response_code(500);
    exit('Database Error');
}


/* ========================================================
   TELEGRAM API
======================================================== */

function tg($method, $data = [])
{
    global $BOT_TOKEN;

    $url =
        'https://api.telegram.org/bot' .
        $BOT_TOKEN .
        '/' .
        $method;

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30
    ]);

    $result = curl_exec($ch);

    curl_close($ch);

    if (!$result) {
        return [];
    }

    $json = json_decode($result, true);

    return is_array($json) ? $json : [];
}


/* ========================================================
   SEND MESSAGE
======================================================== */

function sendMsg($chatId, $text, $keyboard = null)
{
    $data = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];

    if ($keyboard !== null) {

        $data['reply_markup'] =
            json_encode(
                $keyboard,
                JSON_UNESCAPED_UNICODE
            );
    }

    return tg('sendMessage', $data);
}


/* ========================================================
   EDIT MESSAGE
======================================================== */

function editMsg($chatId, $messageId, $text, $keyboard = null)
{
    $data = [
        'chat_id' => $chatId,
        'message_id' => $messageId,
        'text' => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];

    if ($keyboard !== null) {

        $data['reply_markup'] =
            json_encode(
                $keyboard,
                JSON_UNESCAPED_UNICODE
            );
    }

    return tg('editMessageText', $data);
}


/* ========================================================
   CALLBACK ANSWER
======================================================== */

function answerCallback($id, $text = '')
{
    return tg(
        'answerCallbackQuery',
        [
            'callback_query_id' => $id,
            'text' => $text
        ]
    );
}


/* ========================================================
   USER SAVE
======================================================== */

function saveUser($user)
{
    global $db;

    if (
        !$user ||
        !isset($user['id'])
    ) {
        return;
    }

    $id =
        (int)$user['id'];

    $username =
        $user['username'] ?? '';

    $first =
        $user['first_name'] ?? '';

    $exists =
        $db->querySingle(
            "SELECT id FROM users WHERE id = $id"
        );

    if ($exists) {

        $stmt =
            $db->prepare("
                UPDATE users
                SET username = :username,
                    first_name = :first_name,
                    last_seen = :last_seen
                WHERE id = :id
            ");

        $stmt->bindValue(
            ':username',
            $username,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':first_name',
            $first,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':last_seen',
            time(),
            SQLITE3_INTEGER
        );

        $stmt->bindValue(
            ':id',
            $id,
            SQLITE3_INTEGER
        );

        $stmt->execute();

    } else {

        $stmt =
            $db->prepare("
                INSERT INTO users
                (id, username, first_name, joined_at, last_seen)
                VALUES
                (:id, :username, :first_name, :joined, :last)
            ");

        $stmt->bindValue(
            ':id',
            $id,
            SQLITE3_INTEGER
        );

        $stmt->bindValue(
            ':username',
            $username,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':first_name',
            $first,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':joined',
            time(),
            SQLITE3_INTEGER
        );

        $stmt->bindValue(
            ':last',
            time(),
            SQLITE3_INTEGER
        );

        $stmt->execute();
    }
}


/* ========================================================
   BAN CHECK
======================================================== */

function isBanned($id)
{
    global $db;

    $stmt =
        $db->prepare(
            "SELECT banned FROM users WHERE id = :id"
        );

    $stmt->bindValue(
        ':id',
        $id,
        SQLITE3_INTEGER
    );

    $row =
        $stmt->execute()
            ->fetchArray(SQLITE3_ASSOC);

    return !empty($row['banned']);
}


/* ========================================================
   FORCE JOIN CHECK
======================================================== */

function isJoined($userId)
{
    global $CHANNEL_USERNAME;

    $result =
        tg(
            'getChatMember',
            [
                'chat_id' =>
                    $CHANNEL_USERNAME,

                'user_id' =>
                    $userId
            ]
        );

    if (
        empty($result['ok'])
    ) {
        return false;
    }

    $status =
        $result['result']['status'] ?? '';

    return in_array(
        $status,
        [
            'member',
            'administrator',
            'creator'
        ],
        true
    );
}


/* ========================================================
   FORCE JOIN UI
======================================================== */

function forceJoin($chatId)
{
    global $CHANNEL_LINK;
    global $DEVELOPER_LINK;

    $text =
        "╭━━━━━━━━━━━━━━━━━━╮\n" .
        "       🔍 <b>USERSCAN AI</b>\n" .
        "╰━━━━━━━━━━━━━━━━━━╯\n\n" .

        "👋 <b>Welcome!</b>\n\n" .

        "Your Social Identity Toolkit is waiting for you.\n\n" .

        "🔍 Username Finder\n" .
        "⚡ Username Checker\n" .
        "💡 Username Generator\n" .
        "🧠 Username Score\n" .
        "🔗 Social Link Maker\n" .
        "⭐ Favorites & History\n\n" .

        "🔒 <b>ACCESS LOCKED</b>\n\n" .

        "To unlock UserScan AI, please join our official channel first.\n\n" .

        "📢 <b>Official Channel</b>\n" .
        "Updates • New Tools • Features\n\n" .

        "After joining, press <b>CHECK MEMBERSHIP</b>.";

    $keyboard = [
        'inline_keyboard' => [

            [
                [
                    'text' =>
                        '📢 JOIN OFFICIAL CHANNEL',
                    'url' =>
                        $CHANNEL_LINK
                ]
            ],

            [
                [
                    'text' =>
                        '🔄 CHECK MEMBERSHIP',
                    'callback_data' =>
                        'check_join'
                ]
            ],

            [
                [
                    'text' =>
                        '👨‍💻 DEVELOPER',
                    'url' =>
                        $DEVELOPER_LINK
                ]
            ]

        ]
    ];

    sendMsg(
        $chatId,
        $text,
        $keyboard
    );
}


/* ========================================================
   MAIN MENU
======================================================== */

function mainMenu()
{
    return [
        'keyboard' => [

            [
                '🔍 Find Username',
                '💡 Generate Username'
            ],

            [
                '⚡ Check Username',
                '🧠 Username Score'
            ],

            [
                '🔗 Social Link Maker',
                '📱 Platform Search'
            ],

            [
                '⭐ My Favorites',
                '🕘 Search History'
            ],

            [
                '🔥 Trending Names',
                'ℹ️ How It Works'
            ]

        ],

        'resize_keyboard' => true,
        'is_persistent' => true
    ];
}


/* ========================================================
   SESSION SYSTEM
======================================================== */

$SESSION_FILE =
    __DIR__ . '/userscan_sessions.json';

if (!file_exists($SESSION_FILE)) {

    file_put_contents(
        $SESSION_FILE,
        '{}'
    );
}

$sessions =
    json_decode(
        file_get_contents($SESSION_FILE),
        true
    );

if (!is_array($sessions)) {
    $sessions = [];
}


function saveSessions()
{
    global $sessions;
    global $SESSION_FILE;

    file_put_contents(
        $SESSION_FILE,
        json_encode(
            $sessions,
            JSON_UNESCAPED_UNICODE
        ),
        LOCK_EX
    );
}


function setSession($id, $data)
{
    global $sessions;

    $sessions[$id] = $data;

    saveSessions();
}


function getSession($id)
{
    global $sessions;

    return $sessions[$id] ?? null;
}


function clearSession($id)
{
    global $sessions;

    unset($sessions[$id]);

    saveSessions();
}


/* ========================================================
   USERNAME CLEANER
======================================================== */

function cleanUsername($username)
{
    $username =
        trim($username);

    $username =
        ltrim($username, '@');

    $username =
        preg_replace(
            '/[^a-zA-Z0-9._]/',
            '',
            $username
        );

    return strtolower($username);
}


/* ========================================================
   USERNAME SCORE
======================================================== */

function usernameScore($username)
{
    $score = 100;

    $length =
        strlen($username);

    if ($length > 15) {
        $score -= 20;
    } elseif ($length > 12) {
        $score -= 10;
    } elseif ($length <= 5) {
        $score += 2;
    }

    if (
        preg_match(
            '/[_]{2,}|[.]{2,}/',
            $username
        )
    ) {
        $score -= 15;
    }

    if (
        preg_match(
            '/[0-9]{3,}/',
            $username
        )
    ) {
        $score -= 10;
    }

    if (
        strpos($username, '_') !== false
    ) {
        $score -= 5;
    }

    if (
        strpos($username, '.') !== false
    ) {
        $score -= 3;
    }

    if (
        preg_match(
            '/^[a-z]+$/i',
            $username
        )
    ) {
        $score += 5;
    }

    return max(
        1,
        min(100, $score)
    );
}


/* ========================================================
   SCORE REPORT
======================================================== */

function scoreReport($chatId, $username)
{
    $username =
        cleanUsername($username);

    if (!$username) {

        sendMsg(
            $chatId,
            "❌ Please enter a valid username."
        );

        return;
    }

    $score =
        usernameScore($username);

    if ($score >= 85) {
        $status = '💎 Excellent';
    } elseif ($score >= 70) {
        $status = '🟢 Very Good';
    } elseif ($score >= 55) {
        $status = '🟡 Good';
    } else {
        $status = '🟠 Needs Improvement';
    }

    $length =
        strlen($username);

    $report =
        "🧠 <b>USERNAME SCORE</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "🔍 Username: <code>@" .
        htmlspecialchars($username) .
        "</code>\n\n" .

        "⭐ <b>Overall Score:</b> " .
        $score .
        "/100\n" .

        "📊 <b>Status:</b> " .
        $status .
        "\n\n" .

        "📏 Length: " .
        $length .
        " characters\n\n" .

        "📌 <b>Analysis</b>\n\n" .

        "💎 Brandability: " .
        min(100, $score + 3) .
        "%\n" .

        "🧠 Memorability: " .
        min(100, $score + 1) .
        "%\n" .

        "✨ Simplicity: " .
        max(20, $score - 2) .
        "%\n" .

        "💼 Professional: " .
        min(100, $score + 4) .
        "%\n\n" .

        "💡 <b>Tip:</b>\n" .

        "Short, easy-to-spell and easy-to-remember usernames are generally better for branding.";

    sendMsg(
        $chatId,
        $report,
        [
            'inline_keyboard' => [

                [
                    [
                        'text' => '⚡ Check Username',
                        'callback_data' =>
                            'check_again'
                    ]
                ],

                [
                    [
                        'text' => '⭐ Save Username',
                        'callback_data' =>
                            'save|' . $username
                    ]
                ]

            ]
        ]
    );
}


/* ========================================================
   SOCIAL LINKS
======================================================== */

function socialLinks($chatId, $username)
{
    $username =
        cleanUsername($username);

    if (!$username) {

        sendMsg(
            $chatId,
            "❌ Invalid username."
        );

        return;
    }

    $safe =
        htmlspecialchars(
            $username
        );

    $text =
        "🔗 <b>SOCIAL PROFILE LINKS</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "📸 <b>Instagram</b>\n" .
        "https://instagram.com/" .
        $safe .
        "\n\n" .

        "🎵 <b>TikTok</b>\n" .
        "https://tiktok.com/@" .
        $safe .
        "\n\n" .

        "▶️ <b>YouTube</b>\n" .
        "https://youtube.com/@" .
        $safe .
        "\n\n" .

        "🐦 <b>X</b>\n" .
        "https://x.com/" .
        $safe .
        "\n\n" .

        "✈️ <b>Telegram</b>\n" .
        "https://t.me/" .
        $safe;

    sendMsg(
        $chatId,
        $text,
        [
            'inline_keyboard' => [

                [
                    [
                        'text' =>
                            '⭐ Save Username',
                        'callback_data' =>
                            'save|' . $username
                    ]
                ]

            ]
        ]
    );
}


/* ========================================================
   GENERATOR
======================================================== */

function generateUsernames(
    $chatId,
    $base,
    $style = 'premium'
)
{
    global $db;

    $base =
        cleanUsername($base);

    if (!$base) {

        sendMsg(
            $chatId,
            "❌ Please enter a valid name or keyword."
        );

        return;
    }

    $templates = [

        'premium' => [
            $base . 'hq',
            'the' . $base,
            $base . 'official',
            $base . 'studio',
            $base . 'labs',
            $base . 'verse',
            $base . 'hub',
            $base . 'world',
            $base . 'prime',
            $base . 'elite'
        ],

        'short' => [
            $base . 'x',
            $base . 'io',
            $base . 'go',
            $base . 'hq',
            'x' . $base,
            $base . 'tv',
            $base . 'co',
            $base . 'one'
        ],

        'tech' => [
            $base . 'tech',
            $base . 'dev',
            $base . 'labs',
            $base . 'code',
            $base . 'digital',
            $base . 'ai',
            $base . 'x',
            $base . 'cloud',
            $base . 'systems'
        ],

        'gaming' => [
            $base . 'gaming',
            $base . 'plays',
            $base . 'gg',
            $base . 'gamingx',
            'play' . $base,
            $base . 'fps',
            $base . 'arena',
            $base . 'zone'
        ],

        'professional' => [
            $base . 'official',
            $base . 'media',
            $base . 'studio',
            $base . 'agency',
            $base . 'business',
            $base . 'global',
            $base . 'group',
            $base . 'network'
        ]

    ];

    $list =
        $templates[$style]
        ?? $templates['premium'];

    shuffle($list);

    $list =
        array_unique($list);

    $list =
        array_slice(
            $list,
            0,
            10
        );


    $stmt =
        $db->prepare("
            UPDATE users
            SET generated = generated + 1
            WHERE id = :id
        ");

    $stmt->bindValue(
        ':id',
        $chatId,
        SQLITE3_INTEGER
    );

    $stmt->execute();


    $text =
        "💡 <b>USERNAME GENERATOR</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "🎯 Base: <code>" .
        htmlspecialchars($base) .
        "</code>\n" .

        "✨ Style: <b>" .
        ucfirst($style) .
        "</b>\n\n";


    foreach (
        $list as $i => $name
    ) {

        $score =
            usernameScore($name);

        $text .=
            ($i + 1) .
            ". <code>@" .
            htmlspecialchars($name) .
            "</code> — ⭐ " .
            $score .
            "/100\n";
    }


    $text .=
        "\n⚠️ <i>Score is a branding estimate, not availability confirmation.</i>";


    sendMsg(
        $chatId,
        $text,
        [
            'inline_keyboard' => [

                [
                    [
                        'text' =>
                            '🔄 Generate Again',
                        'callback_data' =>
                            'gen_again'
                    ]
                ],

                [
                    [
                        'text' =>
                            '🔗 Make Social Links',
                        'callback_data' =>
                            'links_mode'
                    ]
                ]

            ]
        ]
    );
}


/* ========================================================
   SAVE FAVORITE
======================================================== */

function saveFavorite($userId, $username)
{
    global $db;

    $username =
        cleanUsername($username);

    if (!$username) {
        return;
    }

    $exists =
        $db->querySingle(
            "SELECT COUNT(*) FROM favorites
             WHERE user_id = " .
             (int)$userId .
             " AND username = '" .
             SQLite3::escapeString($username) .
             "'"
        );

    if (!$exists) {

        $stmt =
            $db->prepare("
                INSERT INTO favorites
                (user_id, username, created_at)
                VALUES
                (:user, :username, :created)
            ");

        $stmt->bindValue(
            ':user',
            $userId,
            SQLITE3_INTEGER
        );

        $stmt->bindValue(
            ':username',
            $username,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':created',
            time(),
            SQLITE3_INTEGER
        );

        $stmt->execute();
    }
}


/* ========================================================
   FAVORITES
======================================================== */

function showFavorites($chatId)
{
    global $db;

    $result =
        $db->query("
            SELECT username
            FROM favorites
            WHERE user_id = " .
            (int)$chatId .
            "
            ORDER BY id DESC
            LIMIT 30
        ");

    $text =
        "⭐ <b>MY FAVORITES</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n";

    $count = 0;

    while (
        $row =
        $result->fetchArray(
            SQLITE3_ASSOC
        )
    ) {

        $count++;

        $text .=
            $count .
            ". <code>@" .
            htmlspecialchars(
                $row['username']
            ) .
            "</code>\n";
    }

    if ($count === 0) {

        $text .=
            "📭 No saved usernames yet.\n\n" .

            "Use ⭐ Save Username after finding a name.";
    }

    sendMsg(
        $chatId,
        $text
    );
}


/* ========================================================
   HISTORY
======================================================== */

function addHistory($userId, $username)
{
    global $db;

    $stmt =
        $db->prepare("
            INSERT INTO history
            (user_id, username, created_at)
            VALUES
            (:user, :username, :created)
        ");

    $stmt->bindValue(
        ':user',
        $userId,
        SQLITE3_INTEGER
    );

    $stmt->bindValue(
        ':username',
        $username,
        SQLITE3_TEXT
    );

    $stmt->bindValue(
        ':created',
        time(),
        SQLITE3_INTEGER
    );

    $stmt->execute();


    $db->exec("
        DELETE FROM history
        WHERE user_id = " .
        (int)$userId .
        "
        AND id NOT IN (
            SELECT id FROM history
            WHERE user_id = " .
            (int)$userId .
            "
            ORDER BY id DESC
            LIMIT 30
        )
    ");
}


function showHistory($chatId)
{
    global $db;

    $result =
        $db->query("
            SELECT username
            FROM history
            WHERE user_id = " .
            (int)$chatId .
            "
            ORDER BY id DESC
            LIMIT 30
        ");

    $text =
        "🕘 <b>SEARCH HISTORY</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n";

    $count = 0;

    while (
        $row =
        $result->fetchArray(
            SQLITE3_ASSOC
        )
    ) {

        $count++;

        $text .=
            $count .
            ". <code>@" .
            htmlspecialchars(
                $row['username']
            ) .
            "</code>\n";
    }

    if (!$count) {

        $text .=
            "📭 Your search history is empty.";
    }

    sendMsg(
        $chatId,
        $text
    );
}


/* ========================================================
   TRENDING
======================================================== */

function showTrending($chatId)
{
    global $db;

    $count =
        $db->querySingle(
            "SELECT COUNT(*) FROM trending"
        );

    $text =
        "🔥 <b>TRENDING USERNAMES</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n";

    if (!$count) {

        $text .=
            "🚀 Trending names are being prepared.\n\n" .

            "Try the Username Generator instead.";

        sendMsg(
            $chatId,
            $text
        );

        return;
    }

    $result =
        $db->query("
            SELECT username, category
            FROM trending
            ORDER BY id DESC
            LIMIT 30
        ");

    while (
        $row =
        $result->fetchArray(
            SQLITE3_ASSOC
        )
    ) {

        $text .=
            "🔥 <code>@" .
            htmlspecialchars(
                $row['username']
            ) .
            "</code>\n" .

            "   #" .
            htmlspecialchars(
                $row['category']
            ) .
            "\n\n";
    }

    sendMsg(
        $chatId,
        $text
    );
}


/* ========================================================
   PLATFORM MENU
======================================================== */

function platformMenu($chatId)
{
    sendMsg(
        $chatId,

        "📱 <b>PLATFORM SEARCH</b>\n\n" .

        "Choose a platform to generate a direct profile URL.",

        [
            'inline_keyboard' => [

                [
                    [
                        'text' => '📸 Instagram',
                        'callback_data' =>
                            'platform|instagram'
                    ],

                    [
                        'text' => '🎵 TikTok',
                        'callback_data' =>
                            'platform|tiktok'
                    ]
                ],

                [
                    [
                        'text' => '▶️ YouTube',
                        'callback_data' =>
                            'platform|youtube'
                    ],

                    [
                        'text' => '🐦 X',
                        'callback_data' =>
                            'platform|x'
                    ]
                ],

                [
                    [
                        'text' => '✈️ Telegram',
                        'callback_data' =>
                            'platform|telegram'
                    ]
                ]

            ]
        ]
    );
}


/* ========================================================
   PLATFORM LINK
======================================================== */

function platformLink($chatId, $platform, $username)
{
    $username =
        cleanUsername($username);

    if (!$username) {

        sendMsg(
            $chatId,
            "❌ Invalid username."
        );

        return;
    }

    $urls = [

        'instagram' =>
            'https://instagram.com/' .
            $username,

        'tiktok' =>
            'https://tiktok.com/@' .
            $username,

        'youtube' =>
            'https://youtube.com/@' .
            $username,

        'x' =>
            'https://x.com/' .
            $username,

        'telegram' =>
            'https://t.me/' .
            $username

    ];

    if (!isset($urls[$platform])) {
        return;
    }

    $names = [

        'instagram' => '📸 Instagram',
        'tiktok' => '🎵 TikTok',
        'youtube' => '▶️ YouTube',
        'x' => '🐦 X',
        'telegram' => '✈️ Telegram'

    ];

    $name =
        $names[$platform];

    sendMsg(
        $chatId,

        $name .
        "\n\n🔗 <a href=\"" .
        $urls[$platform] .
        "\">Open Profile</a>\n\n" .

        "Username: <code>@" .
        htmlspecialchars($username) .
        "</code>"
    );
}


/* ========================================================
   HOW IT WORKS
======================================================== */

function howItWorks($chatId)
{
    sendMsg(
        $chatId,

        "ℹ️ <b>HOW USERSCAN AI WORKS</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "🔍 <b>Find Username</b>\n" .
        "Enter a username or name to start exploring.\n\n" .

        "💡 <b>Generate Username</b>\n" .
        "Create brandable username ideas.\n\n" .

        "🧠 <b>Username Score</b>\n" .
        "Get a simple branding score based on length, simplicity and structure.\n\n" .

        "🔗 <b>Social Link Maker</b>\n" .
        "Generate direct profile links for supported platforms.\n\n" .

        "⭐ <b>Favorites</b>\n" .
        "Save names you like for later.\n\n" .

        "🕘 <b>History</b>\n" .
        "See your recent searches.\n\n" .

        "⚠️ <b>Note:</b>\n" .
        "Profile links and availability indicators may change depending on platform restrictions, privacy settings and rate limits."
    );
}


/* ========================================================
   ADMIN PANEL
======================================================== */

function adminPanel($chatId)
{
    global $ADMIN_ID;

    if (
        (int)$chatId !==
        (int)$ADMIN_ID
    ) {
        return;
    }

    sendMsg(
        $chatId,

        "👑 <b>USERSCAN AI ADMIN</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "Control Center",

        [
            'inline_keyboard' => [

                [
                    [
                        'text' =>
                            '📊 Statistics',
                        'callback_data' =>
                            'admin|stats'
                    ],

                    [
                        'text' =>
                            '👥 Users',
                        'callback_data' =>
                            'admin|users'
                    ]
                ],

                [
                    [
                        'text' =>
                            '📢 Broadcast',
                        'callback_data' =>
                            'admin|broadcast'
                    ]
                ],

                [
                    [
                        'text' =>
                            '🔥 Add Trending',
                        'callback_data' =>
                            'admin|addtrend'
                    ]
                ]

            ]
        ]
    );
}


/* ========================================================
   ADMIN STATS
======================================================== */

function adminStats($chatId)
{
    global $db;

    $total =
        $db->querySingle(
            "SELECT COUNT(*) FROM users"
        );

    $active =
        $db->querySingle(
            "SELECT COUNT(*) FROM users
             WHERE last_seen >= " .
             (time() - 86400)
        );

    $searches =
        $db->querySingle(
            "SELECT SUM(searches) FROM users"
        );

    $generated =
        $db->querySingle(
            "SELECT SUM(generated) FROM users"
        );

    $banned =
        $db->querySingle(
            "SELECT COUNT(*) FROM users
             WHERE banned = 1"
        );

    $favorites =
        $db->querySingle(
            "SELECT COUNT(*) FROM favorites"
        );


    $text =
        "📊 <b>USERSCAN STATISTICS</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n" .

        "👥 Total Users: <b>" .
        ($total ?: 0) .
        "</b>\n" .

        "🟢 Active 24h: <b>" .
        ($active ?: 0) .
        "</b>\n\n" .

        "🔍 Searches: <b>" .
        ($searches ?: 0) .
        "</b>\n" .

        "💡 Generated: <b>" .
        ($generated ?: 0) .
        "</b>\n" .

        "⭐ Favorites: <b>" .
        ($favorites ?: 0) .
        "</b>\n" .

        "🚫 Banned: <b>" .
        ($banned ?: 0) .
        "</b>";
        

    sendMsg(
        $chatId,
        $text
    );
}


/* ========================================================
   ADMIN USERS
======================================================== */

function adminUsers($chatId)
{
    global $db;

    $result =
        $db->query("
            SELECT
                id,
                username,
                first_name,
                searches
            FROM users
            ORDER BY last_seen DESC
            LIMIT 20
        ");

    $text =
        "👥 <b>RECENT USERS</b>\n" .
        "━━━━━━━━━━━━━━━━━━\n\n";

    while (
        $row =
        $result->fetchArray(
            SQLITE3_ASSOC
        )
    ) {

        $name =
            htmlspecialchars(
                $row['first_name'] ?: 'Unknown'
            );

        $username =
            $row['username']
            ? '@' .
              htmlspecialchars(
                  $row['username']
              )
            : 'No username';

        $text .=
            "👤 <b>" .
            $name .
            "</b>\n" .

            "🆔 " .
            $row['id'] .
            "\n" .

            "🔗 " .
            $username .
            "\n" .

            "🔍 Searches: " .
            $row['searches'] .
            "\n\n";
    }

    sendMsg(
        $chatId,
        $text
    );
}


/* ========================================================
   BROADCAST
======================================================== */

function broadcast($adminId, $message)
{
    global $db;

    $result =
        $db->query(
            "SELECT id FROM users
             WHERE banned = 0"
        );

    $sent = 0;
    $failed = 0;

    while (
        $row =
        $result->fetchArray(
            SQLITE3_ASSOC
        )
    ) {

        $response =
            sendMsg(
                $row['id'],
                "📢 <b>Official Announcement</b>\n\n" .
                $message
            );

        if (
            !empty(
                $response['ok']
            )
        ) {

            $sent++;

        } else {

            $failed++;
        }

        usleep(50000);
    }

    sendMsg(
        $adminId,

        "✅ <b>BROADCAST COMPLETE</b>\n\n" .

        "🟢 Sent: " .
        $sent .
        "\n" .

        "🔴 Failed: " .
        $failed
    );
}


/* ========================================================
   UPDATE RECEIVE
======================================================== */

$update =
    json_decode(
        file_get_contents(
            'php://input'
        ),
        true
    );


if (!$update) {

    echo
        "🔍 UserScan AI is Online.";

    exit;
}


/* ========================================================
   CALLBACK QUERY
======================================================== */

if (
    isset(
        $update['callback_query']
    )
) {

    $cb =
        $update['callback_query'];

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

    $messageId =
        $cb['message']['message_id'];

    $data =
        $cb['data'] ?? '';

    saveUser(
        $cb['from']
    );

    answerCallback(
        $cb['id']
    );


    /* FORCE JOIN */

    if (
        $data === 'check_join'
    ) {

        if (
            isJoined($chatId)
        ) {

            sendMsg(
                $chatId,

                "╭━━━━━━━━━━━━━━━━━━╮\n" .
                "   ✅ <b>ACCESS VERIFIED</b>\n" .
                "╰━━━━━━━━━━━━━━━━━━╯\n\n" .

                "Welcome to <b>UserScan AI</b>!\n\n" .

                "🔓 All tools are now unlocked.\n" .
                "🚀 Let's find your next identity.",

                mainMenu()
            );

        } else {

            forceJoin(
                $chatId
            );
        }

        exit;
    }


    /* CHECK FORCE JOIN */

    if (
        !isJoined($chatId)
    ) {

        forceJoin(
            $chatId
        );

        exit;
    }


    /* START GENERATOR */

    if (
        strpos(
            $data,
            'genstyle|'
        ) === 0
    ) {

        $style =
            substr(
                $data,
                9
            );

        setSession(
            $chatId,
            [
                'mode' =>
                    'generate',
                'style' =>
                    $style
            ]
        );

        sendMsg(
            $chatId,

            "💡 <b>USERNAME GENERATOR</b>\n\n" .

            "Send a name, brand or keyword.\n\n" .

            "Example:\n" .
            "<code>Adnan</code>\n" .
            "<code>Tech Master</code>\n" .
            "<code>Gaming</code>"
        );

        exit;
    }


    /* GENERATE AGAIN */

    if (
        $data === 'gen_again'
    ) {

        sendMsg(
            $chatId,

            "💡 <b>Choose Generator Style</b>",

            [
                'inline_keyboard' => [

                    [
                        [
                            'text' =>
                                '💎 Premium',
                            'callback_data' =>
                                'genstyle|premium'
                        ],

                        [
                            'text' =>
                                '⚡ Short',
                            'callback_data' =>
                                'genstyle|short'
                        ]
                    ],

                    [
                        [
                            'text' =>
                                '🤖 Tech',
                            'callback_data' =>
                                'genstyle|tech'
                        ],

                        [
                            'text' =>
                                '🎮 Gaming',
                            'callback_data' =>
                                'genstyle|gaming'
                        ]
                    ],

                    [
                        [
                            'text' =>
                                '💼 Professional',
                            'callback_data' =>
                                'genstyle|professional'
                        ]
                    ]

                ]
            ]
        );

        exit;
    }


    /* SAVE */

    if (
        strpos(
            $data,
            'save|'
        ) === 0
    ) {

        $username =
            substr(
                $data,
                5
            );

        saveFavorite(
            $chatId,
            $username
        );

        answerCallback(
            $cb['id'],
            '⭐ Saved!'
        );

        exit;
    }


    /* PLATFORM */

    if (
        strpos(
            $data,
            'platform|'
        ) === 0
    ) {

        $platform =
            substr(
                $data,
                9
            );

        setSession(
            $chatId,
            [
                'mode' =>
                    'platform',
                'platform' =>
                    $platform
            ]
        );

        sendMsg(
            $chatId,

            "📱 <b>Platform Search</b>\n\n" .

            "Send the username you want to search."
        );

        exit;
    }


    /* LINKS */

    if (
        $data === 'links_mode'
    ) {

        setSession(
            $chatId,
            [
                'mode' =>
                    'links'
            ]
        );

        sendMsg(
            $chatId,

            "🔗 <b>SOCIAL LINK MAKER</b>\n\n" .

            "Send a username.\n\n" .

            "Example:\n" .
            "<code>adnan</code>"
        );

        exit;
    }


    /* NEW SCORE */

    if (
        $data === 'check_again'
    ) {

        setSession(
            $chatId,
            [
                'mode' =>
                    'score'
            ]
        );

        sendMsg(
            $chatId,

            "🧠 <b>USERNAME SCORE</b>\n\n" .

            "Send a username to analyze."
        );

        exit;
    }


    /* ADMIN */

    if (
        (int)$chatId ===
        (int)$ADMIN_ID
    ) {

        if (
            $data === 'admin|stats'
        ) {

            adminStats(
                $chatId
            );

            exit;
        }

        if (
            $data === 'admin|users'
        ) {

            adminUsers(
                $chatId
            );

            exit;
        }

        if (
            $data === 'admin|broadcast'
        ) {

            setSession(
                $chatId,
                [
                    'mode' =>
                        'broadcast'
                ]
            );

            sendMsg(
                $chatId,

                "📢 <b>BROADCAST MODE</b>\n\n" .

                "Send the message you want to broadcast.\n\n" .

                "Use /cancel to stop."
            );

            exit;
        }

        if (
            $data === 'admin|addtrend'
        ) {

            setSession(
                $chatId,
                [
                    'mode' =>
                        'addtrend'
                ]
            );

            sendMsg(
                $chatId,

                "🔥 <b>ADD TRENDING NAME</b>\n\n" .

                "Format:\n" .
                "<code>username | category</code>\n\n" .

                "Example:\n" .
                "<code>TechNova | Tech</code>"
            );

            exit;
        }
    }

    exit;
}


/* ========================================================
   MESSAGE
======================================================== */

if (
    isset(
        $update['message']
    )
) {

    $message =
        $update['message'];

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

    $user =
        $message['from'] ?? [];

    $text =
        trim(
            $message['text'] ?? ''
        );


    saveUser(
        $user
    );


    /* BAN */

    if (
        isBanned($chatId)
    ) {

        sendMsg(
            $chatId,
            "🚫 <b>Access Denied</b>"
        );

        exit;
    }


    /* START */

    if (
        $text === '/start'
    ) {

        clearSession(
            $chatId
        );

        if (
            !isJoined($chatId)
        ) {

            forceJoin(
                $chatId
            );

            exit;
        }

        sendMsg(
            $chatId,

            "╭━━━━━━━━━━━━━━━━━━╮\n" .
            "     🔍 <b>USERSCAN AI</b>\n" .
            "╰━━━━━━━━━━━━━━━━━━╯\n\n" .

            "👋 Welcome to your Social Identity Toolkit.\n\n" .

            "🔍 Find usernames\n" .
            "💡 Generate brandable names\n" .
            "🧠 Score your username\n" .
            "🔗 Build social links\n" .
            "⭐ Save your favorites\n\n" .

            "🚀 <b>Find • Check • Build • Brand</b>",

            mainMenu()
        );

        exit;
    }


    /* ADMIN */

    if (
        $text === '/admin' &&
        (int)$chatId ===
        (int)$ADMIN_ID
    ) {

        adminPanel(
            $chatId
        );

        exit;
    }


    /* CANCEL */

    if (
        $text === '/cancel'
    ) {

        clearSession(
            $chatId
        );

        sendMsg(
            $chatId,
            "❌ Operation cancelled.",
            mainMenu()
        );

        exit;
    }


    /* FORCE JOIN */

    if (
        !isJoined($chatId)
    ) {

        forceJoin(
            $chatId
        );

        exit;
    }


    /* SESSION */

    $session =
        getSession(
            $chatId
        );


    /* ADMIN BROADCAST */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'broadcast' &&
        (int)$chatId ===
        (int)$ADMIN_ID
    ) {

        clearSession(
            $chatId
        );

        broadcast(
            $chatId,
            $text
        );

        exit;
    }


    /* ADMIN TRENDING */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'addtrend' &&
        (int)$chatId ===
        (int)$ADMIN_ID
    ) {

        $parts =
            explode(
                '|',
                $text,
                2
            );

        if (
            count($parts) !== 2
        ) {

            sendMsg(
                $chatId,

                "❌ Invalid format.\n\n" .

                "Use:\n" .
                "<code>username | category</code>"
            );

            exit;
        }

        $username =
            cleanUsername(
                trim($parts[0])
            );

        $category =
            trim($parts[1]);

        if (!$username) {

            sendMsg(
                $chatId,
                "❌ Invalid username."
            );

            exit;
        }

        $stmt =
            $db->prepare("
                INSERT INTO trending
                (username, category, created_at)
                VALUES
                (:username, :category, :created)
            ");

        $stmt->bindValue(
            ':username',
            $username,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':category',
            $category,
            SQLITE3_TEXT
        );

        $stmt->bindValue(
            ':created',
            time(),
            SQLITE3_INTEGER
        );

        $stmt->execute();

        clearSession(
            $chatId
        );

        sendMsg(
            $chatId,

            "✅ <b>Trending Username Added</b>\n\n" .

            "@" .
            htmlspecialchars($username) .
            "\n" .

            "#" .
            htmlspecialchars($category)
        );

        exit;
    }


    /* GENERATOR SESSION */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'generate'
    ) {

        $style =
            $session['style']
            ?? 'premium';

        clearSession(
            $chatId
        );

        generateUsernames(
            $chatId,
            $text,
            $style
        );

        exit;
    }


    /* SCORE SESSION */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'score'
    ) {

        clearSession(
            $chatId
        );

        scoreReport(
            $chatId,
            $text
        );

        exit;
    }


    /* LINKS SESSION */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'links'
    ) {

        clearSession(
            $chatId
        );

        socialLinks(
            $chatId,
            $text
        );

        exit;
    }


    /* PLATFORM SESSION */

    if (
        $session &&
        ($session['mode'] ?? '') ===
        'platform'
    ) {

        $platform =
            $session['platform']
            ?? '';

        clearSession(
            $chatId
        );

        platformLink(
            $chatId,
            $platform,
            $text
        );

        exit;
    }


    /* MENU */

    switch ($text) {


        /* FIND USERNAME */

        case '🔍 Find Username':

            setSession(
                $chatId,
                [
                    'mode' =>
                        'find'
                ]
            );

            sendMsg(
                $chatId,

                "🔍 <b>USERNAME FINDER</b>\n" .
                "━━━━━━━━━━━━━━━━━━\n\n" .

                "Enter the username you want to explore.\n\n" .

                "Example:\n" .
                "<code>adnan</code>\n\n" .

                "I'll create profile links across supported platforms."
            );

            break;


        /* GENERATE */

        case '💡 Generate Username':

            sendMsg(
                $chatId,

                "💡 <b>CHOOSE GENERATOR STYLE</b>",

                [
                    'inline_keyboard' => [

                        [
                            [
                                'text' =>
                                    '💎 Premium',
                                'callback_data' =>
                                    'genstyle|premium'
                            ],

                            [
                                'text' =>
                                    '⚡ Short',
                                'callback_data' =>
                                    'genstyle|short'
                            ]
                        ],

                        [
                            [
                                'text' =>
                                    '🤖 Tech',
                                'callback_data' =>
                                    'genstyle|tech'
                            ],

                            [
                                'text' =>
                                    '🎮 Gaming',
                                'callback_data' =>
                                    'genstyle|gaming'
                            ]
                        ],

                        [
                            [
                                'text' =>
                                    '💼 Professional',
                                'callback_data' =>
                                    'genstyle|professional'
                            ]
                        ]

                    ]
                ]
            );

            break;


        /* CHECK */

        case '⚡ Check Username':

            setSession(
                $chatId,
                [
                    'mode' =>
                        'check'
                ]
            );

            sendMsg(
                $chatId,

                "⚡ <b>USERNAME CHECKER</b>\n\n" .

                "Send a username.\n\n" .

                "Example:\n" .
                "<code>adnan</code>"
            );

            break;


        /* SCORE */

        case '🧠 Username Score':

            setSession(
                $chatId,
                [
                    'mode' =>
                        'score'
                ]
            );

            sendMsg(
                $chatId,

                "🧠 <b>USERNAME SCORE</b>\n\n" .

                "Send a username and I'll analyze its branding quality."
            );

            break;


        /* LINK MAKER */

        case '🔗 Social Link Maker':

            setSession(
                $chatId,
                [
                    'mode' =>
                        'links'
                ]
            );

            sendMsg(
                $chatId,

                "🔗 <b>SOCIAL LINK MAKER</b>\n\n" .

                "Send a username.\n\n" .

                "Example:\n" .
                "<code>adnan</code>"
            );

            break;


        /* PLATFORM */

        case '📱 Platform Search':

            platformMenu(
                $chatId
            );

            break;


        /* FAVORITES */

        case '⭐ My Favorites':

            showFavorites(
                $chatId
            );

            break;


        /* HISTORY */

        case '🕘 Search History':

            showHistory(
                $chatId
            );

            break;


        /* TRENDING */

        case '🔥 Trending Names':

            showTrending(
                $chatId
            );

            break;


        /* HOW */

        case 'ℹ️ How It Works':

            howItWorks(
                $chatId
            );

            break;


        /* FIND SESSION */

        default:

            if (
                $session &&
                ($session['mode'] ?? '') ===
                'find'
            ) {

                clearSession(
                    $chatId
                );

                $username =
                    cleanUsername(
                        $text
                    );

                if (!$username) {

                    sendMsg(
                        $chatId,
                        "❌ Invalid username."
                    );

                    exit;
                }

                addHistory(
                    $chatId,
                    $username
                );

                $stmt =
                    $db->prepare("
                        UPDATE users
                        SET searches = searches + 1
                        WHERE id = :id
                    ");

                $stmt->bindValue(
                    ':id',
                    $chatId,
                    SQLITE3_INTEGER
                );

                $stmt->execute();

                socialLinks(
                    $chatId,
                    $username
                );

                exit;
            }


            /* CHECK SESSION */

            if (
                $session &&
                ($session['mode'] ?? '') ===
                'check'
            ) {

                clearSession(
                    $chatId
                );

                $username =
                    cleanUsername(
                        $text
                    );

                if (!$username) {

                    sendMsg(
                        $chatId,
                        "❌ Invalid username."
                    );

                    exit;
                }

                addHistory(
                    $chatId,
                    $username
                );

                $score =
                    usernameScore(
                        $username
                    );

                sendMsg(
                    $chatId,

                    "⚡ <b>USERNAME CHECK</b>\n" .
                    "━━━━━━━━━━━━━━━━━━\n\n" .

                    "🔍 Username:\n" .
                    "<code>@" .
                    htmlspecialchars(
                        $username
                    ) .
                    "</code>\n\n" .

                    "🧠 Brand Score: <b>" .
                    $score .
                    "/100</b>\n\n" .

                    "📱 Supported profile links are ready below.\n\n" .

                    "⚠️ <i>Actual availability cannot be guaranteed from a simple public web check. Platform restrictions and privacy settings may affect results.</i>",

                    [
                        'inline_keyboard' => [

                            [
                                [
                                    'text' =>
                                        '📸 Instagram',
                                    'url' =>
                                        'https://instagram.com/' .
                                        $username
                                ],

                                [
                                    'text' =>
                                        '🎵 TikTok',
                                    'url' =>
                                        'https://tiktok.com/@' .
                                        $username
                                ]
                            ],

                            [
                                [
                                    'text' =>
                                        '▶️ YouTube',
                                    'url' =>
                                        'https://youtube.com/@' .
                                        $username
                                ],

                                [
                                    'text' =>
                                        '🐦 X',
                                    'url' =>
                                        'https://x.com/' .
                                        $username
                                ]
                            ],

                            [
                                [
                                    'text' =>
                                        '✈️ Telegram',
                                    'url' =>
                                        'https://t.me/' .
                                        $username
                                ]
                            ],

                            [
                                [
                                    'text' =>
                                        '⭐ Save',
                                    'callback_data' =>
                                        'save|' .
                                        $username
                                ]
                            ]

                        ]
                    ]
                );

                exit;
            }


            sendMsg(
                $chatId,

                "🤖 <b>UserScan AI</b>\n\n" .

                "Please use the menu below to choose a tool.",

                mainMenu()
            );

            break;
    }

    exit;
}

?>