{% extends "base.html" %}
{% block title %}{{ panel.name }} | فرنود{% endblock %}
{% block content %}
<div class="dashboard">
    {% include "_sidebar.html" %}
    <main class="main">
        <header class="topbar">
  <div style="display:flex;gap:.5rem;align-items:center">
    <a href="{{ url_for('panel_edit', slug=panel.slug) }}" class="btn-primary inline">✏️ ویرایش نام</a>
  </div>
            <h2>{{ panel.name }}</h2>
            <div class="topbar-actions">
                <a href="{{ url_for('panel_users', slug=panel.slug) }}" class="btn-primary inline">کاربران VPN</a>
                <a href="{{ url_for('panels_list') }}" class="greeting">همه پنل‌ها</a>
                <button type="button" class="theme-toggle" id="themeToggle" title="تغییر تم">
                    <svg class="icon-sun" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
                    <svg class="icon-moon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:none"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
                </button>
            </div>
        </header>
        <div class="content">
            <div class="card">
                <div class="panel-info-row">
                    <div>
                        <div class="stat-label">نوع</div>
                        <div class="stat-value" style="font-size:1rem">{{ panel.panel_type }}</div>
                    </div>
                    <div>
                        <div class="stat-label">آدرس</div>
                        <div class="stat-value" style="font-size:0.85rem;word-break:break-all">{{ panel.base_url }}</div>
                    </div>
                    <div>
                        <div class="stat-label">وضعیت</div>
                        <div class="stat-value" style="font-size:1rem" id="liveStatus">
                            {% if error %}<span style="color:var(--error)">آفلاین</span>{% else %}<span class="ok">آنلاین</span>{% endif %}
                        </div>
                    </div>
                    <div>
                        <div class="stat-label">بروزرسانی</div>
                        <div class="stat-value" style="font-size:0.85rem;color:var(--text-secondary)" id="liveUpdated">—</div>
                    </div>
                </div>
            </div>

            <div class="card glass panel-limit-card">
              <div class="card-title">سقف فروش این پنل</div>
              <p class="muted">۰ یا خالی = بدون محدودیت. تعداد سفارش‌های فعال/تحویل‌شده این پنل کنترل می‌شود.</p>
              <form method="post" action="{{ url_for('panel_settings', panel_id=panel.id) }}" class="inline-form">
                <input type="number" min="0" name="max_sales" value="{{ panel.max_sales if panel.max_sales is not none else '' }}" placeholder="بدون محدودیت">
                <button class="btn-primary inline" type="submit">ذخیره</button>
              </form>
            </div>

            <div class="card glass">
              <div class="card-title">روش تمدید سرویس</div>
              <p class="muted">هنگام تمدید سرویس توسط کاربر، این روش اعمال می‌شود.</p>
              <form method="post" action="{{ url_for('panel_settings', panel_id=panel.id) }}" class="inline-form">
                <select name="renew_mode">
                  <option value="reset_both" {% if panel.renew_mode == 'reset_both' or not panel.renew_mode %}selected{% endif %}>۱) ریست زمان و حجم</option>
                  <option value="reset_time" {% if panel.renew_mode == 'reset_time' %}selected{% endif %}>۲) ریست زمان فقط</option>
                  <option value="reset_volume" {% if panel.renew_mode == 'reset_volume' %}selected{% endif %}>۳) ریست حجم فقط</option>
                  <option value="additive" {% if panel.renew_mode == 'additive' %}selected{% endif %}>۴) بدون ریست (افزایشی)</option>
                </select>
                <button class="btn-primary inline" type="submit">ذخیره</button>
              </form>
            </div>

            <div id="liveError" class="card" style="{% if not error %}display:none;{% endif %}border-color:color-mix(in srgb, var(--error) 40%, transparent)">
                <div class="card-title" style="color:var(--error)">خطا</div>
                <p class="card-desc" id="liveErrorText">{{ error or '' }}</p>
            </div>

            <div class="stats" id="statsHardware">
                <div class="stat"><div class="stat-label">CPU</div><div class="stat-value" id="sCpu">—</div></div>
                <div class="stat"><div class="stat-label">رم</div><div class="stat-value" id="sMem">—</div></div>
                <div class="stat"><div class="stat-label">دیسک</div><div class="stat-value" id="sDisk">—</div></div>
                <div class="stat"><div class="stat-label">کاربران کل</div><div class="stat-value" id="sUsers">—</div></div>
            </div>
            <div class="stats">
                <div class="stat"><div class="stat-label">فعال</div><div class="stat-value ok" id="sActive">—</div></div>
                <div class="stat"><div class="stat-label">منقضی / محدود</div><div class="stat-value" id="sExpired">—</div></div>
                <div class="stat"><div class="stat-label">ترافیک ورودی</div><div class="stat-value" style="font-size:1rem" id="sIn">—</div></div>
                <div class="stat"><div class="stat-label">ترافیک خروجی</div><div class="stat-value" style="font-size:1rem" id="sOut">—</div></div>
            </div>

            <div class="card">
                <form method="POST" action="{{ url_for('panels_delete', panel_id=panel.id) }}" onsubmit="return confirm('پنل حذف شود؟');">
                    <button type="submit" class="btn-danger">حذف پنل</button>
                </form>
            </div>
        </div>
    </main>
</div>
<script>
(function() {
    const slug = {{ panel.slug|tojson }};
    const url = "/api/panels/" + slug + "/stats";

    function fmtGB(n) {
        if (n == null || isNaN(n)) return "—";
        return (Number(n) / 1024 / 1024 / 1024).toFixed(1) + " GB";
    }
    function pick(obj, keys, def) {
        for (const k of keys) {
            if (obj && obj[k] != null) return obj[k];
        }
        return def;
    }
    function render(data) {
        const el = (id) => document.getElementById(id);
        const now = new Date().toLocaleTimeString("fa-IR");
        el("liveUpdated").textContent = now;

        if (!data.ok) {
            el("liveStatus").innerHTML = '<span style="color:var(--error)">آفلاین</span>';
            el("liveError").style.display = "";
            el("liveErrorText").textContent = data.error || "خطا";
            return;
        }
        el("liveStatus").innerHTML = '<span class="ok">آنلاین</span>';
        el("liveError").style.display = "none";
        const s = data.stats || {};
        const cpu = pick(s, ["cpu_usage", "cpu"], null);
        el("sCpu").textContent = cpu != null ? (Number(cpu).toFixed(1) + "%") : "—";

        const memUsed = pick(s, ["mem_used", "memory_used"], null);
        const memTotal = pick(s, ["mem_total", "memory_total"], null);
        el("sMem").textContent = (memUsed != null && memTotal != null) ? (fmtGB(memUsed) + " / " + fmtGB(memTotal)) : "—";

        const diskUsed = pick(s, ["disk_used"], null);
        const diskTotal = pick(s, ["disk_total"], null);
        el("sDisk").textContent = (diskUsed != null && diskTotal != null) ? (fmtGB(diskUsed) + " / " + fmtGB(diskTotal)) : "—";

        const users = s.users || {};
        el("sUsers").textContent = pick(s, ["total_user", "users_total"], pick(users, ["total"], "—"));
        el("sActive").textContent = pick(s, ["users_active", "active_users"], pick(users, ["active"], "—"));
        el("sExpired").textContent = pick(s, ["users_expired", "expired_users"], pick(users, ["expired"], "—"));
        el("sIn").textContent = fmtGB(pick(s, ["incoming_bandwidth", "bandwidth_in"], null));
        el("sOut").textContent = fmtGB(pick(s, ["outgoing_bandwidth", "bandwidth_out"], null));
    }

    async function tick() {
        try {
            const res = await fetch(url, { credentials: "same-origin" });
            const data = await res.json();
            render(data);
        } catch (e) {
            render({ ok: false, error: "خطا در دریافت آمار" });
        }
    }
    tick();
    setInterval(tick, 5000);
})();
</script>
{% endblock %}
