<?php
   error_reporting(E_ALL);
   ini_set("display_errors", "1");
   
http_response_code(200);

error_reporting(E_ALL);
ini_set("display_errors", "1");

const TOKEN    = "9128505244:AAEJ6ZjFm-y1y1bVCZKc-LQWgTiR8GX0WH0";
const ADMIN_ID = 5907210771;          // آیدی عددی خودت
const SECRET   = "111";    // فقط حروف انگلیسی، عدد، _ و -
const DATA     = __DIR__ . "/data.json";

const RIGHTS = [
    "can_change_info"        => "تغییر اطلاعات",
    "can_post_messages"      => "ارسال پیام (کانال)",
    "can_edit_messages"      => "ویرایش پیام (کانال)",
    "can_delete_messages"    => "حذف پیام",
    "can_restrict_members"   => "مسدود کردن",
    "can_invite_users"       => "دعوت کاربر",
    "can_pin_messages"       => "پین پیام (گروه)",
    "can_promote_members"    => "افزودن ادمین",
    "can_manage_video_chats" => "ویس‌چت",
    "is_anonymous"           => "ناشناس",
];
const CHANNEL_ONLY = ["can_post_messages", "can_edit_messages"];
const GROUP_ONLY   = ["can_pin_messages"];

// ---------- ابزارها ----------
function api($method, $params = []) {
    $url  = "https://api.telegram.org/bot" . TOKEN . "/$method";
    $body = json_encode($params, JSON_UNESCAPED_UNICODE);

    if (function_exists("curl_init")) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $body,
            CURLOPT_HTTPHEADER     => ["Content-Type: application/json"],
            CURLOPT_TIMEOUT        => 25,
        ]);
        $raw = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if ($raw === false) return ["ok" => false, "description" => "curl error: $err"];
    } else {
        $raw = @file_get_contents($url, false, stream_context_create(["http" => [
            "method"  => "POST",
            "header"  => "Content-Type: application/json",
            "content" => $body,
            "timeout" => 25,
        ]]));
        if ($raw === false) return ["ok" => false, "description" => "request failed (curl غیرفعال است)"];
    }
    return json_decode($raw, true) ?: ["ok" => false, "description" => "invalid response"];
}

function load() {
    $d = is_file(DATA) ? json_decode(file_get_contents(DATA), true) : null;
    if (!is_array($d)) $d = [];
    return $d + ["bots" => [], "state" => null, "done" => []];
}
function save($d) {
    file_put_contents(DATA, json_encode($d, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
}
function default_rights() {
    $r = [];
    foreach (RIGHTS as $k => $_) $r[$k] = true;
    $r["can_promote_members"] = false;
    $r["is_anonymous"] = false;
    return $r;
}

// ---------- صفحات کمکی (باز کردن در مرورگر) ----------
if (isset($_GET["setup"]) || isset($_GET["info"])) {
    header("Content-Type: text/plain; charset=utf-8");
    echo "PHP: " . PHP_VERSION . "\n";
    echo "curl: " . (function_exists("curl_init") ? "OK" : "غیرفعال") . "\n";
    echo "نوشتن در پوشه: " . (is_writable(__DIR__) ? "OK" : "مشکل دارد (پرمیشن پوشه را 755 یا 775 کن)") . "\n\n";

    if (isset($_GET["setup"])) {
        $https = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off") || ($_SERVER["HTTP_X_FORWARDED_PROTO"] ?? "") === "https";
        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["SCRIPT_NAME"];
        echo "Webhook URL: $url\n";
        echo "setWebhook: " . json_encode(api("setWebhook", [
            "url"             => $url,
            "secret_token"    => SECRET,
            "allowed_updates" => ["message", "callback_query", "my_chat_member"],
            "drop_pending_updates" => true,
        ]), JSON_UNESCAPED_UNICODE) . "\n\n";
    }
    echo "getMe: " . json_encode(api("getMe"), JSON_UNESCAPED_UNICODE) . "\n\n";
    echo "getWebhookInfo: " . json_encode(api("getWebhookInfo"), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
    exit;
}

// ---------- از اینجا به بعد فقط درخواست‌های تلگرام ----------
if (($_SERVER["HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN"] ?? "") !== SECRET) {
    http_response_code(403);
    echo "forbidden";
    exit;
}

$u = json_decode(file_get_contents("php://input"), true);
if (!$u) exit;

// ---------- منوها ----------
function main_menu() {
    return ["inline_keyboard" => [
        [["text" => "➕ افزودن ربات", "callback_data" => "add"]],
        [["text" => "📋 لیست / تنظیم ربات‌ها", "callback_data" => "list"]],
    ]];
}
function list_view($d) {
    if (!$d["bots"]) {
        return ["هنوز رباتی تنظیم نکرده‌ای.", ["inline_keyboard" => [
            [["text" => "➕ افزودن ربات", "callback_data" => "add"]],
            [["text" => "🔙 منو", "callback_data" => "menu"]],
        ]]];
    }
    $rows = [];
    foreach ($d["bots"] as $b) {
        $rows[] = [["text" => "🤖 " . $b["name"] . " (" . $b["id"] . ")", "callback_data" => "b:" . $b["id"]]];
    }
    $rows[] = [["text" => "🔙 منو", "callback_data" => "menu"]];
    return ["ربات‌هایی که باید ادمین شوند:", ["inline_keyboard" => $rows]];
}
function bot_view($d, $id) {
    foreach ($d["bots"] as $b) {
        if ((string)$b["id"] === (string)$id) {
            $btns = [];
            foreach (RIGHTS as $k => $label) {
                $btns[] = ["text" => (!empty($b["rights"][$k]) ? "✅ " : "❌ ") . $label,
                           "callback_data" => "t:$id:$k"];
            }
            $rows = array_chunk($btns, 2);
            $rows[] = [["text" => "🗑 حذف ربات", "callback_data" => "d:$id"]];
            $rows[] = [["text" => "🔙 بازگشت", "callback_data" => "list"]];
            return ["🤖 " . $b["name"] . "\nآیدی: " . $b["id"] . "\n\nدسترسی‌ها (برای تغییر بزن):",
                    ["inline_keyboard" => $rows]];
        }
    }
    return ["پیدا نشد.", main_menu()];
}

// ---------- ادمین کردن ربات‌ها در یک چت ----------
function process_chat($chat) {
    $d = load();
    $cid = $chat["id"];
    if (!$d["bots"] || in_array($cid, $d["done"])) return;
    $d["done"][] = $cid;
    save($d);

    $isChannel = $chat["type"] === "channel";
    $ok = []; $fail = [];

    foreach ($d["bots"] as $b) {
        $p = ["chat_id" => $cid, "user_id" => (int)$b["id"]];
        foreach ($b["rights"] as $k => $v) {
            if ($isChannel && in_array($k, GROUP_ONLY)) continue;
            if (!$isChannel && in_array($k, CHANNEL_ONLY)) continue;
            $p[$k] = (bool)$v;
        }
        $r = api("promoteChatMember", $p);
        if (!empty($r["ok"])) $ok[] = $b["name"];
        else $fail[] = $b["name"] . " ← " . ($r["description"] ?? "?");
        usleep(500000);
    }

    $msg = "📌 " . ($chat["title"] ?? $cid) . "\n";
    if ($ok)   $msg .= "✅ ادمین شدند: " . implode("، ", $ok) . "\n";
    if ($fail) $msg .= "❌ ناموفق:\n" . implode("\n", $fail);
    api("sendMessage", ["chat_id" => ADMIN_ID, "text" => $msg]);
}

// ---------- ربات ادر در یک چت ادمین شد ----------
if (isset($u["my_chat_member"])) {
    $m    = $u["my_chat_member"];
    $new  = $m["new_chat_member"];
    $chat = $m["chat"];

    if (in_array($chat["type"], ["channel", "group", "supergroup"]) && $new["status"] === "administrator") {
        if (!empty($new["can_promote_members"])) {
            process_chat($chat);
        } else {
            api("sendMessage", ["chat_id" => ADMIN_ID,
                "text" => "⚠️ ربات در «" . ($chat["title"] ?? "") . "» ادمین شد ولی دسترسی Add New Admins ندارد."]);
        }
    } elseif (in_array($new["status"], ["left", "kicked"])) {
        $d = load();
        $d["done"] = array_values(array_diff($d["done"], [$chat["id"]]));
        save($d);
    }
    exit;
}

// ---------- فقط ادمین ----------
$from = $u["message"]["from"]["id"] ?? $u["callback_query"]["from"]["id"] ?? 0;
if ($from != ADMIN_ID) exit;

$d = load();

// ---------- پیام‌ها ----------
if (isset($u["message"])) {
    $msg  = $u["message"];
    $chat = $msg["chat"]["id"];
    $text = trim($msg["text"] ?? "");
    if ($msg["chat"]["type"] !== "private") exit;

    if (in_array($text, ["/start", "/menu", "/cancel"])) {
        $d["state"] = null; save($d);
        api("sendMessage", ["chat_id" => $chat, "text" => "🤖 ربات ادر\nمنوی اصلی:", "reply_markup" => main_menu()]);
        exit;
    }

    if (($d["state"] ?? null) === "add") {
        $id = null; $name = null;

        $fu = $msg["forward_from"] ?? ($msg["forward_origin"]["sender_user"] ?? null);
        if ($fu) {
            if (empty($fu["is_bot"])) {
                api("sendMessage", ["chat_id" => $chat, "text" => "❌ این پیام از یک ربات نیست. دوباره بفرست یا /cancel"]);
                exit;
            }
            $id   = $fu["id"];
            $name = isset($fu["username"]) ? "@" . $fu["username"] : $fu["first_name"];
        } elseif (preg_match('/^(\d{5,15})(?:\s+(.+))?$/u', $text, $mm)) {
            $id   = (int)$mm[1];
            $name = isset($mm[2]) ? trim($mm[2]) : (string)$id;
        }

        if (!$id) {
            api("sendMessage", ["chat_id" => $chat,
                "text" => "❌ نامعتبر. آیدی عددی ربات (اختیاری: بعدش یوزرنیم) یا یک پیام فوروارد‌شده از ربات بفرست.\nمثال: 123456789 @MyBot\nانصراف: /cancel"]);
            exit;
        }

        $exists = false;
        foreach ($d["bots"] as $b) if ($b["id"] == $id) $exists = true;
        if ($exists) {
            api("sendMessage", ["chat_id" => $chat, "text" => "⚠️ این ربات قبلاً اضافه شده."]);
        } else {
            $d["bots"][] = ["id" => $id, "name" => $name, "rights" => default_rights()];
            api("sendMessage", ["chat_id" => $chat, "text" => "✅ $name اضافه شد."]);
        }
        $d["state"] = null; save($d);
        [$t, $kb] = list_view($d);
        api("sendMessage", ["chat_id" => $chat, "text" => $t, "reply_markup" => $kb]);
    }
    exit;
}

// ---------- دکمه‌ها ----------
if (isset($u["callback_query"])) {
    $cb   = $u["callback_query"];
    $data = $cb["data"];
    $chat = $cb["message"]["chat"]["id"];
    $mid  = $cb["message"]["message_id"];

    $edit = function ($text, $kb) use ($chat, $mid) {
        api("editMessageText", ["chat_id" => $chat, "message_id" => $mid, "text" => $text, "reply_markup" => $kb]);
    };

    if ($data === "menu") {
        $edit("🤖 ربات ادر\nمنوی اصلی:", main_menu());
    } elseif ($data === "add") {
        $d["state"] = "add"; save($d);
        $edit("آیدی عددی ربات رو بفرست (اختیاری: بعدش یوزرنیم یا اسم)\nمثال: 123456789 @MyBot\nیا یک پیام از اون ربات فوروارد کن.\nانصراف: /cancel", ["inline_keyboard" => []]);
    } elseif ($data === "list") {
        [$t, $kb] = list_view($d);
        $edit($t, $kb);
    } elseif (strpos($data, "b:") === 0) {
        [$t, $kb] = bot_view($d, substr($data, 2));
        $edit($t, $kb);
    } elseif (strpos($data, "t:") === 0) {
        [, $id, $right] = explode(":", $data);
        foreach ($d["bots"] as &$b) {
            if ((string)$b["id"] === $id && isset(RIGHTS[$right])) {
                $b["rights"][$right] = empty($b["rights"][$right]);
            }
        }
        unset($b);
        save($d);
        [$t, $kb] = bot_view($d, $id);
        $edit($t, $kb);
    } elseif (strpos($data, "d:") === 0) {
        $id = substr($data, 2);
        $edit("مطمئنی این ربات حذف شود؟", ["inline_keyboard" => [[
            ["text" => "✅ بله", "callback_data" => "dc:$id"],
            ["text" => "❌ خیر", "callback_data" => "b:$id"],
        ]]]);
    } elseif (strpos($data, "dc:") === 0) {
        $id = substr($data, 3);
        $d["bots"] = array_values(array_filter($d["bots"], fn($b) => (string)$b["id"] !== $id));
        save($d);
        [$t, $kb] = list_view($d);
        $edit($t, $kb);
    }
    api("answerCallbackQuery", ["callback_query_id" => $cb["id"]]);
}