<?php
// modules/pasarguard/widgets/psg_create.php

// اصلاح مسیر برای زمانی که فایل مستقیماً توسط AJAX فراخوانی می‌شود
require_once __DIR__ . '/../pasarguard_api.php';

global $pdo;

// ==============================================================
// پردازش درخواست‌های AJAX (تک‌تک برای هر یوزر جهت Progress Bar)
// ==============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'ajax_create_single_user') {
    header('Content-Type: application/json');
    
    $serverId = $_POST['server_id'] ?? null;
    if (!$serverId) { 
        echo json_encode(['status' => 'error', 'message' => 'سرور مقصد مشخص نشده است.']); 
        exit; 
    }

    // دریافت توکن و آدرس سرور
    $tokenRaw = getPsgApiToken($serverId);
    if (!$tokenRaw || !is_array($tokenRaw) || empty($tokenRaw['token'])) {
        echo json_encode(['status' => 'error', 'message' => 'احراز هویت سرور شکست خورد.']); 
        exit;
    }
    
    $apiToken = $tokenRaw['token'];
    $serverUrl = $tokenRaw['server_url'] ?? '';

    // جمع‌آوری اطلاعات کاربر
    $username = trim($_POST['username'] ?? '');
    $status = $_POST['status'] ?? 'active';
    $note = trim($_POST['note'] ?? '');
    $resetStrategy = $_POST['reset_strategy'] ?? 'no_reset';
    
    // دریافت مقدار حجم و واحد (پشتیبانی از MB و GB)
    $limitVal = (float)($_POST['data_limit_val'] ?? 0);
    $limitUnit = $_POST['data_limit_unit'] ?? 'GB';
    
    $dataLimitBytes = 0;
    if ($limitVal > 0) {
        $dataLimitBytes = ($limitUnit === 'MB') ? (int)($limitVal * pow(1024, 2)) : (int)($limitVal * pow(1024, 3));
    }
    
    $expireVal = !empty($_POST['expire_date']) ? date('Y-m-d\TH:i:sP', strtotime(trim($_POST['expire_date']))) : null;
    
    // بازسازی آرایه پروتکل‌ها
    $builtProxies = [];
    $postedProxies = $_POST['proxies'] ?? [];
    if (!is_array($postedProxies)) $postedProxies = [$postedProxies];
    foreach($postedProxies as $proto) {
        $builtProxies[$proto] = ($proto === 'shadowsocks') ? ["method" => "chacha20-ietf-poly1305"] : new stdClass();
    }
    if (empty($builtProxies)) $builtProxies['vless'] = new stdClass();

    $groupIds = isset($_POST['group_ids']) ? array_map('intval', $_POST['group_ids']) : [];
    $inventoryPlanName = trim($_POST['inventory_plan_name'] ?? '');

    $payload = [
        "username" => $username, 
        "status" => $status, 
        "data_limit" => $dataLimitBytes, 
        "data_limit_reset_strategy" => $resetStrategy,
        "expire" => $expireVal,
        "note" => $note, 
        "group_ids" => $groupIds, 
        "proxies" => $builtProxies,
        "inbounds" => [],
        "next_plan" => null
    ];

    // ارسال به API اصلی پاسارگارد
    $res = executePsgApiCall($serverUrl, "/api/user", "POST", $payload, $apiToken);
    
    if ($res['code'] === 200 || $res['code'] === 201) {
        $link = $res['data']['subscription_url'] ?? '-';
        $dbInserted = false;

        // ثبت خودکار در انبار پنل VPNet (ذخیره مقدار خام حجم و واحد آن در دیتابیس انبار)
        if (!empty($inventoryPlanName) && $limitVal > 0 && $link !== '-' && isset($pdo)) {
            try {
                $stmtCheck = $pdo->prepare("SELECT id FROM inventory WHERE config_link = ? OR account_username = ?");
                $stmtCheck->execute([$link, $username]);
                if ($stmtCheck->rowCount() == 0) {
                    $stmtInsert = $pdo->prepare("INSERT INTO inventory (plan_name, server_id, volume, volume_unit, account_username, config_link, status) VALUES (?, ?, ?, ?, ?, ?, 'available')");
                    $stmtInsert->execute([$inventoryPlanName, $serverId, $limitVal, $limitUnit, $username, $link]);
                    $dbInserted = true;
                }
            } catch(Exception $e) {}
        }
        
        echo json_encode(['status' => 'success', 'username' => $username, 'link' => $link, 'db_inserted' => $dbInserted]);
    } else {
        $errDetail = isset($res['data']['detail']) ? (is_array($res['data']['detail']) ? json_encode($res['data']['detail']) : $res['data']['detail']) : 'خطای ارتباط با سرور پاسارگارد (احتمالاً Timeout یا قطعی موقت)';
        echo json_encode(['status' => 'error', 'username' => $username, 'message' => $errDetail, 'api_code' => $res['code']]);
    }
    exit;
}

// ==============================================================
// بارگذاری واسط کاربری (UI)
// ==============================================================

// دریافت لیست طرح‌ها و سرورها از دیتابیس انبار
$plansList = [];
$serversList = [];
try {
    if (isset($pdo)) {
        $plansList = $pdo->query("SELECT * FROM plans ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
        $serversList = $pdo->query("SELECT * FROM servers ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {}
?>

<div id="progressOverlay" class="fixed inset-0 bg-slate-900/80 backdrop-blur-sm z-[200] hidden flex-col items-center justify-center p-4 transition-opacity">
    <div class="bg-white dark:bg-slate-800 rounded-3xl p-8 max-w-md w-full shadow-2xl text-center relative overflow-hidden">
        <div class="absolute top-0 left-0 w-full h-1.5 bg-gray-100 dark:bg-slate-700">
            <div id="progressBarTop" class="h-full bg-blue-500 transition-all duration-300" style="width: 0%"></div>
        </div>
        <div class="w-20 h-20 bg-blue-50 dark:bg-blue-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-10 h-10 text-blue-600 dark:text-blue-400 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 002-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
        </div>
        <h3 class="text-xl font-black text-gray-800 dark:text-white mb-2">در حال ساخت اکانت‌ها...</h3>
        <p id="progressText" class="text-sm font-bold text-gray-500 dark:text-gray-400 mb-8">لطفاً این صفحه را نبندید.</p>
        
        <div class="w-full bg-gray-100 dark:bg-slate-700 rounded-full h-4 mb-3 overflow-hidden border border-gray-200 dark:border-slate-600 shadow-inner">
            <div id="progressBar" class="bg-gradient-to-r from-blue-500 to-indigo-600 h-full rounded-full transition-all duration-300 relative" style="width: 0%">
                <div class="absolute inset-0 bg-white/20 animate-pulse"></div>
            </div>
        </div>
        <div class="flex justify-between items-center text-sm font-black text-gray-600 dark:text-gray-300 px-1">
            <span id="progressPercent" class="text-blue-600 dark:text-blue-400">0%</span>
            <span id="progressCount" class="font-mono">0 / 0</span>
        </div>

        <div id="retryContainer" class="hidden mt-6 border-t border-gray-200 dark:border-slate-700 pt-5">
            <div class="bg-rose-50 dark:bg-rose-900/30 border border-rose-200 dark:border-rose-800 text-rose-700 dark:text-rose-400 p-4 rounded-xl text-sm font-bold mb-4">
                ⚠️ ارتباط با سرور <span id="retryServerName" class="text-rose-900 dark:text-rose-200 font-black"></span> برای اکانت <span id="retryUsername" class="text-rose-900 dark:text-rose-200 font-black font-mono" dir="ltr"></span> برقرار نشد!
            </div>
            <div class="flex flex-col sm:flex-row gap-2">
                <button id="btnRetryYes" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-xl text-xs font-bold transition">🔄 تلاش مجدد</button>
                <button id="btnRetryNo" class="flex-1 bg-gray-200 hover:bg-gray-300 dark:bg-slate-700 dark:hover:bg-slate-600 text-gray-800 dark:text-gray-200 py-2 rounded-xl text-xs font-bold transition">⏭️ رد شدن</button>
                <button id="btnRetryCancelAll" class="flex-1 bg-rose-600 hover:bg-rose-700 text-white py-2 rounded-xl text-xs font-bold transition">⏹️ لغو کار</button>
            </div>
        </div>
    </div>
</div>

<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden border-t-8 border-t-blue-600 mb-10">
    <div class="bg-gray-50 dark:bg-slate-700/50 border-b border-gray-100 dark:border-slate-600 p-6 flex justify-between items-center">
        <h2 class="text-lg font-black text-blue-800 dark:text-blue-400 flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
            سیستم پیشرفته ایجاد کاربر (متصل به انبار)
        </h2>
    </div>

    <div class="p-6 md:p-8">
        <form id="advancedCreateForm" class="block">
            
            <div class="mb-6 bg-blue-50 dark:bg-blue-900/20 p-5 rounded-2xl border border-blue-200 dark:border-blue-800/50" dir="rtl">
                <label class="block text-sm font-black text-blue-800 dark:text-blue-300 mb-2">سرور مقصد (Server)</label>
                <select name="server_id" id="target_server_id" required class="w-full border-2 border-blue-200 dark:border-blue-700 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-800 dark:text-white text-sm font-bold shadow-sm transition" onchange="onServerChange()">
                    <?php if(empty($serversList)): ?>
                        <option value="" disabled selected>هیچ سروری تعریف نشده است! ابتدا از مدیریت پنل‌ها سرور اضافه کنید.</option>
                    <?php else: ?>
                        <?php foreach($serversList as $index => $srv): ?>
                            <option value="<?php echo $srv['id']; ?>" <?php echo $index === 0 ? 'selected' : ''; ?>><?php echo htmlspecialchars($srv['name']); ?> (<?php echo htmlspecialchars($srv['url']); ?>)</option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <p class="text-[10px] text-blue-600 dark:text-blue-400 mt-2">محصولات تولید شده روی این سرور ساخته می‌شوند.</p>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-8 mb-8 border border-gray-200 dark:border-slate-700 rounded-2xl p-6 bg-white dark:bg-slate-800 shadow-sm" dir="rtl">
                
                <div class="md:col-span-2 space-y-6">
                    <h3 class="text-sm font-black text-gray-800 dark:text-slate-100 border-b border-gray-100 dark:border-slate-700 pb-3">۱. تنظیمات و ویژگی‌های اکانت</h3>
                    
                    <div class="grid grid-cols-2 gap-5">
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">وضعیت اکانت (Status)</label>
                            <select name="status" id="create_status" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 dark:text-white text-sm font-bold shadow-sm transition">
                                <option value="active">فعال (Active)</option>
                                <option value="disabled">مسدود (Disabled)</option>
                                <option value="on_hold">در انتظار (On Hold)</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">سقف حجم (Data Limit)</label>
                            <div class="flex" dir="ltr">
                                <select id="create_limit_unit" name="data_limit_unit" class="border border-r-0 border-gray-200 dark:border-slate-600 p-3 rounded-l-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-600 dark:text-white text-sm font-bold cursor-pointer transition shadow-sm" onchange="autoDetectNextNumber()">
                                    <option value="GB">GB</option>
                                    <option value="MB">MB</option>
                                </select>
                                <input type="number" id="create_limit_val" name="data_limit_val" step="0.1" min="0" required class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-r-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 dark:text-white text-sm font-bold font-mono shadow-sm transition" placeholder="برای ثبت انبار اجباری است" dir="ltr" oninput="autoDetectNextNumber()">
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-5">
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">ریست دوره‌ای (Periodic Reset)</label>
                            <select name="reset_strategy" id="create_reset" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 dark:text-white text-sm font-bold shadow-sm transition">
                                <option value="no_reset">بدون ریست</option>
                                <option value="day">روزانه</option>
                                <option value="week">هفتگی</option>
                                <option value="month">ماهانه</option>
                                <option value="year">سالانه</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">تاریخ انقضا (Expiry Date)</label>
                            <div class="flex gap-2">
                                <input type="datetime-local" id="create_expire_val" name="expire_date" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 dark:text-white text-[12px] font-bold font-mono shadow-sm transition" dir="ltr">
                                <button type="button" onclick="$('#create_expire_val').val('')" class="bg-rose-50 text-rose-600 dark:bg-rose-900/30 px-3 rounded-xl text-[10px] font-bold border border-rose-200 dark:border-rose-800 transition hover:bg-rose-100" title="پاک کردن تاریخ">Clear</button>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">یادداشت (Note)</label>
                        <input type="text" name="note" id="create_note" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 dark:text-white text-sm shadow-sm transition" placeholder="یادداشت اختیاری برای اکانت‌ها...">
                    </div>

                    <div class="border border-gray-200 dark:border-slate-600 rounded-xl shadow-sm overflow-hidden">
                        <div class="px-5 py-3 bg-gray-50 dark:bg-slate-700/50 border-b border-gray-200 dark:border-slate-600">
                            <span class="text-xs font-bold text-gray-700 dark:text-gray-200 flex items-center gap-2" dir="rtl">🔒 تنظیمات پروتکل‌ها (Proxies)</span>
                        </div>
                        <div class="p-5 flex flex-wrap gap-4 bg-white dark:bg-slate-800" dir="ltr">
                            <label class="flex items-center gap-2 cursor-pointer border border-gray-200 dark:border-slate-600 bg-gray-50 dark:bg-slate-700 px-4 py-2 rounded-lg hover:border-blue-300 transition">
                                <input type="checkbox" name="proxies[]" value="vless" checked class="w-4 h-4 text-blue-600 rounded border-gray-300"> <span class="text-xs font-bold font-mono text-gray-700 dark:text-gray-300">VLESS</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer border border-gray-200 dark:border-slate-600 bg-gray-50 dark:bg-slate-700 px-4 py-2 rounded-lg hover:border-blue-300 transition">
                                <input type="checkbox" name="proxies[]" value="vmess" checked class="w-4 h-4 text-blue-600 rounded border-gray-300"> <span class="text-xs font-bold font-mono text-gray-700 dark:text-gray-300">VMESS</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer border border-gray-200 dark:border-slate-600 bg-gray-50 dark:bg-slate-700 px-4 py-2 rounded-lg hover:border-blue-300 transition">
                                <input type="checkbox" name="proxies[]" value="trojan" checked class="w-4 h-4 text-blue-600 rounded border-gray-300"> <span class="text-xs font-bold font-mono text-gray-700 dark:text-gray-300">TROJAN</span>
                            </label>
                            <label class="flex items-center gap-2 cursor-pointer border border-gray-200 dark:border-slate-600 bg-gray-50 dark:bg-slate-700 px-4 py-2 rounded-lg hover:border-blue-300 transition">
                                <input type="checkbox" name="proxies[]" value="shadowsocks" checked class="w-4 h-4 text-blue-600 rounded border-gray-300"> <span class="text-xs font-bold font-mono text-gray-700 dark:text-gray-300">SHADOWSOCKS</span>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="md:col-span-1 border-r md:border-r-0 md:border-l border-gray-200 dark:border-slate-700 md:pr-6 pr-0 h-full flex flex-col">
                    <div class="flex border-b border-gray-200 dark:border-slate-700 mb-4" dir="ltr">
                        <button type="button" class="flex-1 pb-3 text-sm font-bold text-[#3b5998] border-b-2 border-[#3b5998]">Groups</button>
                    </div>
                    <div class="flex-1 overflow-y-auto tiny-scrollbar pl-2 space-y-1" id="create_groups_list" dir="ltr" style="max-height: 400px;"></div>
                </div>
            </div>

            <div class="bg-blue-50/50 dark:bg-blue-900/10 p-6 rounded-2xl border border-blue-100 dark:border-blue-800/50 mb-8 relative">
                <h3 class="text-sm font-black text-blue-800 dark:text-blue-400 mb-5">۲. تولید هوشمند نام کاربری و ادغام با انبار</h3>
                
                <div class="absolute top-6 left-6 bg-white dark:bg-slate-800 border border-blue-200 dark:border-blue-700 font-bold text-xs px-4 py-2 rounded-xl shadow-sm text-blue-700 dark:text-blue-300 flex items-center gap-2">
                    تعداد: <span id="live_gen_count" class="font-black font-mono text-base">0</span>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4 items-end">
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">طرح انبار (ثبت خودکار)</label>
                        <select name="inventory_plan_name" id="gen_db_plan" required onchange="syncPlanName()" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm font-bold">
                            <option value="" disabled selected>-- انتخاب کنید --</option>
                            <?php foreach($plansList as $p): ?>
                                <option value="<?php echo htmlspecialchars($p['plan_name']); ?>" data-en="<?php echo htmlspecialchars($p['plan_name_en'] ?? ''); ?>"><?php echo htmlspecialchars($p['plan_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">نام برند</label>
                        <input type="text" id="gen_brand" value="VPNet" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm" dir="ltr" oninput="autoDetectNextNumber()">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">نام انگلیسی طرح</label>
                        <input type="text" id="gen_plan" placeholder="مثال: gold" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm" dir="ltr" oninput="autoDetectNextNumber()">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5 flex justify-between items-center">
                            <span>شروع از شماره</span>
                            <button type="button" onclick="autoDetectNextNumber()" class="text-[9px] text-blue-600 dark:text-blue-400 hover:text-blue-800 transition flex items-center gap-1 bg-blue-50 dark:bg-blue-900/30 px-1.5 py-0.5 rounded">
                                تشخیص هوشمند
                            </button>
                        </label>
                        <div class="relative">
                            <input type="number" id="gen_start" min="1" value="1" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm transition" dir="ltr" oninput="updateLiveCount()">
                            <div id="detect_loading" class="absolute left-3 top-3 hidden">
                                <div class="animate-spin h-5 w-5 border-2 border-blue-500 border-t-transparent rounded-full"></div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">تا شماره (پایان)</label>
                        <input type="number" id="gen_end" min="1" value="1" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm" dir="ltr" oninput="updateLiveCount()">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">محل قرارگیری شماره</label>
                        <select id="gen_position" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-blue-500 bg-white dark:bg-slate-700 dark:text-white text-sm shadow-sm" onchange="autoDetectNextNumber()">
                            <option value="end">در انتها (پیش‌فرض)</option>
                            <option value="after_brand">بعد از برند</option>
                            <option value="after_plan">بعد از طرح</option>
                        </select>
                    </div>
                </div>

                <button type="button" onclick="generateUserList()" class="mt-6 w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-md text-sm flex justify-center items-center gap-2">
                    تولید و پیش‌نمایش لیست نام‌های کاربری
                </button>
            </div>

            <div id="preview_section" class="hidden">
                <h3 class="text-sm font-black text-gray-800 dark:text-white mb-4">۳. تایید و ارسال به سرور و انبار</h3>
                <div id="generated_users_container" class="space-y-3 mb-8 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar border border-gray-100 dark:border-slate-700 rounded-xl p-4 bg-gray-50 dark:bg-slate-800/30">
                </div>
                
                <button type="button" onclick="startBulkCreation()" id="btn_submit_final" class="w-full bg-[#3b5998] hover:bg-blue-800 text-white font-black py-4 rounded-xl transition shadow-[0_4px_20px_rgba(59,89,152,0.4)] text-lg flex items-center justify-center gap-3">
                    ثبت نهایی در سرور مقصد و افزودن به انبار محصولات
                </button>
            </div>
            
            <div id="final_result_container"></div>
        </form>
    </div>
</div>

<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script>
    function getSelectedServerId() {
        return document.getElementById('target_server_id').value;
    }

    function onServerChange() {
        loadPsgGroupsForCreate();
        setTimeout(autoDetectNextNumber, 200);
    }

    function autoDetectNextNumber() {
        let sId = getSelectedServerId();
        if(!sId) return;

        const brand = document.getElementById('gen_brand').value.trim();
        const plan = document.getElementById('gen_plan').value.trim();
        const limitInput = document.getElementById('create_limit_val').value.trim();
        const limitUnit = document.getElementById('create_limit_unit').value;
        const pos = document.getElementById('gen_position').value;

        if (!brand || !plan || !limitInput) return;

        const volumeStr = limitInput + limitUnit;
        let prefix = "";
        
        if (pos === 'after_brand') { 
            prefix = `${brand}-`.toLowerCase(); 
        } else if (pos === 'after_plan') { 
            prefix = `${brand}-${plan}-`.toLowerCase(); 
        } else { 
            prefix = `${brand}-${plan}-${volumeStr}-`.toLowerCase(); 
        }

        $('#detect_loading').removeClass('hidden');
        $('#gen_start').addClass('opacity-50 pointer-events-none');

        $.ajax({
            url: 'pasarguard_api.php?ajax_call=users_list&server_id=' + sId,
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                let usersList = Array.isArray(res) ? res : (res.users || []);
                let maxNumber = 0;

                usersList.forEach(user => {
                    let uname = user.username.toLowerCase();
                    
                    if (pos === 'end' && uname.startsWith(prefix)) {
                        let parts = uname.split('-');
                        let num = parseInt(parts[parts.length - 1]);
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    } 
                    else if (pos === 'after_brand' && uname.startsWith(prefix) && uname.endsWith(`-${plan}-${volumeStr}`.toLowerCase())) {
                        let parts = uname.split('-');
                        let num = parseInt(parts[1]); 
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    } 
                    else if (pos === 'after_plan' && uname.startsWith(prefix) && uname.endsWith(`-${volumeStr}`.toLowerCase())) {
                        let parts = uname.split('-');
                        let num = parseInt(parts[2]);
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    }
                });

                document.getElementById('gen_start').value = maxNumber + 1;
                document.getElementById('gen_end').value = maxNumber + 1; 
                updateLiveCount();
            },
            error: function() { console.error("Auto detect failed."); },
            complete: function() {
                $('#detect_loading').addClass('hidden');
                $('#gen_start').removeClass('opacity-50 pointer-events-none');
            }
        });
    }

    function syncPlanName() {
        const sel = document.getElementById('gen_db_plan');
        if(sel.selectedIndex > 0) {
            document.getElementById('gen_plan').value = sel.options[sel.selectedIndex].getAttribute('data-en') || '';
            setTimeout(autoDetectNextNumber, 200);
        }
    }

    function loadPsgGroupsForCreate() {
        let sId = getSelectedServerId();
        if(!sId) {
            $('#create_groups_list').html('<div class="text-center text-xs text-amber-500 font-bold mt-5">ابتدا سرور مقصد را انتخاب کنید</div>');
            return;
        }

        $('#create_groups_list').html('<div class="text-center text-xs text-gray-400 mt-10 animate-pulse">در حال دریافت گروه‌ها از سرور...</div>');

        $.ajax({
            url: 'pasarguard_api.php?ajax_call=groups&server_id=' + sId,
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                let listContainer = $('#create_groups_list');
                let groupsList = Array.isArray(res) ? res : (res.groups || res.data || []);
                
                if (groupsList.length > 0) {
                    let html = '';
                    groupsList.forEach(g => {
                        let gId = g.id !== undefined ? g.id : (g.value || '');
                        let gName = g.name || g.title || `Group ${gId}`;
                        let checked = ''; 
                        html += `<label class="flex items-center gap-3 p-2 hover:bg-gray-50 dark:hover:bg-slate-700/50 cursor-pointer rounded-xl transition border border-transparent hover:border-gray-200 dark:hover:border-slate-600">
                                    <input type="checkbox" name="group_ids[]" value="${gId}" ${checked} class="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"> 
                                    <span class="text-sm font-bold text-gray-700 dark:text-gray-300">${gName}</span>
                                 </label>`;
                    });
                    listContainer.html(html);
                } else {
                    listContainer.html('<div class="text-center text-xs text-rose-500 font-bold mt-5">هیچ گروهی یافت نشد!</div>');
                }
            },
            error: function() {
                $('#create_groups_list').html('<div class="text-center text-xs text-rose-500 font-bold mt-5">خطا در اتصال به API</div>');
            }
        });
    }

    function updateLiveCount() {
        const start = parseInt(document.getElementById('gen_start').value) || 0;
        const end = parseInt(document.getElementById('gen_end').value) || 0;
        const count = (start > 0 && end >= start) ? (end - start) + 1 : 0;
        document.getElementById('live_gen_count').innerText = count;
    }

    function generateUserList() {
        const dbPlan = document.getElementById('gen_db_plan').value;
        const limitInput = document.getElementById('create_limit_val').value.trim();
        const limitUnit = document.getElementById('create_limit_unit').value;

        if(!dbPlan) {
            alert('لطفاً «طرح انبار» را انتخاب کنید تا پس از ساخت، اکانت‌ها مستقیماً به انبار محصولات اضافه شوند.');
            return;
        }
        if(!limitInput || limitInput <= 0) {
            alert('لطفاً در بخش اول (تنظیمات اکانت) سقف حجم را وارد کنید. این مقدار برای ساخت یوزرنیم و ثبت در انبار اجباری است.');
            return;
        }

        const brand = document.getElementById('gen_brand').value.trim();
        const plan = document.getElementById('gen_plan').value.trim();
        let volumeStr = limitInput + limitUnit; 

        const start = parseInt(document.getElementById('gen_start').value);
        const end = parseInt(document.getElementById('gen_end').value);
        const pos = document.getElementById('gen_position').value;

        if(isNaN(start) || isNaN(end) || end < start) { 
            alert('اعداد وارد شده برای شروع و پایان نامعتبر است.'); 
            return; 
        }

        const container = document.getElementById('generated_users_container');
        container.innerHTML = ''; 
        
        for(let i = 0; i <= (end - start); i++) {
            const num = start + i;
            let parts = [];
            
            if (pos === 'after_brand') {
                if(brand) parts.push(`${brand}-${num}`); else parts.push(num);
                if(plan) parts.push(plan);
                if(volumeStr) parts.push(volumeStr);
            } else if (pos === 'after_plan') {
                if(brand) parts.push(brand);
                if(plan) parts.push(`${plan}-${num}`); else parts.push(num);
                if(volumeStr) parts.push(volumeStr);
            } else { 
                if(brand) parts.push(brand);
                if(plan) parts.push(plan);
                if(volumeStr) parts.push(volumeStr);
                parts.push(num);
            }
            
            let u = parts.join('-').replace(/-+/g, '-').replace(/^-|-$/g, '');

            container.insertAdjacentHTML('beforeend', `
                <div class="flex items-center gap-3 bg-white dark:bg-slate-800 p-3 rounded-xl border border-gray-200 dark:border-slate-600 shadow-sm gen-row transition hover:border-blue-300 dark:hover:border-blue-500">
                    <div class="flex-1">
                        <input type="text" name="username[]" value="${u}" required class="w-full bg-transparent outline-none font-mono text-sm font-bold text-gray-800 dark:text-blue-300 border-b border-dashed border-gray-300 dark:border-slate-600 pb-1 focus:border-blue-500 transition" dir="ltr">
                    </div>
                    <button type="button" onclick="this.closest('.gen-row').remove();" class="p-2 text-rose-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-900/30 rounded-lg transition" title="حذف این کاربر">
                        ❌
                    </button>
                </div>`);
        }
        
        $('#preview_section').slideDown();
        $('#final_result_container').html(''); // پاک کردن نتایج قبلی در صورت وجود
    }

    function askUserToRetry(serverName, username) {
        return new Promise((resolve) => {
            $('#retryServerName').text(serverName);
            $('#retryUsername').text(username);
            $('#retryContainer').removeClass('hidden').hide().slideDown(300);

            $('#btnRetryYes').off('click').on('click', function() {
                $('#retryContainer').slideUp(300, () => $(this).addClass('hidden'));
                resolve('retry');
            });
            $('#btnRetryNo').off('click').on('click', function() {
                $('#retryContainer').slideUp(300, () => $(this).addClass('hidden'));
                resolve('skip');
            });
            $('#btnRetryCancelAll').off('click').on('click', function() {
                $('#retryContainer').slideUp(300, () => $(this).addClass('hidden'));
                resolve('abort');
            });
        });
    }

    async function startBulkCreation() {
        let usernames = [];
        $('input[name="username[]"]').each(function() {
            if($(this).val().trim() !== '') usernames.push($(this).val().trim());
        });
        
        if(usernames.length === 0) {
            alert('هیچ یوزرنیمی برای ساخت وجود ندارد.');
            return false;
        }

        let server_id = $('#target_server_id').val();
        let serverName = $("#target_server_id option:selected").text();
        let status = $('#create_status').val();
        let data_limit_val = $('#create_limit_val').val();
        let data_limit_unit = $('#create_limit_unit').val();
        let reset_strategy = $('#create_reset').val();
        let expire_date = $('#create_expire_val').val();
        let note = $('#create_note').val();
        let inventory_plan_name = $('#gen_db_plan').val();
        
        let proxies = [];
        $('input[name="proxies[]"]:checked').each(function() { proxies.push($(this).val()); });
        
        let group_ids = [];
        $('input[name="group_ids[]"]:checked').each(function() { group_ids.push($(this).val()); });

        $('#progressOverlay').removeClass('hidden').addClass('flex');
        $('#progressCount').text(`0 / ${usernames.length}`);
        $('#progressBar, #progressBarTop').css('width', '0%');
        $('#progressPercent').text('0%');

        let successCount = 0;
        let failCount = 0;
        let dbInsertCount = 0;
        let bulkOutputText = "";
        let actionResults = [];
        let abortAll = false;

        const ajaxUrl = window.location.pathname.includes('/inventory/') 
            ? '../pasarguard/widgets/psg_create.php' 
            : '/vpnet-panel/modules/pasarguard/widgets/psg_create.php';

        for(let i = 0; i < usernames.length; i++) {
            if (abortAll) break;

            let uname = usernames[i];
            $('#progressText').html(`در حال ساخت: <span class="text-blue-600 font-mono text-lg ml-2" dir="ltr">${uname}</span>`);
            
            let successForThisUser = false;
            let attempt = 0;
            let maxAutoRetries = 2;

            while (!successForThisUser && !abortAll) {
                try {
                    let response = await $.ajax({
                        url: ajaxUrl,
                        type: 'POST',
                        dataType: 'json',
                        timeout: 25000, 
                        data: {
                            action: 'ajax_create_single_user',
                            server_id: server_id,
                            status: status,
                            data_limit_val: data_limit_val,
                            data_limit_unit: data_limit_unit,
                            reset_strategy: reset_strategy,
                            expire_date: expire_date,
                            note: note,
                            inventory_plan_name: inventory_plan_name,
                            proxies: proxies,
                            group_ids: group_ids,
                            username: uname
                        }
                    });

                    if(response.status === 'success') {
                        successCount++;
                        if(response.db_inserted) dbInsertCount++;
                        bulkOutputText += `${response.username},${response.link}\n`;
                        successForThisUser = true; 
                    } else {
                        if (response.api_code && response.api_code >= 400 && response.api_code < 500 && response.api_code !== 429 && response.api_code !== 408) {
                            failCount++;
                            actionResults.push({username: uname, error: response.message});
                            break; 
                        } else {
                            throw new Error(response.message || "Network Error");
                        }
                    }
                } catch (err) {
                    attempt++;
                    if (attempt > maxAutoRetries) {
                        let userChoice = await askUserToRetry(serverName, uname);
                        
                        if (userChoice === 'retry') {
                            attempt = 0; 
                            $('#progressText').html(`در حال تلاش مجدد برای: <span class="text-amber-500 font-mono text-lg ml-2" dir="ltr">${uname}</span>`);
                        } else if (userChoice === 'skip') {
                            failCount++;
                            let errorText = (err.status === 404) ? "فایل پردازشگر پیدا نشد" : "انصراف پس از قطعی ارتباط";
                            actionResults.push({username: uname, error: err.message || errorText});
                            break; 
                        } else if (userChoice === 'abort') {
                            abortAll = true; 
                            actionResults.push({username: uname, error: "لغو کامل عملیات به دستور مدیر"});
                            break;
                        }
                    } else {
                        $('#progressText').html(`ارتباط قطع شد! تلاش مجدد (${attempt}/${maxAutoRetries}): <span class="text-amber-500 font-mono text-lg ml-2" dir="ltr">${uname}</span>`);
                        await new Promise(r => setTimeout(r, 4000));
                    }
                }
            }

            let percent = Math.round(((i + 1) / usernames.length) * 100);
            $('#progressBar, #progressBarTop').css('width', percent + '%');
            $('#progressPercent').text(percent + '%');
            $('#progressCount').text(`${i + 1} / ${usernames.length}`);
        }

        setTimeout(() => {
            $('#progressOverlay').addClass('hidden').removeClass('flex');
            renderFinalReport(successCount, failCount, dbInsertCount, bulkOutputText, actionResults);
        }, 800);
    }

    function renderFinalReport(successCount, failCount, dbInsertCount, bulkOutputText, actionResults) {
        let html = `
        <div class="mt-10 border-t-2 border-dashed border-gray-200 dark:border-slate-700 pt-8" id="final_result_box">
            <div class="flex justify-between items-center mb-6">
                <h3 class="font-black text-gray-800 dark:text-white text-lg flex items-center gap-2">
                    ✅ گزارش عملیات و ثبت در انبار
                </h3>
                <div class="flex gap-3 text-sm font-bold">
                    <span class="text-blue-700 bg-blue-100 dark:bg-blue-900/50 dark:text-blue-300 px-4 py-1.5 rounded-lg shadow-sm">ورود به انبار: ${dbInsertCount}</span>
                    <span class="text-emerald-700 bg-emerald-100 dark:bg-emerald-900/50 dark:text-emerald-300 px-4 py-1.5 rounded-lg shadow-sm">ساخت موفق: ${successCount}</span>
                    ${failCount > 0 ? `<span class="text-rose-700 bg-rose-100 dark:bg-rose-900/50 dark:text-rose-300 px-4 py-1.5 rounded-lg shadow-sm">خطا: ${failCount}</span>` : ''}
                </div>
            </div>
        `;

        if (successCount > 0) {
            html += `
            <div class="relative">
                <textarea id="bulkOutput" rows="8" readonly class="w-full border-2 border-emerald-300 dark:border-emerald-700/50 bg-emerald-50 dark:bg-slate-900 p-5 rounded-2xl outline-none font-mono text-sm text-left leading-relaxed text-gray-800 dark:text-gray-200 custom-scrollbar shadow-inner" dir="ltr">${bulkOutputText.trim()}</textarea>
                <button type="button" onclick="copyBulkData()" id="copyBtn" class="absolute bottom-4 right-4 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold px-5 py-2.5 rounded-xl shadow-md transition flex items-center gap-2">
                    کپی لیست اکانت‌ها
                </button>
            </div>
            `;
        }

        if (actionResults.length > 0) {
            html += `
            <div class="mt-8 space-y-3">
                <h4 class="font-bold text-rose-700 dark:text-rose-400 text-sm mb-3 border-b border-rose-100 dark:border-rose-900/50 pb-2">گزارش خطاهای ساخت:</h4>
            `;
            actionResults.forEach(err => {
                html += `
                <div class="bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800/50 p-4 rounded-xl text-sm font-mono text-left flex items-start gap-3" dir="ltr">
                    <span class="font-black text-rose-800 dark:text-rose-300 min-w-[150px]">${err.username}</span>
                    <span class="text-rose-600 dark:text-rose-400 border-l border-rose-200 dark:border-rose-800/50 pl-3">${err.error}</span>
                </div>
                `;
            });
            html += `</div>`;
        }

        html += `</div>`;

        $('#final_result_container').html(html);
        $('#preview_section').slideUp();
    }

    function copyBulkData() {
        const textarea = document.getElementById("bulkOutput");
        const btn = document.getElementById("copyBtn");
        textarea.select();
        textarea.setSelectionRange(0, 99999); 
        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);
        });
    }

    $(document).ready(function() {
        if(document.getElementById('target_server_id') && document.getElementById('target_server_id').value !== '') {
            onServerChange();
        }
        updateLiveCount();
        
        $('#create_limit_val').on('change', function() {
            setTimeout(autoDetectNextNumber, 400);
        });
        
        // جلوگیری از رفرش با دکمه Enter
        $('#advancedCreateForm').on('submit', function(e) {
            e.preventDefault();
        });
    });
</script>