<?php
// modules/servers.php
require_once '../includes/auth.php';
checkLogin();
if (!isAdmin()) { header("Location: ../dashboard.php"); exit; }
require_once '../config/db.php';

// عملیات حذف یا افزودن
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'add_server') {
        $type = $_POST['type'] ?? 'pasarguard'; // دریافت نوع پنل
        
        $stmt = $pdo->prepare("INSERT INTO servers (name, type, url, username, password) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            trim($_POST['name']), 
            $type, 
            rtrim(trim($_POST['url']), '/'), 
            trim($_POST['username']), 
            trim($_POST['password'])
        ]);
        $msg = "سرور جدید با موفقیت اضافه شد.";
    }
    
    if (isset($_POST['action']) && $_POST['action'] === 'delete_server') {
        // جلوگیری از حذف سروری که محصولات آن در انبار وجود دارد (اختیاری اما امن)
        $pdo->prepare("DELETE FROM servers WHERE id = ?")->execute([$_POST['server_id']]);
        $msg = "سرور مورد نظر حذف شد.";
    }
}

$servers = $pdo->query("SELECT * FROM servers ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
require_once '../includes/header.php';
?>

<div class="max-w-6xl mx-auto p-6" dir="rtl">
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
        <div>
            <h2 class="text-xl font-black text-gray-800 dark:text-white flex items-center gap-2">
                <svg class="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2"></path></svg>
                مدیریت پنل‌های متصل (Servers)
            </h2>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 font-bold">افزودن و مدیریت سرورهای مختلف برای اتصال به انبار</p>
        </div>
        
        <button onclick="document.getElementById('addServerModal').classList.remove('hidden'); document.getElementById('addServerModal').classList.add('flex');" class="bg-blue-600 text-white px-5 py-2.5 rounded-xl font-bold text-sm shadow-lg hover:bg-blue-700 transition 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>
            افزودن سرور جدید
        </button>
    </div>

    <?php if(isset($msg)) echo "<div class='bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800 p-4 rounded-xl mb-6 font-bold shadow-sm'>✅ $msg</div>"; ?>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php if(empty($servers)): ?>
            <div class="col-span-full bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50 p-6 rounded-2xl text-center">
                <p class="text-amber-600 dark:text-amber-400 font-bold text-sm">هنوز هیچ سروری به سیستم متصل نشده است. لطفاً اولین پنل خود را اضافه کنید.</p>
            </div>
        <?php else: ?>
            <?php foreach($servers as $srv): ?>
                <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 border border-gray-100 dark:border-slate-700 shadow-sm relative overflow-hidden transition hover:shadow-md hover:border-blue-200 dark:hover:border-slate-600">
                    <div class="flex justify-between items-start mb-5 border-b border-gray-50 dark:border-slate-700/50 pb-4">
                        <div>
                            <h3 class="font-black text-lg text-gray-800 dark:text-white mb-1"><?php echo htmlspecialchars($srv['name']); ?></h3>
                            <span class="text-[10px] bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border border-blue-100 dark:border-blue-800 px-2 py-0.5 rounded font-bold uppercase tracking-wider">
                                <?php echo htmlspecialchars($srv['type']); ?>
                            </span>
                        </div>
                        <form method="POST" onsubmit="return confirm('آیا از حذف این سرور اطمینان دارید؟\nنکته: در صورت حذف، ارتباط محصولاتِ این سرور در انبار قطع خواهد شد!')">
                            <input type="hidden" name="action" value="delete_server">
                            <input type="hidden" name="server_id" value="<?php echo $srv['id']; ?>">
                            <button type="submit" class="bg-rose-50 dark:bg-rose-900/30 text-rose-500 hover:bg-rose-500 hover:text-white transition p-2 rounded-lg" title="حذف سرور">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                            </button>
                        </form>
                    </div>
                    <div class="space-y-3 text-xs font-bold text-gray-500 dark:text-gray-400">
                        <div class="flex justify-between items-center bg-gray-50 dark:bg-slate-900/50 p-2.5 rounded-lg">
                            <span>آدرس:</span> 
                            <span dir="ltr" class="text-blue-600 dark:text-blue-400 truncate max-w-[180px]" title="<?php echo htmlspecialchars($srv['url']); ?>"><?php echo htmlspecialchars($srv['url']); ?></span>
                        </div>
                        <div class="flex justify-between items-center p-2.5">
                            <span>یوزرنیم:</span> 
                            <span class="text-gray-800 dark:text-gray-200 font-mono bg-gray-100 dark:bg-slate-700 px-2 py-1 rounded"><?php echo htmlspecialchars($srv['username']); ?></span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div id="addServerModal" class="fixed inset-0 bg-black/60 hidden items-center justify-center z-[100] p-4 backdrop-blur-sm" dir="rtl">
    <div class="bg-white dark:bg-slate-800 rounded-3xl p-8 max-w-md w-full shadow-2xl relative">
        <button type="button" onclick="document.getElementById('addServerModal').classList.add('hidden'); document.getElementById('addServerModal').classList.remove('flex');" class="absolute top-6 left-6 text-gray-400 hover:text-gray-700 dark:hover:text-white transition">
            <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="M6 18L18 6M6 6l12 12"></path></svg>
        </button>

        <h2 class="text-xl font-black mb-6 text-gray-800 dark:text-white flex items-center gap-2">
            <svg class="w-6 h-6 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
            افزودن سرور / پنل جدید
        </h2>
        
        <form method="POST" class="space-y-5">
            <input type="hidden" name="action" value="add_server">
            
            <div>
                <label class="block text-xs font-bold text-gray-600 dark:text-gray-400 mb-2">نوع سیستم (Panel Type)</label>
                <select name="type" required class="w-full border-2 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">
                    <option value="pasarguard">پاسارگارد (Pasarguard)</option>
                    <option value="marzban" disabled>مرزبان (Marzban) - به زودی</option>
                    <option value="xui" disabled>پنل X-UI - به زودی</option>
                </select>
                <p class="text-[10px] text-gray-400 mt-1">ساختار API بر اساس این گزینه تغییر می‌کند.</p>
            </div>

            <div>
                <label class="block text-xs font-bold text-gray-600 dark:text-gray-400 mb-2">نام نمایشی سیستم شما</label>
                <input type="text" name="name" required placeholder="مثال: سرور آلمان اصلی" class="w-full border-2 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 transition">
            </div>
            
            <div>
                <label class="block text-xs font-bold text-gray-600 dark:text-gray-400 mb-2">آدرس پنل (URL + Port)</label>
                <input type="text" name="url" required placeholder="https://panel.example.com:8000" dir="ltr" class="w-full border-2 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-mono transition">
            </div>
            
            <div class="grid grid-cols-2 gap-4 border-t border-gray-100 dark:border-slate-700 pt-4 mt-2">
                <div>
                    <label class="block text-xs font-bold text-gray-600 dark:text-gray-400 mb-2">یوزرنیم ادمین</label>
                    <input type="text" name="username" required class="w-full border-2 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-mono transition" dir="ltr">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-600 dark:text-gray-400 mb-2">رمز عبور (Password)</label>
                    <input type="password" name="password" required class="w-full border-2 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-mono transition" dir="ltr">
                </div>
            </div>
            
            <div class="flex gap-3 pt-4">
                <button type="submit" class="flex-[2] bg-blue-600 hover:bg-blue-700 text-white py-3.5 rounded-xl font-black shadow-lg transition flex justify-center 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="M5 13l4 4L19 7"></path></svg>
                    ذخیره و اتصال
                </button>
                <button type="button" onclick="document.getElementById('addServerModal').classList.add('hidden'); document.getElementById('addServerModal').classList.remove('flex');" class="flex-1 bg-gray-100 hover:bg-gray-200 dark:bg-slate-700 dark:hover:bg-slate-600 text-gray-700 dark:text-gray-200 py-3.5 rounded-xl font-bold transition">
                    انصراف
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>