<?php
// تنظیمات ربات
$botToken = "توکن_ربات_خود_را_وارد_کنید";
$adminIDs = [123456789, 987654321]; // آیدی عددی ادمین‌های اصلی را اینجا بنویسید

// دریافت ورودی از تلگرام
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!$update) exit;

// پردازش پیام متنی
if (isset($update["message"])) {
    $message = $update["message"];
    $chatID = $message["chat"]["id"];
    $userID = $message["from"]["id"];
    $text = trim($message["text"] ?? "");
    
    // بررسی: آیا کاربر ادمین اصلی است؟
    if (!in_array($userID, $adminIDs)) {
        file_put_contents("log.txt", "$userID تلاش غیرمجاز کرد: $text\n", FILE_APPEND);
        exit;
    }
    
    // بررسی دستور "تاس عدد"
    if (preg_match("/^تاس\s+(\d+)$/u", $text, $matches)) {
        $count = intval($matches[1]);
        
        // محدودیت برای جلوگیری از خرابکاری
        if ($count < 1) {
            sendMessage($chatID, "❌ تعداد تاس باید حداقل 1 باشد.", $botToken);
            exit;
        }
        if ($count > 20) {  // ✅ تغییر به 20
            sendMessage($chatID, "⚠️ حداکثر 20 تاس می‌توانید بریزید.", $botToken);
            exit;
        }
        
        // انداختن تاس‌ها
        $results = [];
        for ($i = 1; $i <= $count; $i++) {
            $dice = rand(1, 6);
            $results[] = "$i‌_$dice";
        }
        
        // ساختن خروجی
        $output = "🎲 نتایج انداختن $count تاس:\n\n";
        $output .= implode("\n", $results);
        
        // اضافه کردن آمار
        $output .= "\n\n📊 تعداد هر عدد:\n";
        for ($num = 1; $num <= 6; $num++) {
            $found = 0;
            foreach ($results as $r) {
                if (strpos($r, "_{$num}") !== false) $found++;
            }
            $output .= "عدد $num : $found بار\n";
        }
        
        sendMessage($chatID, $output, $botToken);
    }
}

// تابع ارسال پیام
function sendMessage($chatID, $message, $botToken) {
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $data = [
        "chat_id" => $chatID,
        "text" => $message,
        "parse_mode" => "HTML"
    ];
    
    $options = [
        "http" => [
            "header" => "Content-Type: application/x-www-form-urlencoded\r\n",
            "method" => "POST",
            "content" => http_build_query($data)
        ]
    ];
    $context = stream_context_create($options);
    file_get_contents($url, false, $context);
}
?>