<?php
// modules/pasarguard/widgets/psg_stats.php
?>

<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-cyan-500 mb-6">
    <div class="bg-gray-50 dark:bg-slate-700/40 border-b border-gray-100 dark:border-slate-600 p-4 flex flex-wrap justify-between items-center gap-4">
        <h2 class="text-base font-black text-cyan-800 dark:text-cyan-400 flex items-center gap-2">
            <span>📊</span> وضعیت زنده منابع سرور اصلی
        </h2>
        <div class="flex items-center gap-4">
            <label class="inline-flex items-center cursor-pointer">
                <span class="ml-2 text-xs font-bold text-gray-600 dark:text-gray-400">نمایش نودهای متصل</span>
                <div class="relative">
                    <input type="checkbox" id="toggle_nodes_view" class="sr-only peer" onchange="toggleNodesSection(this.checked)">
                    <div class="w-10 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-600 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-500"></div>
                </div>
            </label>
            <button onclick="loadPsgStats()" class="bg-cyan-100 hover:bg-cyan-200 text-cyan-700 p-2 rounded-xl transition">
                <span id="stats_refresh_icon" class="block text-sm">🔄</span>
            </button>
        </div>
    </div>

    <div class="p-5">
        <div id="stats_loading" class="py-10 text-center text-gray-500 font-bold text-sm">در حال استخراج اطلاعات از سرور...</div>
        <div id="stats_error" class="hidden py-4 text-center text-rose-500 font-bold text-xs bg-rose-50 dark:bg-rose-900/20 rounded-xl"></div>
        
        <div id="stats_container" class="hidden grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            
            <!-- مصرف پردازنده -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl flex flex-col justify-between">
                <div class="flex justify-between items-center mb-2">
                    <span class="text-xs font-bold text-gray-500 dark:text-gray-400 flex items-center gap-1.5"><span>💻</span> پردازنده (CPU)</span>
                    <span id="stat_cpu_cores" class="text-[14px] font-bold bg-blue-100 dark:bg-slate-600 text-blue-700 dark:text-slate-200 px-2 py-0.5 rounded-md" dir="ltr">0 cores</span>
                </div>
                <span id="stat_cpu_val" class="text-lg font-black text-gray-800 dark:text-slate-200" dir="ltr">0%</span>
            </div>

            <!-- مصرف حافظه -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl flex flex-col justify-between">
                <div class="flex justify-between items-center mb-2">
                    <span class="text-xs font-bold text-gray-500 dark:text-gray-400 flex items-center gap-1.5"><span>🧠</span> حافظه (RAM)</span>
                    <span id="stat_ram_perc" class="text-[14px] font-bold text-purple-600 bg-purple-50 dark:bg-purple-900/30 px-2 py-0.5 rounded-md" dir="ltr">0%</span>
                </div>
                <span id="stat_ram_val" class="text-lg font-black text-gray-800 dark:text-slate-200" dir="ltr">0 / 0 GB</span>
            </div>

            <!-- مصرف دیسک -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl flex flex-col justify-between">
                <div class="flex justify-between items-center mb-2">
                    <span class="text-xs font-bold text-gray-500 dark:text-gray-400 flex items-center gap-1.5"><span>💾</span> فضای دیسک</span>
                    <span id="stat_disk_perc" class="text-[14px] font-bold text-amber-600 bg-amber-50 dark:bg-amber-900/30 px-2 py-0.5 rounded-md" dir="ltr">0%</span>
                </div>
                <span id="stat_disk_val" class="text-lg font-black text-gray-800 dark:text-slate-200" dir="ltr">0 / 0 GB</span>
            </div>

            <!-- ترافیک مصرفی کل -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl flex flex-col justify-between">
                <div class="flex justify-between items-center mb-2">
                    <span class="text-xs font-bold text-gray-500 dark:text-gray-400 flex items-center gap-1.5"><span>🌍</span>کل ترافیک مصرفی</span>
                    <div class="flex gap-1.5">
                        <span id="stat_speed_in" class="text-[12px] font-bold text-emerald-600 bg-emerald-50 dark:bg-emerald-900/30 px-1.5 py-0.5 rounded-md" dir="ltr">⬇ 0 KB/s</span>
                        <span id="stat_speed_out" class="text-[12px] font-bold text-blue-600 bg-blue-50 dark:bg-blue-900/30 px-1.5 py-0.5 rounded-md" dir="ltr">⬆ 0 KB/s</span>
                    </div>
                </div>
                <div class="flex justify-between items-end">
                    <span id="stat_net_total" class="text-lg font-black text-gray-800 dark:text-slate-200" dir="ltr">0 GB</span>
                    <div class="flex flex-col text-[12px] font-bold text-gray-500">
                        <span id="stat_net_in" dir="ltr">⬇ 0 B</span>
                        <span id="stat_net_out" dir="ltr">⬆ 0 B</span>
                    </div>
                </div>
            </div>

            <!-- آپتایم سرور -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl md:col-span-2 flex items-center gap-3">
                <div class="w-10 h-10 rounded-full bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400 flex items-center justify-center text-lg shrink-0">⏱️</div>
                <div>
                    <span class="block text-[12px] font-bold text-gray-500 dark:text-gray-400 mb-0.5">زمان روشن بودن سرور (Uptime)</span>
                    <span id="stat_uptime" class="text-lg font-black text-gray-800 dark:text-slate-200 flex flex-row-reverse justify-end gap-1"></span>
                </div>
            </div>

            <!-- آمار کاربران -->
            <div class="bg-gray-50 dark:bg-slate-700/40 border border-gray-100 dark:border-slate-600 p-4 rounded-2xl md:col-span-2 grid grid-cols-3 gap-2 divide-x divide-gray-200 dark:divide-slate-600 divide-x-reverse items-center">
                <div class="text-center">
                    <span class="text-[14px] font-bold text-gray-500 dark:text-gray-400 mb-0.5 flex items-center justify-center gap-1"><span>👥</span> کل</span>
                    <span id="stat_total_users" class="text-xl font-black text-gray-800 dark:text-slate-200">-</span>
                </div>
                <div class="text-center">
                    <span class="text-[14px] font-bold text-gray-500 dark:text-gray-400 mb-0.5 flex items-center justify-center gap-1"><span>✅</span> فعال</span>
                    <span id="stat_active_users" class="text-xl font-black text-blue-600 dark:text-blue-400">-</span>
                </div>
                <div class="text-center">
                    <span class="text-[14px] font-bold text-gray-500 dark:text-gray-400 mb-0.5 flex items-center justify-center gap-1">
                        <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span> آنلاین
                    </span>
                    <span id="stat_online_users" class="text-xl font-black text-emerald-600 dark:text-emerald-400">-</span>
                </div>
            </div>

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

<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script>
    function toggleNodesSection(show) {
        localStorage.setItem('psg_show_nodes', show);
        $('#psg_nodes_section').toggleClass('hidden', !show);
        if(show && typeof loadPsgNodes === 'function') loadPsgNodes();
    }

    function formatBytes(bytes, decimals = 2) {
        if (!+bytes || bytes <= 0) return '0 B';
        const k = 1024, dm = decimals < 0 ? 0 : decimals;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
    }

    function formatUptime(seconds) {
        if (seconds === null || seconds === undefined || isNaN(seconds) || seconds <= 0) return '<span dir="rtl">نامشخص</span>';
        let d = Math.floor(seconds / (3600*24));
        let h = Math.floor((seconds % (3600*24)) / 3600);
        let m = Math.floor((seconds % 3600) / 60);
        let res = "";
        
        // استفاده از ساختار LTR قطعه‌قطعه برای جلوگیری از بهم ریختگی متن در محیط RTL
        if (d > 0) res += `<span dir="ltr">${d}</span> <span>روز و</span> `;
        res += `<span dir="ltr">${h}</span> <span>ساعت و</span> <span dir="ltr">${m}</span> <span>دقیقه</span>`;
        return `<div class="flex items-center gap-1 flex-wrap" dir="rtl">${res}</div>`;
    }

    function loadPsgStats() {
        $('#stats_refresh_icon').addClass('animate-spin');
        $.ajax({
            url: 'pasarguard_api.php?ajax_call=system_stats',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                $('#stats_refresh_icon').removeClass('animate-spin');
                $('#stats_loading, #stats_error').addClass('hidden');
                
                if (res.error) { $('#stats_error').html(res.error).removeClass('hidden'); return; }

                // CPU
                let cpu = parseFloat(res.cpu_usage ?? res.cpu_percent ?? res.cpu ?? 0);
                let cores = res.cpu_cores ?? res.cores ?? 0;
                $('#stat_cpu_val').text(Math.round(cpu) + '%');
                $('#stat_cpu_cores').text(cores + ' Cores');
                
                // RAM
                let memTotal = parseFloat(res.mem_total ?? res.memory_total ?? 1);
                let memUsed = parseFloat(res.mem_used ?? res.memory_used ?? 0);
                $('#stat_ram_val').text(formatBytes(memUsed, 1) + ' / ' + formatBytes(memTotal, 1));
                $('#stat_ram_perc').text(Math.round((memUsed/memTotal)*100) + '%');

                // Disk
                let diskTotal = parseFloat(res.disk_total ?? res.disk_size ?? 1);
                let diskUsed = parseFloat(res.disk_used ?? res.disk_usage ?? 0);
                if (diskUsed > 0) {
                    $('#stat_disk_val').text(formatBytes(diskUsed, 1) + ' / ' + formatBytes(diskTotal, 1));
                    $('#stat_disk_perc').text(Math.round((diskUsed/diskTotal)*100) + '%');
                } else {
                    $('#stat_disk_val').text('نامشخص');
                }

                // Uptime هوشمند
                let uptimeRaw = res.uptime ?? res.system_uptime ?? res.up_time ?? null;
                if (uptimeRaw === null) {
                    let foundKey = Object.keys(res).find(k => k.toLowerCase().includes('uptime'));
                    if (foundKey) uptimeRaw = res[foundKey];
                }
                
                let uptimeDisplay = '<span dir="rtl">نامشخص</span>';
                if (uptimeRaw !== null && uptimeRaw !== undefined && uptimeRaw !== '') {
                    if (typeof uptimeRaw === 'string' && /[^0-9.]/.test(uptimeRaw)) {
                        uptimeDisplay = `<span dir="ltr">${uptimeRaw}</span>`;
                    } else {
                        uptimeDisplay = formatUptime(Number(uptimeRaw));
                    }
                }
                $('#stat_uptime').html(uptimeDisplay);
                
                // Users
                $('#stat_total_users').text(res.total_user ?? res.users_total ?? res.users ?? 0);
                $('#stat_active_users').text(res.users_active ?? res.active_users ?? res.active ?? 0);
                $('#stat_online_users').text(res.online_users ?? res.users_online ?? res.online ?? 0);

                // Traffic هوشمند
                function parseTraffic(val) {
                    if (val === undefined || val === null || val === '') return { num: 0, text: '0 B' };
                    if (typeof val === 'string' && /[a-zA-Z]/.test(val)) return { num: null, text: val };
                    return { num: Number(val), text: formatBytes(Number(val)) };
                }

                let inKey = Object.keys(res).find(k => k.toLowerCase().includes('incom') && !k.toLowerCase().includes('speed')) || 'incoming_bandwidth';
                let outKey = Object.keys(res).find(k => k.toLowerCase().includes('outgo') && !k.toLowerCase().includes('speed')) || 'outgoing_bandwidth';

                let inData = parseTraffic(res[inKey] ?? 0);
                let outData = parseTraffic(res[outKey] ?? 0);

                $('#stat_net_in').text('⬇ ' + inData.text);
                $('#stat_net_out').text('⬆ ' + outData.text);

                if (res.total_traffic !== undefined) {
                    $('#stat_net_total').text(parseTraffic(res.total_traffic).text);
                } else if (inData.num !== null && outData.num !== null) {
                    $('#stat_net_total').text(formatBytes(inData.num + outData.num));
                } else {
                    $('#stat_net_total').text(outData.text); 
                }

                let speedIn = parseFloat(res.incoming_bandwidth_speed ?? res.incoming_speed ?? res.speed_in ?? 0);
                let speedOut = parseFloat(res.outgoing_bandwidth_speed ?? res.outgoing_speed ?? res.speed_out ?? 0);
                $('#stat_speed_in').text('⬇ ' + formatBytes(speedIn) + '/s');
                $('#stat_speed_out').text('⬆ ' + formatBytes(speedOut) + '/s');

                $('#stats_container').removeClass('hidden');
            },
            error: function() {
                $('#stats_refresh_icon').removeClass('animate-spin');
                $('#stats_loading').addClass('hidden');
                $('#stats_error').html('خطا در دریافت اطلاعات از سرور اصلی').removeClass('hidden');
            }
        });
    }

    $(document).ready(function() {
        loadPsgStats();
        let savedNodesPref = localStorage.getItem('psg_show_nodes') === 'true';
        $('#toggle_nodes_view').prop('checked', savedNodesPref);
        toggleNodesSection(savedNodesPref);
    });
</script>