<?php
// تست پیشرفته ساخت گروهی اکانت در سرور پاسارگارد (VPNet) - نسخه خروجی استاندارد Bulk

$apiUrlBase = "https://cs.myspacex.shop:8000";
$adminUser  = "bastani";
$adminPass  = "kucqeGheVwun2020@";

$results = [];
$errorMsg = '';
$bulkOutputText = ''; // متغیر برای ذخیره خروجی متنی گروهی

// ==========================================
// توابع ارتباط با API
// ==========================================
function getAccessToken($urlBase, $username, $password) {
    $url = $urlBase . "/api/admin/token";
    $postData = http_build_query(["grant_type" => "password", "username" => $username, "password" => $password]);
    $headers = [
        "User-Agent: Mozilla/5.0", "Accept: */*", "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
        "x-client-timezone: Asia/Tehran", "x-client-timezone-offset-minutes: 210", "Origin: " . $urlBase, "Referer: " . $urlBase . "/dashboard/"
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) return ['success' => false, 'error' => "خطا در لاگین: $response"];
    return ['success' => true, 'token' => json_decode($response, true)['access_token']];
}

function createAccount($urlBase, $token, $username, $trafficGB, $days, $groupId) {
    $url = $urlBase . "/api/user";
    $dataLimitBytes = (int)($trafficGB * pow(1024, 3));

    $expireVal = null;
    if ($days > 0) {
        date_default_timezone_set('Asia/Tehran');
        $expireVal = date('Y-m-d\TH:i:sP', time() + ($days * 86400)); 
    }

    $jsonData = json_encode([
        "username" => $username, "status" => "active", "data_limit" => $dataLimitBytes, "expire" => $expireVal,
        "note" => "", "group_ids" => [(int)$groupId], "proxy_settings" => ["shadowsocks" => ["method" => "chacha20-ietf-poly1305"]], "next_plan" => null
    ]);

    $headers = [
        "User-Agent: Mozilla/5.0", "Accept: application/json", "Authorization: Bearer " . $token,
        "Content-Type: application/json", "x-client-timezone: Asia/Tehran", "x-client-timezone-offset-minutes: 210",
        "Origin: " . $urlBase, "Referer: " . $urlBase . "/dashboard/"
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) return ['success' => false, 'error' => $error];
    
    $responseData = json_decode($response, true);
    if ($httpCode === 200 || $httpCode === 201) return ['success' => true, 'link' => $responseData['subscription_url'] ?? '-'];
    
    return ['success' => false, 'error' => $responseData['detail'] ?? $response];
}

// تولید فرمت یوزرنیم
function generateUsernameFormat($brand, $plan, $volume, $num, $position) {
    $parts = [];
    if ($position == 'after_brand') {
        if ($brand) $parts[] = "$brand-$num"; else $parts[] = $num;
        if ($plan) $parts[] = $plan;
        $parts[] = "{$volume}GB";
    } elseif ($position == 'after_plan') {
        if ($brand) $parts[] = $brand;
        if ($plan) $parts[] = "$plan-$num"; else $parts[] = $num;
        $parts[] = "{$volume}GB";
    } else { 
        if ($brand) $parts[] = $brand;
        if ($plan) $parts[] = $plan;
        $parts[] = "{$volume}GB";
        $parts[] = $num;
    }
    return implode("-", $parts);
}

// ==========================================
// پردازش فرم
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $brand = trim($_POST['brand']);
    $plan = trim($_POST['plan']);
    $volume = (float)$_POST['volume'];
    $days = (int)$_POST['days'];
    $groupId = (int)$_POST['group_id'];
    $position = $_POST['position'];
    $startNum = (int)$_POST['start_num'];
    $endNum = (int)$_POST['end_num'];

    if ($endNum >= $startNum) {
        $login = getAccessToken($apiUrlBase, $adminUser, $adminPass);
        if ($login['success']) {
            $token = $login['token'];
            $successCount = 0;
            $failCount = 0;

            for ($i = $startNum; $i <= $endNum; $i++) {
                $username = generateUsernameFormat($brand, $plan, $volume, $i, $position);
                $res = createAccount($apiUrlBase, $token, $username, $volume, $days, $groupId);
                
                if ($res['success']) {
                    // اگر موفق بود، به متن خروجی با فرمت دلخواه اضافه می‌شود
                    $bulkOutputText .= $username . "," . $res['link'] . "\n";
                    $successCount++;
                } else {
                    $failCount++;
                    // نگهداری خطاهای احتمالی برای نمایش
                    $results[] = ['username' => $username, 'status' => false, 'error' => $res['error']];
                }
            }
        } else {
            $errorMsg = "خطا در اتصال اولیه به API: " . $login['error'];
        }
    } else {
        $errorMsg = "شماره پایان باید بزرگتر یا مساوی شماره شروع باشد!";
    }
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>تولیدکننده گروهی اکانت (VPNet)</title>
    <script src="/vpnet-panel/assets/js/tailwindcss.js"></script>
    <link href="/vpnet-panel/assets/css/Vazirmatn-font-face.css" rel="stylesheet">
    <style>body { font-family: 'Vazirmatn', sans-serif; background-color: #f8fafc; }</style>
</head>
<body class="p-8">

<div class="max-w-5xl mx-auto">
    <div class="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden border-t-8 border-t-blue-600">
        
        <div class="bg-gray-50 border-b border-gray-100 p-6 flex justify-between items-center">
            <h2 class="text-lg font-black text-blue-800 flex items-center gap-2">
                <span class="text-2xl">⚡</span> ابزار ساخت مستقیم و گروهی اکانت در سرور اصلی
            </h2>
        </div>

        <div class="p-6">
            <?php if($errorMsg): ?>
                <div class="bg-red-50 text-red-600 p-4 rounded-xl font-bold mb-6 border border-red-200">❌ <?php echo $errorMsg; ?></div>
            <?php endif; ?>

            <form method="POST" class="block">
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-5 mb-6 bg-blue-50/50 p-5 rounded-2xl border border-blue-100">
                    <div>
                        <label class="block text-xs font-bold text-blue-800 mb-2">شناسه گروه (Group ID)</label>
                        <select name="group_id" class="w-full border-2 border-white p-3 rounded-xl outline-none focus:border-blue-500 font-bold bg-white">
                            <option value="2">گروه 2 (Silver)</option>
                            <option value="3">گروه 3 (Gold)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-blue-800 mb-2">حجم (GB)</label>
                        <input type="number" name="volume" value="50" required min="1" class="w-full border-2 border-white p-3 rounded-xl outline-none focus:border-blue-500 bg-white" dir="ltr">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-blue-800 mb-2">اعتبار (روز) - 0 = نامحدود</label>
                        <input type="number" name="days" value="30" required min="0" class="w-full border-2 border-white p-3 rounded-xl outline-none focus:border-blue-500 bg-white" dir="ltr">
                    </div>
                </div>

                <div class="bg-gray-50 p-5 rounded-2xl border border-gray-200 mb-6">
                    <h3 class="text-sm font-bold text-gray-700 mb-4">تنظیمات نام‌گذاری (تولید خودکار یوزرنیم)</h3>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-4 gap-3 items-end mb-4">
                        <div>
                            <label class="block text-[11px] font-bold text-gray-600 mb-1">نام برند</label>
                            <input type="text" name="brand" value="VPNet" class="w-full border-2 border-gray-200 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-white text-sm" dir="ltr">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-600 mb-1">نام طرح</label>
                            <input type="text" name="plan" value="Silver" class="w-full border-2 border-gray-200 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-white text-sm" dir="ltr">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-600 mb-1">شروع از شماره</label>
                            <input type="number" name="start_num" min="1" value="1" class="w-full border-2 border-gray-200 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-white text-sm" dir="ltr">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-600 mb-1">تا شماره</label>
                            <input type="number" name="end_num" min="1" value="5" class="w-full border-2 border-gray-200 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-white text-sm" dir="ltr">
                        </div>
                        <div class="sm:col-span-4 mt-2">
                            <label class="block text-[11px] font-bold text-gray-600 mb-1">محل قرارگیری شماره</label>
                            <select name="position" class="w-full border-2 border-gray-200 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-white text-sm">
                                <option value="end">در انتها (پیش‌فرض)</option>
                                <option value="after_brand">بعد از برند</option>
                                <option value="after_plan">بعد از طرح</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl transition shadow text-sm mt-2">🚀 اتصال به سرور و ساخت اکانت‌ها</button>
                </div>
            </form>

            <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($successCount)): ?>
            <div class="mt-8 border-t border-gray-200 pt-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-black text-gray-800 flex items-center gap-2">
                        ✅ خروجی استاندارد برای پنل انبار
                    </h3>
                    <div class="flex gap-3 text-sm font-bold">
                        <span class="text-emerald-600 bg-emerald-50 px-3 py-1 rounded-lg">موفق: <?php echo $successCount; ?></span>
                        <?php if($failCount > 0): ?>
                            <span class="text-rose-600 bg-rose-50 px-3 py-1 rounded-lg">خطا: <?php echo $failCount; ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($successCount > 0): ?>
                <div class="relative">
                    <textarea id="bulkOutput" rows="10" readonly class="w-full border-2 border-emerald-200 bg-emerald-50/20 p-4 rounded-xl outline-none font-mono text-xs text-left leading-relaxed text-gray-700" dir="ltr"><?php echo htmlspecialchars(trim($bulkOutputText)); ?></textarea>
                    
                    <button onclick="copyBulkData()" id="copyBtn" class="absolute top-4 right-4 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold px-4 py-2 rounded-lg shadow transition flex items-center gap-1">
                        📋 کپی یکجا
                    </button>
                </div>
                <p class="text-[10px] text-gray-500 mt-2 font-bold">این متن را کپی کرده و مستقیماً در بخش «ایمپورت گروهی» پنل انبار قرار دهید.</p>
                <?php endif; ?>

                <?php if (!empty($results)): ?>
                    <div class="mt-6 space-y-2">
                        <h4 class="font-bold text-rose-700 text-xs mb-2">لیست اکانت‌های ناموفق:</h4>
                        <?php foreach($results as $err): ?>
                            <div class="bg-rose-50 border border-rose-200 p-2 rounded-lg text-xs font-mono text-left" dir="ltr">
                                <span class="font-bold text-rose-800"><?php echo htmlspecialchars($err['username']); ?></span> : 
                                <span class="text-rose-600"><?php echo htmlspecialchars($err['error']); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

        </div>
    </div>
</div>

<script>
    function copyBulkData() {
        const textarea = document.getElementById("bulkOutput");
        const btn = document.getElementById("copyBtn");
        
        textarea.select();
        textarea.setSelectionRange(0, 99999); /* For mobile devices */
        
        navigator.clipboard.writeText(textarea.value).then(() => {
            const originalHTML = btn.innerHTML;
            btn.innerHTML = '✅ کپی شد!';
            btn.classList.replace('bg-emerald-600', 'bg-green-600');
            btn.classList.replace('hover:bg-emerald-700', 'hover:bg-green-700');
            
            setTimeout(() => {
                btn.innerHTML = originalHTML;
                btn.classList.replace('bg-green-600', 'bg-emerald-600');
                btn.classList.replace('hover:bg-green-700', 'hover:bg-emerald-700');
            }, 2000);
        });
    }
</script>

</body>
</html>