<?php
// modules/dashboard/widgets/scripts.php
if (basename($_SERVER['PHP_SELF']) == 'scripts.php') { die('Access Denied'); }
?>
<script src="/vpnet-panel/assets/js/jquery-3.7.0.min.js"></script>
<script src="/vpnet-panel/assets/js/chart.min.js"></script>
<script src="https://unpkg.com/persian-date@1.1.0/dist/persian-date.min.js"></script>
<script src="https://unpkg.com/persian-datepicker@1.2.0/dist/js/persian-datepicker.min.js"></script>

<script>
    // ==========================================
    // تنظیمات تقویم‌ها و نمودار آژاکسی اصلی
    // ==========================================
    $(document).ready(function() {
        const dpOptions = { format: 'YYYY/MM/DD', initialValue: false, autoClose: true, calendar: { persian: { locale: 'fa' } } };
        $('#start_date_picker').persianDatepicker({ ...dpOptions, onSelect: function (unix) { $('#start_date_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        $('#end_date_picker').persianDatepicker({ ...dpOptions, onSelect: function (unix) { $('#end_date_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });

        let startVal = $('#start_date_alt').val();
        let endVal = $('#end_date_alt').val();
        if(startVal) $('#start_date_picker').val(startVal);
        if(endVal) $('#end_date_picker').val(endVal);
    });

    let trendChart;
    Chart.defaults.font.family = 'Vazirmatn';
    Chart.defaults.color = document.documentElement.classList.contains('dark') ? '#94a3b8' : '#64748b';

    function initOrUpdateChart(labels, profit, volume, count) {
        if (labels.length === 0) {
            $('#chart_container').addClass('hidden');
            $('#chart_empty_msg').removeClass('hidden');
            return;
        }
        $('#chart_empty_msg').addClass('hidden');
        $('#chart_container').removeClass('hidden').css('opacity', '0.5');

        if (trendChart) {
            trendChart.data.labels = labels;
            trendChart.data.datasets[0].data = profit;
            trendChart.data.datasets[1].data = volume;
            trendChart.data.datasets[2].data = count;
            trendChart.update();
            setTimeout(() => $('#chart_container').css('opacity', '1'), 150);
        } else {
            const ctxTrend = document.getElementById('trendChart').getContext('2d');
            trendChart = new Chart(ctxTrend, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        { label: 'سود (T)', data: profit, backgroundColor: 'rgba(16, 185, 129, 0.8)', borderRadius: 6, yAxisID: 'y' },
                        { label: 'حجم (GB)', data: volume, type: 'line', borderColor: '#8b5cf6', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' },
                        { label: 'فروش (عدد)', data: count, type: 'line', borderColor: '#f59e0b', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { type: 'linear', position: 'left', grid: { color: 'rgba(156, 163, 175, 0.1)' } },
                        y1: { type: 'linear', position: 'right', grid: { display: false } },
                        x: { grid: { display: false } }
                    }
                }
            });
            setTimeout(() => $('#chart_container').css('opacity', '1'), 150);
        }
    }

    // دریافت اطلاعات نمودار با AJAX بلافاصله پس از لود ساختار صفحه
    $(document).ready(function() {
        let startVal = $('#start_date_alt').val() || '';
        let endVal = $('#end_date_alt').val() || '';
        fetchChartData(startVal, endVal);
    });

    function fetchChartData(start, end) {
        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_chart: 1, start_date: start, end_date: end },
            dataType: 'json',
            success: function(res) { initOrUpdateChart(res.labels, res.profit, res.volume, res.count); }
        });
    }

    function setChartDate(range) {
        const pd = new persianDate();
        let startStr = '', endStr = pd.format('YYYY/MM/DD');

        if (range === '3days') startStr = pd.subtract('days', 3).format('YYYY/MM/DD');
        else if (range === 'week') startStr = pd.subtract('days', 7).format('YYYY/MM/DD');
        else if (range === '15days') startStr = pd.subtract('days', 15).format('YYYY/MM/DD');
        else if (range === 'month') startStr = pd.subtract('days', 30).format('YYYY/MM/DD');
        else if (range === '3months') startStr = pd.subtract('days', 90).format('YYYY/MM/DD');

        $('#start_date_picker').val(startStr); $('#start_date_alt').val(startStr);
        $('#end_date_picker').val(endStr); $('#end_date_alt').val(endStr);
        fetchChartData(startStr, endStr);
    }

    $('#chartFilterForm').on('submit', function(e) {
        e.preventDefault();
        fetchChartData($('#start_date_alt').val(), $('#end_date_alt').val());
    });

    <?php if($isAdmin): ?>
    // ==========================================
    // کدهای مربوط به نمودار مقایسه نمایندگان
    // ==========================================
    let opChart;
    function initOpChart(labels, sales, op_profit, ad_profit, vol) {
        if (labels.length === 0) {
            $('#op_chart_container').addClass('hidden');
            $('#op_chart_empty').removeClass('hidden');
            return;
        }
        $('#op_chart_empty').addClass('hidden');
        $('#op_chart_container').removeClass('hidden').css('opacity', '0.5');

        if (opChart) {
            opChart.data.labels = labels;
            opChart.data.datasets[0].data = sales;
            opChart.data.datasets[1].data = op_profit;
            opChart.data.datasets[2].data = ad_profit;
            opChart.data.datasets[3].data = vol;
            opChart.update();
            setTimeout(() => $('#op_chart_container').css('opacity', '1'), 150);
        } else {
            const ctx = document.getElementById('opChart').getContext('2d');
            opChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        { label: 'فروش کل (T)', data: sales, backgroundColor: '#3b82f6', borderRadius: 4, yAxisID: 'y' },
                        { label: 'سود نماینده (T)', data: op_profit, backgroundColor: '#10b981', borderRadius: 4, yAxisID: 'y' },
                        { label: 'سود ادمین (T)', data: ad_profit, backgroundColor: '#8b5cf6', borderRadius: 4, yAxisID: 'y' },
                        { label: 'حجم فروخته شده (GB)', data: vol, type: 'line', borderColor: '#f59e0b', borderWidth: 3, pointBackgroundColor: '#fff', tension: 0.4, yAxisID: 'y1' }
                    ]
                },
                options: {
                    responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
                    scales: {
                        y: { type: 'linear', position: 'left', grid: { color: 'rgba(156, 163, 175, 0.1)' } },
                        y1: { type: 'linear', position: 'right', grid: { display: false } },
                        x: { grid: { display: false } }
                    }
                }
            });
            setTimeout(() => $('#op_chart_container').css('opacity', '1'), 150);
        }
    }

    function loadOpChart(timeFilter, btnElement) {
        $('.op-time-btn').removeClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').addClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        $(btnElement).addClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').removeClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        
        $('#op_time_filter').val(timeFilter);
        $('#op_start_picker').val(''); $('#op_start_alt').val('');
        $('#op_end_picker').val(''); $('#op_end_alt').val('');
        
        fetchOpChart();
    }

    function fetchOpChart() {
        let timeFilter = $('#op_time_filter').val();
        let sd = $('#op_start_alt').val();
        let ed = $('#op_end_alt').val();
        if(sd || ed) timeFilter = 'custom';
        
        let ops = $('#op_select').val();

        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_op_chart: 1, time_filter: timeFilter, start: sd, end: ed, ops: ops },
            dataType: 'json',
            success: function(res) {
                initOpChart(res.labels, res.sales, res.op_profit, res.ad_profit, res.vol);
            }
        });
    }

    $('#opChartFilterForm').on('submit', function(e) {
        e.preventDefault();
        $('#op_time_filter').val('custom');
        $('.op-time-btn').removeClass('active bg-indigo-100 text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300').addClass('bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-300');
        fetchOpChart();
    });

    $(document).ready(function() {
        const dpOptions2 = { format: 'YYYY/MM/DD', initialValue: false, autoClose: true, calendar: { persian: { locale: 'fa' } } };
        $('#op_start_picker').persianDatepicker({ ...dpOptions2, onSelect: function (unix) { $('#op_start_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        $('#op_end_picker').persianDatepicker({ ...dpOptions2, onSelect: function (unix) { $('#op_end_alt').val(new persianDate(unix).format('YYYY/MM/DD')); } });
        
        fetchOpChart();
    });
    <?php endif; ?>

    // ==========================================
    // موتور مانیتورینگ زنده (AJAX Polling) 
    // ==========================================
    let lastTimeObj = "<?php echo $initLastTime; ?>";
    const isAdmin = <?php echo $isAdmin ? 'true' : 'false'; ?>;
    
    let processedIds = [
        <?php 
            // حل باگ کرش کردن جاوااسکریپت (تغییر نام متغیر به $recentActivity)
            if(!empty($recentActivity)) {
                $ids = array_map(function($a) { return "'" . $a['act_type'] . "_" . $a['ref_id'] . "'"; }, $recentActivity);
                echo implode(",", $ids);
            }
        ?>
    ];

    function formatNumber(num) {
        return Number(num).toLocaleString('en-US');
    }

    function updateStatBox(id, newValue, htmlContent) {
        let el = $('#' + id);
        if (el.attr('data-val') != newValue) {
            el.attr('data-val', newValue);
            el.html(htmlContent);
            let box = el.closest('div').length ? el.closest('div') : el.closest('a');
            box.addClass('ring-2 ring-emerald-500 scale-[1.02]').delay(1000).queue(function(next){
                $(this).removeClass('ring-2 ring-emerald-500 scale-[1.02]');
                next();
            });
        }
    }

    function updateLiveList(id, htmlContent) {
        let el = $('#' + id);
        el.html(htmlContent);
    }

    function fetchLiveFeed() {
        $.ajax({
            url: window.location.href.split('?')[0],
            type: 'GET',
            data: { ajax_live: 1, last_time: lastTimeObj },
            dataType: 'json',
            success: function(response) {
                if (isAdmin) {
                    updateStatBox('live_pending', response.stats.pending_count, formatNumber(response.stats.pending_count));
                    let pendHtml = '';
                    if(response.stats.pending_list.length > 0) {
                        response.stats.pending_list.forEach(p => {
                            pendHtml += `<div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16">${p.op_name}</span><span class="font-mono text-amber-600 dark:text-amber-400" dir="ltr">${formatNumber(p.amount)}</span></div>`;
                        });
                    } else {
                        pendHtml = '<span>موردی نیست</span>';
                    }
                    updateLiveList('live_pending_list', pendHtml);

                    updateStatBox('live_stock', response.stats.stock_count, formatNumber(response.stats.stock_count));
                    let stockHtml = '';
                    if(response.stats.stock_list.length > 0) {
                        response.stats.stock_list.forEach(s => {
                            stockHtml += `<div class="flex justify-between border-b border-gray-50 dark:border-slate-700/50 pb-0.5"><span class="truncate w-16">${s.plan_name} (${s.volume}G)</span><span class="font-mono font-bold text-rose-600 dark:text-rose-400">${s.qty} عدد</span></div>`;
                        });
                    } else {
                        stockHtml = '<span>موجودی تکمیل است</span>';
                    }
                    updateLiveList('live_stock_list', stockHtml);
                }
                
                updateStatBox('live_profit', response.stats.profit, formatNumber(response.stats.profit) + ' <span class="text-[10px]">T</span>');
                updateStatBox('live_sales', response.stats.sales, formatNumber(response.stats.sales));
                updateStatBox('live_volume', response.stats.volume, formatNumber(response.stats.volume) + ' <span class="text-[10px] font-normal text-gray-400">GB</span>');

                if (response.radar) {
                    if (isAdmin) {
                        updateStatBox('radar_total_system', response.radar.totalSystemMoney, formatNumber(response.radar.totalSystemMoney) + ' تومان');
                        updateStatBox('radar_total_gb', response.radar.totalGBSold, formatNumber(response.radar.totalGBSold) + ' <span class="text-xs font-normal">GB</span>');
                        updateStatBox('radar_provider_debt', response.radar.providerDebt, formatNumber(response.radar.providerDebt) + ' <span class="text-[10px] font-normal">T</span>');
                        updateStatBox('radar_pending_amt', response.radar.radarPendingAmount, formatNumber(response.radar.radarPendingAmount) + ' <span class="text-[10px] font-normal">T</span>');
                        
                        $('#radar_wallet_perc').text(response.radar.walletPercentage);
                        $('#radar_debt_perc').text(response.radar.debtPercentage);
                        $('#radar_wallet_bar').css('width', response.radar.walletPercentage + '%');
                        $('#radar_debt_bar').css('width', response.radar.debtPercentage + '%');
                        
                        if(response.radar.walletPercentage > 10) { $('#radar_wallet_text').removeClass('hidden').text(formatNumber(response.radar.totalWalletBalance)); } else { $('#radar_wallet_text').addClass('hidden'); }
                        if(response.radar.debtPercentage > 10) { $('#radar_debt_text').removeClass('hidden').text(formatNumber(response.radar.totalCreditDebt)); } else { $('#radar_debt_text').addClass('hidden'); }
                    } else {
                        updateStatBox('radar_total_buys', response.radar.radarTotalBuys, formatNumber(response.radar.radarTotalBuys) + ' <span class="text-xs font-normal">سرویس</span>');
                        updateStatBox('radar_total_spent', response.radar.radarTotalSpent, formatNumber(response.radar.radarTotalSpent) + ' <span class="text-[10px] font-normal">T</span>');
                        $('#radar_today_new').text(response.radar.todayNewCount);
                        $('#radar_today_renew').text(response.radar.todayRenewCount);
                    }
                }

                if (response.activities && response.activities.length > 0) {
                    $('#empty_timeline').hide();
                    
                    response.activities.forEach(function(act) {
                        let uid = act.uid;
                        if(processedIds.includes(uid)) return;
                        processedIds.push(uid);

                        let opName = act.op_name;
                        let isEmergency = (act.extra && act.extra.includes('اضطراری'));
                        
                        let bgClass = isEmergency ? 'bg-rose-900/30 border-rose-800/50' : 'bg-gray-800/50 border-gray-700/50';
                        let glowClass = isEmergency ? 'super-emergency-item' : 'super-new-item';
                        
                        let icon = '🔔'; let color = 'text-blue-400';
                        if(act.act_type === 'sale') { icon = '🛒'; color = 'text-emerald-400'; }
                        if(act.act_type === 'receipt') { icon = '📄'; color = 'text-amber-400'; }
                        if(act.act_type === 'wallet') {
                            if(act.plan === 'bonus_add') { icon = '🎁'; color = 'text-purple-400'; }
                            else if(act.plan === 'manual_sub') { icon = '➖'; color = 'text-rose-400'; }
                            else { icon = '💳'; color = 'text-indigo-400'; }
                        }
                        if(isEmergency) { icon = '🚨'; color = 'text-rose-500'; }
                        
                        let contentHtml = '';
                        if (act.act_type === 'sale') {
                            let adminProfitHtml = isAdmin ? `
                                <div class="flex flex-col gap-1 col-span-2 sm:col-span-1 border-t sm:border-t-0 sm:border-r border-gray-700/50 pt-2 sm:pt-0 sm:pr-2">
                                    <span class="text-gray-500 text-[10px] font-bold">سود ادمین:</span>
                                    <span class="text-purple-400 font-black text-sm" dir="ltr">${formatNumber(act.ad_profit)} <span class="text-[9px] font-normal">T</span></span>
                                </div>` : '';
                            let gridCols = isAdmin ? 'sm:grid-cols-3' : '';
                            let volDisplay = (act.volume_unit === 'MB') ? (act.volume + 'M') : (act.volume + 'G');
                            
                            contentHtml = `
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2 bg-gray-800/50 p-2 rounded border border-gray-700/50 inline-block">
                                    طرح ${act.plan} <span class="text-blue-400 font-black">(${volDisplay})</span>
                                </div>
                                <div class="grid grid-cols-2 ${gridCols} gap-2 mt-1 bg-black/30 p-2.5 rounded-xl border border-gray-700/50">
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">پرداخت مشتری:</span>
                                        <span class="text-emerald-400 font-black text-sm" dir="ltr">${formatNumber(act.amount)} <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    <div class="flex flex-col gap-1">
                                        <span class="text-gray-500 text-[10px] font-bold">سود نماینده:</span>
                                        <span class="text-green-400 font-black text-sm" dir="ltr">${formatNumber(act.op_profit)} <span class="text-[9px] font-normal">T</span></span>
                                    </div>
                                    ${adminProfitHtml}
                                </div>
                            `;
                        } else {
                            let title = act.extra ? act.extra : 'فیش واریزی (منتظر تایید)';
                            contentHtml = `
                                <div class="text-xs font-bold text-gray-300 leading-tight mb-2">${title}</div>
                                <div class="mt-2 bg-black/30 p-2.5 rounded-xl border border-gray-700/50 flex justify-between items-center">
                                    <span class="text-gray-500 text-[10px] font-bold">مبلغ تراکنش:</span>
                                    <span class="${color} font-black text-sm" dir="ltr">${formatNumber(act.amount)} <span class="text-[9px] font-normal">T</span></span>
                                </div>
                            `;
                        }

                        let html = `
                        <div data-uid="${uid}" class="flex items-start gap-3 p-3.5 rounded-xl border ${bgClass} ${glowClass}" style="display:none;">
                            <div class="w-8 h-8 rounded-full bg-black/30 flex items-center justify-center shrink-0 shadow-inner ${color} text-sm mt-1">${icon}</div>
                            <div class="flex-1 w-full">
                                <div class="flex justify-between items-center mb-1.5">
                                    <span class="font-bold text-gray-200 text-[13px] sm:text-sm">${opName}</span>
                                    <span class="text-[11px] text-gray-500 font-mono bg-gray-800 px-2 py-0.5 rounded-lg" dir="ltr">${act.time_shamsi}</span>
                                </div>
                                ${contentHtml}
                            </div>
                        </div>`;
                        
                        let $el = $(html);
                        $('#timeline_container').prepend($el);
                        $el.slideDown(400);
                        
                        if ($('#timeline_container').children().length > 30) {
                            $('#timeline_container').children().last().remove();
                        }
                    });
                }
                lastTimeObj = response.current_time;
            },
            error: function(err) {
                console.log("Monitoring paused, retrying...");
            }
        });
    }

    setInterval(fetchLiveFeed, 5000);
</script>