<?php
// modules/inventory/widgets/import.php

global $pdo;
$serversList = [];
try {
    if (isset($pdo)) {
        $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-emerald-500 transition-all duration-300" style="width: 0%"></div>
        </div>
        <div class="w-20 h-20 bg-emerald-50 dark:bg-emerald-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg class="w-10 h-10 text-emerald-600 dark:text-emerald-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-emerald-400 to-emerald-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-emerald-600 dark:text-emerald-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-emerald-600 hover:bg-emerald-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-emerald-500 max-w-5xl mx-auto">
    <div class="flex border-b border-gray-100 dark:border-slate-700 bg-gray-50 dark:bg-slate-800 flex-wrap">
        <button type="button" onclick="switchImportTab('generator')" id="tab-generator" class="flex-1 py-4 px-2 font-bold text-emerald-700 dark:text-emerald-400 bg-white dark:bg-slate-700 border-b-2 border-emerald-500 text-sm transition">۱. تولید و ورود پیشرفته</button>
        <button type="button" onclick="switchImportTab('single')" id="tab-single" class="flex-1 py-4 px-2 font-bold text-gray-500 transition text-sm">۲. ساخت و ورود تکی</button>
        <button type="button" onclick="switchImportTab('bulk')" id="tab-bulk" class="flex-1 py-4 px-2 font-bold text-gray-500 transition text-sm">۳. ایمپورت گروهی (لینک)</button>
    </div>

    <div class="p-6">
        
        <form id="form-generator" class="block" onsubmit="event.preventDefault();">
            
            <div class="mb-6 bg-emerald-50 dark:bg-emerald-900/20 p-5 rounded-2xl border border-emerald-200 dark:border-emerald-800/50" dir="rtl">
                <label class="block text-sm font-black text-emerald-800 dark:text-emerald-300 mb-2">سرور مقصد (Server)</label>
                <select id="target_server_id_gen" name="server_id" required class="w-full border-2 border-emerald-200 dark:border-emerald-700 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-800 dark:text-white text-sm font-bold shadow-sm transition" onchange="onServerChangeGen()">
                    <?php if(empty($serversList)): ?>
                        <option value="" disabled selected>هیچ سروری تعریف نشده است!</option>
                    <?php else: ?>
                        <option value="" disabled selected>-- انتخاب سرور --</option>
                        <?php foreach($serversList as $srv): ?>
                            <option value="<?php echo $srv['id']; ?>"><?php echo htmlspecialchars($srv['name']); ?></option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </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-gray-50/50 dark:bg-slate-800/50 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-200 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 id="create_status_gen" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm">
                                <option value="active">فعال (Active)</option>
                                <option value="disabled">مسدود (Disabled)</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">سقف حجم</label>
                            <div class="flex" dir="ltr">
                                <select id="create_limit_unit_gen" class="border border-r-0 border-gray-200 dark:border-slate-600 p-3 rounded-l-xl outline-none focus:border-emerald-500 bg-gray-50 dark:bg-slate-600 dark:text-white text-sm font-bold cursor-pointer" onchange="autoDetectNextNumber()">
                                    <option value="GB">GB</option>
                                    <option value="MB">MB</option>
                                </select>
                                <input type="number" id="create_limit_val_gen" 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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm font-mono" 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">ریست دوره‌ای حجم</label>
                            <select id="create_reset_gen" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm">
                                <option value="no_reset">بدون ریست</option>
                                <option value="day">روزانه</option>
                                <option value="month">ماهانه</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">تاریخ انقضا</label>
                            <div class="flex gap-2">
                                <input type="datetime-local" id="create_expire_val_gen" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-[12px] font-mono" dir="ltr">
                                <button type="button" onclick="$('#create_expire_val_gen').val('')" class="bg-rose-50 text-rose-600 px-3 rounded-xl text-[10px] font-bold border border-rose-200 dark:bg-rose-900/30 dark:border-rose-800">Clear</button>
                            </div>
                        </div>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">یادداشت</label>
                        <input type="text" id="create_note_gen" class="w-full border border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm">
                    </div>
                    <div class="border border-gray-200 dark:border-slate-600 rounded-xl overflow-hidden">
                        <div class="px-5 py-3 bg-white 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">🔒 پروتکل‌ها (Proxies)</span></div>
                        <div class="p-5 flex flex-wrap gap-4 bg-gray-50 dark:bg-slate-800" dir="ltr">
                            <label class="flex items-center gap-2 cursor-pointer"><input type="checkbox" name="proxies_gen[]" value="vless" checked class="text-emerald-600"> <span class="text-xs font-bold font-mono dark:text-gray-300">VLESS</span></label>
                            <label class="flex items-center gap-2 cursor-pointer"><input type="checkbox" name="proxies_gen[]" value="vmess" checked class="text-emerald-600"> <span class="text-xs font-bold font-mono dark:text-gray-300">VMESS</span></label>
                            <label class="flex items-center gap-2 cursor-pointer"><input type="checkbox" name="proxies_gen[]" value="trojan" checked class="text-emerald-600"> <span class="text-xs font-bold font-mono dark:text-gray-300">TROJAN</span></label>
                            <label class="flex items-center gap-2 cursor-pointer"><input type="checkbox" name="proxies_gen[]" value="shadowsocks" checked class="text-emerald-600"> <span class="text-xs font-bold font-mono dark:text-gray-300">SHADOWSOCKS</span></label>
                        </div>
                    </div>
                </div>
                <div class="md:col-span-1 border-r border-gray-200 dark:border-slate-700 pr-6 h-full flex flex-col">
                    <h3 class="text-sm font-bold text-emerald-600 border-b-2 border-emerald-600 pb-3 mb-4 inline-block w-fit">گروه‌ها (Groups)</h3>
                    <div class="flex-1 overflow-y-auto tiny-scrollbar pl-2 space-y-1" id="create_groups_list_gen" style="max-height: 400px;">
                        <div class="text-center text-xs text-amber-500 font-bold mt-10">ابتدا سرور را انتخاب کنید...</div>
                    </div>
                </div>
            </div>

            <div class="bg-emerald-50/50 dark:bg-emerald-900/10 p-6 rounded-2xl border border-emerald-100 dark:border-emerald-800/50 mb-8 relative">
                <h3 class="text-sm font-black text-emerald-800 dark:text-emerald-400 mb-5">تولید هوشمند یوزرنیم</h3>
                <div class="absolute top-6 left-6 bg-white dark:bg-slate-800 border border-emerald-200 dark:border-emerald-700 font-bold text-xs px-4 py-2 rounded-xl text-emerald-700 dark:text-emerald-300">
                    تعداد: <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 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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm" dir="ltr" oninput="autoDetectNextNumber()">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-600 dark:text-gray-400 mb-1.5">طرح EN</label>
                        <input type="text" id="gen_plan" class="w-full border-2 border-white dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-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">
                            <span>شروع از</span>
                            <button type="button" onclick="autoDetectNextNumber()" class="text-[9px] text-emerald-600 hover:text-emerald-800 bg-emerald-50 px-1 rounded dark:bg-emerald-900/30 dark:text-emerald-400">تشخیص</button>
                        </label>
                        <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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-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>
                        <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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-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-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-sm" onchange="autoDetectNextNumber()">
                            <option value="end">انتها</option>
                            <option value="after_brand">بعد برند</option>
                            <option value="after_plan">بعد طرح</option>
                        </select>
                    </div>
                </div>
                <button type="button" onclick="generateUserListGen()" class="mt-6 w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3.5 rounded-xl transition text-sm">تولید لیست پیش‌نمایش</button>
            </div>

            <div id="preview_section_gen" class="hidden">
                <div id="generated_users_container_gen" class="space-y-3 mb-6 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_gen" class="w-full bg-[#3b5998] hover:bg-blue-800 text-white font-black py-4 rounded-xl transition text-lg flex items-center justify-center gap-3">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    ثبت در سرور و انتقال به انبار
                </button>
            </div>
            <div id="final_result_container_gen"></div>
        </form>

        <form id="form-single" class="hidden" onsubmit="event.preventDefault(); startSingleCreation();">
            <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">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-black text-blue-800 dark:text-blue-300 mb-2">سرور مقصد (Server)</label>
                        <select id="target_server_id_single" name="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" onchange="onServerChangeSingle()">
                            <option value="" disabled selected>-- انتخاب سرور --</option>
                            <?php foreach($serversList as $srv): ?>
                                <option value="<?php echo $srv['id']; ?>"><?php echo htmlspecialchars($srv['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-black text-blue-800 dark:text-blue-300 mb-2">طرح انبار (Inventory Plan)</label>
                        <select id="single_db_plan" 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">
                            <option value="" disabled selected>-- انتخاب طرح انبار --</option>
                            <?php foreach($plansList as $p): ?>
                                <option value="<?php echo htmlspecialchars($p['plan_name']); ?>"><?php echo htmlspecialchars($p['plan_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 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-5">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">نام کاربری (Username)</label>
                            <input type="text" id="single_username" dir="ltr" required class="w-full bg-gray-50 dark:bg-slate-700 border border-gray-200 dark:border-slate-600 p-2.5 rounded-lg outline-none focus:border-blue-500 text-sm font-mono dark:text-white">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">وضعیت (Status)</label>
                            <select id="single_status" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-lg outline-none focus:border-blue-500 bg-white dark:bg-slate-700 text-sm dark:text-white">
                                <option value="active">فعال</option>
                                <option value="disabled">مسدود</option>
                            </select>
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-4">
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">سقف حجم</label>
                            <div class="flex" dir="ltr">
                                <select id="single_limit_unit" class="border border-r-0 border-gray-200 dark:border-slate-600 p-2.5 rounded-l-lg outline-none focus:border-blue-500 bg-gray-100 dark:bg-slate-600 text-sm dark:text-white font-bold cursor-pointer">
                                    <option value="GB">GB</option>
                                    <option value="MB">MB</option>
                                </select>
                                <input type="number" id="single_limit_val" step="0.1" min="0.1" required class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-r-lg outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 text-sm dark:text-white" dir="ltr">
                            </div>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">ریست دوره‌ای</label>
                            <select id="single_reset" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-lg outline-none focus:border-blue-500 bg-white dark:bg-slate-700 text-sm dark:text-white">
                                <option value="no_reset">بدون ریست</option>
                                <option value="day">روزانه</option>
                                <option value="month">ماهانه</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">تاریخ انقضا</label>
                            <input type="datetime-local" id="single_expire_val" dir="ltr" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-lg outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 text-[11px] dark:text-white">
                        </div>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1.5">یادداشت</label>
                        <input type="text" id="single_note" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-lg outline-none focus:border-blue-500 bg-gray-50 dark:bg-slate-700 text-sm dark:text-white">
                    </div>
                    <div class="border border-gray-200 dark:border-slate-600 rounded-lg overflow-hidden">
                        <div class="px-4 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">🔒 پروتکل‌ها</span></div>
                        <div class="p-4 flex flex-wrap gap-3 bg-white dark:bg-slate-800" dir="ltr">
                            <label class="flex items-center gap-1.5"><input type="checkbox" name="proxies_single[]" value="vless" checked class="text-blue-600"> <span class="text-xs font-mono dark:text-gray-300">VLESS</span></label>
                            <label class="flex items-center gap-1.5"><input type="checkbox" name="proxies_single[]" value="vmess" checked class="text-blue-600"> <span class="text-xs font-mono dark:text-gray-300">VMESS</span></label>
                            <label class="flex items-center gap-1.5"><input type="checkbox" name="proxies_single[]" value="trojan" checked class="text-blue-600"> <span class="text-xs font-mono dark:text-gray-300">TROJAN</span></label>
                            <label class="flex items-center gap-1.5"><input type="checkbox" name="proxies_single[]" value="shadowsocks" checked class="text-blue-600"> <span class="text-xs font-mono dark:text-gray-300">SHADOWSOCKS</span></label>
                        </div>
                    </div>
                </div>
                <div class="md:col-span-1 border-r border-gray-100 dark:border-slate-700 pr-6 h-full flex flex-col">
                    <h3 class="text-xs font-bold text-blue-600 border-b-2 border-blue-600 pb-2 mb-3 inline-block w-fit">گروه‌ها</h3>
                    <div class="flex-1 overflow-y-auto tiny-scrollbar pl-1" id="create_groups_list_single" dir="ltr">
                        <div class="text-center text-xs text-gray-400 mt-5">سرور را انتخاب کنید...</div>
                    </div>
                </div>
            </div>

            <button type="button" onclick="startSingleCreation()" id="btn_submit_single" class="mt-6 w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-4 rounded-xl transition shadow text-lg flex items-center justify-center gap-3">
                <svg class="w-6 h-6" 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>
                ایجاد کاربر در سرور و ثبت در انبار
            </button>
            <div id="single_result_container" class="mt-4"></div>
        </form>

        <form method="POST" id="form-bulk" class="hidden" action="inventory.php">
            <input type="hidden" name="action" value="bulk_import">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-5 bg-gray-50 dark:bg-slate-800/50 p-4 rounded-2xl border border-gray-100 dark:border-slate-700">
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">انتخاب طرح کالا</label>
                    <select name="plan_name" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white font-bold" dir="ltr">
                        <option value="" disabled selected>-- انتخاب طرح --</option>
                        <?php foreach($plansList as $p): ?>
                            <option value="<?php echo htmlspecialchars($p['plan_name']); ?>"><?php echo htmlspecialchars($p['plan_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">حجم اختصاصی (GB)</label>
                    <input type="number" name="volume" required min="1" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white" dir="ltr">
                </div>
            </div>
            <div class="mb-6">
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">لیست اکانت‌ها</label>
                <p class="text-xs text-gray-500 dark:text-gray-400 mb-3 bg-gray-100 dark:bg-slate-700 p-2 rounded">قالب استاندارد: <code>نام‌کاربری,لینک‌ ساب</code> (هر اکانت در یک خط جدید)</p>
                <textarea name="bulk_data" rows="7" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-4 rounded-xl outline-none focus:border-emerald-500 bg-white dark:bg-slate-700 dark:text-white text-left font-mono text-sm leading-relaxed" dir="ltr"></textarea>
            </div>
            <button type="submit" class="w-full bg-gray-800 hover:bg-gray-900 dark:bg-blue-600 dark:hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-lg text-lg">🚀 ایمپورت دسته‌جمعی به انبار</button>
        </form>

    </div>
</div>

<script>
    // تنظیم مسیر API پاسارگارد به صورت داینامیک
    const psgAjaxUrl = '../pasarguard/widgets/psg_create.php';
    const psgApiGetUrl = '../pasarguard/pasarguard_api.php';

    function switchImportTab(tab) {
        ['single', 'bulk', 'generator'].forEach(t => {
            document.getElementById('form-' + t).classList.toggle('hidden', t !== tab);
            document.getElementById('tab-' + t).className = (t === tab) ? "flex-1 py-4 px-2 font-bold text-emerald-700 dark:text-emerald-400 bg-white dark:bg-slate-700 border-b-2 border-emerald-500 text-sm transition" : "flex-1 py-4 px-2 font-bold text-gray-500 transition text-sm";
        });
        
        if(tab === 'generator' && $('#target_server_id_gen').val()) onServerChangeGen();
        if(tab === 'single' && $('#target_server_id_single').val()) onServerChangeSingle();
    }

    function loadPsgGroups(sId, containerId, checkboxName) {
        if(!sId) {
            $('#' + containerId).html('<div class="text-center text-xs text-amber-500 font-bold mt-10">ابتدا سرور را انتخاب کنید</div>');
            return;
        }
        $('#' + containerId).html('<div class="text-center text-xs text-gray-400 mt-10 animate-pulse">در حال دریافت گروه‌ها...</div>');

        $.ajax({
            url: psgApiGetUrl + '?ajax_call=groups&server_id=' + sId,
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                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}`;
                        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="${checkboxName}" value="${gId}" 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>`;
                    });
                    $('#' + containerId).html(html);
                } else {
                    $('#' + containerId).html('<div class="text-center text-xs text-rose-500 font-bold mt-10">هیچ گروهی یافت نشد!</div>');
                }
            },
            error: function() {
                $('#' + containerId).html('<div class="text-center text-xs text-rose-500 font-bold mt-10">خطا در اتصال به API</div>');
            }
        });
    }

    function getSelectedServerIdGen() { return document.getElementById('target_server_id_gen').value; }
    
    function onServerChangeGen() {
        loadPsgGroups(getSelectedServerIdGen(), 'create_groups_list_gen', 'group_ids_gen[]');
        setTimeout(autoDetectNextNumber, 200);
    }

    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 autoDetectNextNumber() {
        let sId = getSelectedServerIdGen();
        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_gen').value.trim();
        const limitUnit = document.getElementById('create_limit_unit_gen').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(); 

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

        $.ajax({
            url: psgApiGetUrl + '?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 num = parseInt(uname.split('-').pop());
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    } 
                    else if (pos === 'after_brand' && uname.startsWith(prefix) && uname.endsWith(`-${plan}-${volumeStr}`.toLowerCase())) {
                        let num = parseInt(uname.split('-')[1]); 
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    } 
                    else if (pos === 'after_plan' && uname.startsWith(prefix) && uname.endsWith(`-${volumeStr}`.toLowerCase())) {
                        let num = parseInt(uname.split('-')[2]);
                        if (!isNaN(num) && num > maxNumber) maxNumber = num;
                    }
                });
                document.getElementById('gen_start').value = maxNumber + 1;
                document.getElementById('gen_end').value = maxNumber + 1; 
                updateLiveCount();
            },
            complete: function() { $('#gen_start').removeClass('opacity-50 pointer-events-none'); }
        });
    }

    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 generateUserListGen() {
        $('#page-loading-overlay').removeClass('opacity-100').addClass('opacity-0 pointer-events-none');

        const dbPlan = document.getElementById('gen_db_plan').value;
        const limitInput = document.getElementById('create_limit_val_gen').value.trim();
        const limitUnit = document.getElementById('create_limit_unit_gen').value;

        if(!dbPlan || !limitInput || limitInput <= 0) {
            alert('لطفاً فرم را به درستی کامل کنید.'); return;
        }

        const brand = document.getElementById('gen_brand').value.trim();
        const plan = document.getElementById('gen_plan').value.trim();
        const 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_gen');
        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); parts.push(volumeStr);
            } else if (pos === 'after_plan') {
                if(brand) parts.push(brand);
                if(plan) parts.push(`${plan}-${num}`); else parts.push(num);
                parts.push(volumeStr);
            } else { 
                if(brand) parts.push(brand); if(plan) parts.push(plan);
                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">
                    <div class="flex-1"><input type="text" name="username_gen[]" 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" 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 rounded-lg transition">×</button>
                </div>`);
        }
        $('#preview_section_gen').slideDown();
        $('#final_result_container_gen').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() {
        $('#page-loading-overlay').removeClass('opacity-100').addClass('opacity-0 pointer-events-none');

        let usernames = [];
        $('input[name="username_gen[]"]').each(function() {
            if($(this).val().trim() !== '') usernames.push($(this).val().trim());
        });
        if(usernames.length === 0) return;

        let server_id = $('#target_server_id_gen').val();
        let serverName = $("#target_server_id_gen option:selected").text();
        let status = $('#create_status_gen').val();
        let data_limit_val = $('#create_limit_val_gen').val();
        let data_limit_unit = $('#create_limit_unit_gen').val();
        let reset_strategy = $('#create_reset_gen').val();
        let expire_date = $('#create_expire_val_gen').val();
        let note = $('#create_note_gen').val();
        let inventory_plan_name = $('#gen_db_plan').val();
        
        let proxies = [];
        $('input[name="proxies_gen[]"]:checked').each(function() { proxies.push($(this).val()); });
        let group_ids = [];
        $('input[name="group_ids_gen[]"]: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, failCount = 0, dbInsertCount = 0;
        let bulkOutputText = ""; let actionResults = [];
        let abortAll = false;

        for(let i = 0; i < usernames.length; i++) {
            if (abortAll) break;
            
            let uname = usernames[i];
            $('#progressText').html(`در حال ساخت: <span class="text-emerald-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: psgAjaxUrl, 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');
            let html = `<div class="mt-8 border-t-2 border-dashed border-gray-200 dark:border-slate-700 pt-6"><div class="flex gap-3 font-bold text-sm mb-4"><span class="text-emerald-700 bg-emerald-100 px-4 py-1.5 rounded-lg">ثبت انبار: ${dbInsertCount}</span></div>`;
            if (successCount > 0) {
                html += `<textarea id="bulkOutput" rows="8" readonly class="w-full border-2 border-emerald-300 bg-emerald-50 p-4 rounded-xl font-mono text-sm" dir="ltr">${bulkOutputText.trim()}</textarea>`;
            }
            if (actionResults.length > 0) {
                html += `<div class="mt-4 space-y-2">`;
                actionResults.forEach(err => { html += `<div class="bg-rose-50 text-rose-800 p-3 rounded-xl text-sm font-mono" dir="ltr">${err.username}: ${err.error}</div>`; });
                html += `</div>`;
            }
            html += `</div>`;
            $('#final_result_container_gen').html(html);
            $('#preview_section_gen').slideUp();
        }, 800);
    }

    function getSelectedServerIdSingle() { return document.getElementById('target_server_id_single').value; }
    function onServerChangeSingle() { loadPsgGroups(getSelectedServerIdSingle(), 'create_groups_list_single', 'group_ids_single[]'); }

    async function startSingleCreation() {
        $('#page-loading-overlay').removeClass('opacity-100').addClass('opacity-0 pointer-events-none');

        let server_id = $('#target_server_id_single').val();
        let inventory_plan_name = $('#single_db_plan').val();
        let username = $('#single_username').val().trim();
        let status = $('#single_status').val();
        let data_limit_val = $('#single_limit_val').val();
        let data_limit_unit = $('#single_limit_unit').val();
        let reset_strategy = $('#single_reset').val();
        let expire_date = $('#single_expire_val').val();
        let note = $('#single_note').val();
        
        let proxies = [];
        $('input[name="proxies_single[]"]:checked').each(function() { proxies.push($(this).val()); });
        let group_ids = [];
        $('input[name="group_ids_single[]"]:checked').each(function() { group_ids.push($(this).val()); });

        if(!server_id || !inventory_plan_name || !username || !data_limit_val) {
            alert('پر کردن سرور، طرح، نام‌کاربری و سقف حجم الزامی است.'); return;
        }

        $('#btn_submit_single').html('<div class="animate-spin w-5 h-5 border-4 border-white border-t-transparent rounded-full"></div>').attr('disabled', true);

        try {
            let response = await $.ajax({
                url: psgAjaxUrl, 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: username
                }
            });

            if(response.status === 'success') {
                $('#single_result_container').html(`<div class="bg-emerald-100 text-emerald-800 p-4 rounded-xl font-bold">✅ اکانت ${response.username} ساخته و ${response.db_inserted ? 'در انبار ثبت شد' : 'در انبار ثبت نشد'}.</div>`);
                $('#single_username').val(''); 
            } else {
                $('#single_result_container').html(`<div class="bg-rose-100 text-rose-800 p-4 rounded-xl font-bold">❌ خطا: ${response.message}</div>`);
            }
        } catch (err) {
            $('#single_result_container').html(`<div class="bg-rose-100 text-rose-800 p-4 rounded-xl font-bold">❌ خطای شبکه یا قطعی ارتباط با سرور</div>`);
        }
        
        $('#btn_submit_single').html('ایجاد کاربر در سرور و ثبت در انبار').attr('disabled', false);
    }

    $(document).ready(function() {
        $('#target_server_id_gen').trigger('change');
        $('#target_server_id_single').trigger('change');
        updateLiveCount();
    });
</script>