<?php
// ==============================
// ربات‌ساز نهایی — نسخه اصلاح‌شده
// ==============================

// --- توکن ربات‌ساز ---
define('BOT_TOKEN_RAN', '8541157756:AAHon70mx4A3yzrtAFy-_EeUMKcTWnVzXT4');

// -----------------------------
$update = json_decode(file_get_contents("php://input"), true);
$message = $update["message"] ?? null;
$callback = $update["callback_query"] ?? null;

$user_state_file = "states.json";
$db_pool_file = "db_pool.json";
$template_folder = "VPN";
$bots_folder = "bots";
$main_domain = "stitchshop.ir/Botsaz";

if (!file_exists($user_state_file)) file_put_contents($user_state_file, "{}");
$states = json_decode(file_get_contents($user_state_file), true);

// ======================
// مدیریت پیام‌ها
// ======================
if ($message) {

    $chat_id = $message["chat"]["id"];
    $text = $message["text"] ?? "";

    if (!isset($states[$chat_id])) $states[$chat_id] = ["step" => "none"];
    $step = $states[$chat_id]["step"];

    // ---------------- /start ----------------
    if ($text == "/start") {

        sendMessage($chat_id,
            "سلام ✌️\nیک گزینه انتخاب کن:",
            null,
            [
                "keyboard" => [
                    [["text" => "ساخت ربات 🤖"]],
                    [["text" => "مدیریت ربات ⚙️"]]
                ],
                "resize_keyboard" => true
            ]
        );

        $states[$chat_id]["step"] = "none";
    }

    // ---------------- مدیریت ربات ----------------
    elseif ($text == "مدیریت ربات ⚙️") {

        if (!isset($states[$chat_id]["bot_folder"])) {
            sendMessage($chat_id, "❌ شما هنوز رباتی نساخته‌اید.");
        } else {

            $bot_username = $states[$chat_id]["bot_username"];

            sendMessage($chat_id,
                "مدیریت ربات:\nربات شما: @$bot_username",
                null,
                [
                    "inline_keyboard" => [
                        [["text" => "مشاهده اطلاعات دیتابیس 🗄", "callback_data" => "show_db"]],
                        [["text" => "مشاهده لینک ربات 🤖", "callback_data" => "show_bot"]],
                    ]
                ]
            );
        }
    }

    // ---------------- ساخت ربات ----------------
    elseif ($text == "ساخت ربات 🤖") {

        sendMessage($chat_id, "🔑 لطفاً *توکن ربات* خود را بفرست:", "Markdown");
        $states[$chat_id]["step"] = "get_token";
    }

    elseif ($step == "get_token") {

        $states[$chat_id]["token"] = $text;
        sendMessage($chat_id, "👤 حالا *آیدی عددی مدیر* را بفرست:", "Markdown");
        $states[$chat_id]["step"] = "get_admin";
    }

    elseif ($step == "get_admin") {

        $states[$chat_id]["admin"] = $text;

        sendMessage(
            $chat_id,
            "⚠️ توجه!\nابتدا ربات خود را استارت کنید.\nبعد روی دکمه زیر بزنید:",
            "Markdown",
            [
                "inline_keyboard" => [
                    [["text" => "تأیید و ادامه ✔", "callback_data" => "confirm_install"]]
                ]
            ]
        );

        $states[$chat_id]["step"] = "wait_confirm";
    }

    file_put_contents($user_state_file, json_encode($states, JSON_PRETTY_PRINT));
}



// ======================
// مدیریت CALLBACK
// ======================
if ($callback) {

    $chat_id = $callback["message"]["chat"]["id"];
    $data = $callback["data"];

    // ------- نمایش اطلاعات دیتابیس -------
    if ($data == "show_db") {

        $st = $states[$chat_id];

        if (!isset($st["dbname"])) {
            sendMessage($chat_id, "❌ دیتابیس ذخیره نشده.");
            exit;
        }

        $msg =
            "🗄 *اطلاعات دیتابیس ربات:*\n\n" .
            "📌 DB Name: `" . $st["dbname"] . "`\n" .
            "👤 Username: `" . $st["dbuser"] . "`\n" .
            "🔐 Password: `" . $st["dbpass"] . "`";

        sendMessage($chat_id, $msg, "Markdown");
        exit;
    }

    // ------- نمایش لینک ربات -------
    if ($data == "show_bot") {

        $bot_username = $states[$chat_id]["bot_username"] ?? null;

        if (!$bot_username) {
            sendMessage($chat_id, "❌ اطلاعات ربات یافت نشد.");
            exit;
        }

        sendMessage(
            $chat_id,
            "🤖 ربات شما آماده است:",
            null,
            [
                "inline_keyboard" => [
                    [["text" => "ورود به ربات", "url" => "https://t.me/$bot_username"]]
                ]
            ]
        );

        exit;
    }

    // ------- نصب ربات -------
    if ($data == "confirm_install") {

        if (!isset($states[$chat_id]["token"], $states[$chat_id]["admin"])) {
            sendMessage($chat_id, "❌ خطا: اطلاعات کامل نیست.");
            exit;
        }

        $token = $states[$chat_id]["token"];
        $admin = $states[$chat_id]["admin"];

        // گرفتن دیتابیس
        if (!file_exists($db_pool_file)) file_put_contents($db_pool_file, "[]");
        $db_pool = json_decode(file_get_contents($db_pool_file), true);

        if (count($db_pool) == 0) {
            sendMessage($chat_id, "❌ دیتابیس خالی است!");
            exit;
        }

        $db = array_shift($db_pool);
        file_put_contents($db_pool_file, json_encode($db_pool, JSON_PRETTY_PRINT));

        $dbname = $db["dbname"];
        $usernamedb = $db["username"];
        $passworddb = $db["password"];

        // گرفتن یوزرنیم ربات
        $me = json_decode(file_get_contents("https://api.telegram.org/bot$token/getMe"), true);

        if (!isset($me["result"]["username"])) {
            sendMessage($chat_id, "❌ توکن اشتباه است!");
            exit;
        }

        $username_bot = $me["result"]["username"];

        // ساخت اسم پوشه با فرمت جدید
        $randomNum = str_pad(strval(rand(0, 9999999999)), 10, "0", STR_PAD_LEFT);
        $randomStr = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);

        $folderName = "vpn_" . $randomNum . "_" . $randomStr;
        $user_folder = "$bots_folder/$folderName";

        recurseCopy($template_folder, $user_folder);

        // جایگذاری در config.php
        $config_path = $user_folder . "/config.php";
        $config = file_get_contents($config_path);

        $config = preg_replace("/\\\$dbname\\s*=\\s*['\"].*?['\"];/", "\$dbname = '$dbname';", $config);
        $config = preg_replace("/\\\$usernamedb\\s*=\\s*['\"].*?['\"];/", "\$usernamedb = '$usernamedb';", $config);
        $config = preg_replace("/\\\$passworddb\\s*=\\s*['\"].*?['\"];/", "\$passworddb = '$passworddb';", $config);
        $config = preg_replace("/\\\$APIKEY\\s*=\\s*['\"].*?['\"];/", "\$APIKEY = '$token';", $config);
        $config = preg_replace("/\\\$adminnumber\\s*=\\s*['\"].*?['\"];/", "\$adminnumber = '$admin';", $config);
        $config = preg_replace("/\\\$domainhosts\\s*=\\s*['\"].*?['\"];/", "\$domainhosts = '$main_domain/$bots_folder/$folderName';", $config);
        $config = preg_replace("/\\\$usernamebot\\s*=\\s*['\"].*?['\"];/", "\$usernamebot = '$username_bot';", $config);

        file_put_contents($config_path, $config);

        // اجرای جدول‌ها
        $table_url = "https://$main_domain/$bots_folder/$folderName/table.php";
        getContents($table_url);

        // ست وبهوک
        $webhook_url = "https://$main_domain/$bots_folder/$folderName/index.php";
        file_get_contents("https://api.telegram.org/bot$token/setWebhook?url=$webhook_url");

        // ذخیره کامل اطلاعات در states.json
        $states[$chat_id]["bot_folder"] = $folderName;
        $states[$chat_id]["dbname"] = $dbname;
        $states[$chat_id]["dbuser"] = $usernamedb;
        $states[$chat_id]["dbpass"] = $passworddb;
        $states[$chat_id]["bot_username"] = $username_bot;
        $states[$chat_id]["bot_token"] = $token;

        file_put_contents($user_state_file, json_encode($states, JSON_PRETTY_PRINT));

        // پیام‌ها
        sendMessage(
            $chat_id,
            "✅ ربات شما با موفقیت نصب شد",
            null,
            [
                "inline_keyboard" => [
                    [["text" => "ورود به ربات 🫠", "url" => "https://t.me/$username_bot"]]
                ]
            ]
        );

        sendMessageToUserBot($token, $admin,
            "✅ ربات شما روی سرور نتیفای نصب شد",
            null,
            [
                "inline_keyboard" => [
                    [["text" => "شروع مدیریت ⚙️", "url" => "https://t.me/$username_bot?start=admin"]]
                ]
            ]
        );

    }
}


// =======================
// توابع
// =======================
function sendMessage($chat_id, $text, $parse_mode = null, $keyboard = null) {
    $data = ["chat_id" => $chat_id, "text" => $text];
    if ($parse_mode) $data["parse_mode"] = $parse_mode;
    if ($keyboard) $data["reply_markup"] = json_encode($keyboard);
    file_get_contents("https://api.telegram.org/bot" . BOT_TOKEN_RAN . "/sendMessage?" . http_build_query($data));
}

function sendMessageToUserBot($token, $chat, $text, $parse_mode = null, $keyboard = null) {
    $data = ["chat_id" => $chat, "text" => $text];
    if ($parse_mode) $data["parse_mode"] = $parse_mode;
    if ($keyboard) $data["reply_markup"] = json_encode($keyboard);
    file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($data));
}

function recurseCopy($src, $dst) {
    $dir = opendir($src);
    @mkdir($dst, 0777, true);
    while (($file = readdir($dir)) !== false) {
        if ($file == '.' || $file == '..') continue;
        if (is_dir("$src/$file")) recurseCopy("$src/$file", "$dst/$file");
        else copy("$src/$file", "$dst/$file");
    }
    closedir($dir);
}

function getContents($url) {
    $context = stream_context_create(['http' => ['timeout' => 10], 'https' => ['timeout' => 10]]);
    $response = @file_get_contents($url, false, $context);
    return $response ? json_decode($response, true) : null;
}

?>