

<?php $__env->startSection('title', 'Dashboard'); ?>

<?php $__env->startSection('content'); ?>
    <div class="dashboard-grid">
        <!-- Total Users Card -->
        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Total Users</div>
                    <div class="card-value"><?php echo e(number_format($stats['total_users'])); ?></div>
                </div>
                <div class="stat-icon">👥</div>
            </div>
            <div class="card-change">Platform Growth</div>
        </div>

        <!-- Active Ads Card -->
        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Active Ads</div>
                    <div class="card-value"><?php echo e(number_format($stats['active_ads'])); ?></div>
                </div>
                <div class="stat-icon">📋</div>
            </div>
            <div class="card-change">Live Listings</div>
        </div>

        <!-- Revenue Card -->
        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Monthly Revenue</div>
                    <div class="card-value">₹<?php echo e(number_format($stats['monthly_revenue'])); ?></div>
                </div>
                <div class="stat-icon">💰</div>
            </div>
            <div class="card-change">Active Subscriptions</div>
        </div>

        <!-- Pending Ads Card -->
        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title">Pending Ads</div>
                    <div class="card-value"><?php echo e(number_format($stats['pending_ads'])); ?></div>
                </div>
                <div class="stat-icon">⏳</div>
            </div>
            <div class="card-change">Awaiting Approval</div>
        </div>
    </div>

    <!-- Charts and Tables Section -->
    <div class="content-grid">
        <!-- Users by Plan Chart -->
        <div class="chart-card">
            <div class="card-header" style="display: flex; justify-content: space-between; align-items: flex-start;">
                <div>
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Users by Plan Growth</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Track user distribution trend over time</div>
                </div>
                <div style="display: flex; gap: 12px; align-items: center;">
                    <select id="dateRangeSelector" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary); cursor: pointer;">
                        <option value="today">Today</option>
                        <option value="yesterday">Yesterday</option>
                        <option value="7">Last 7 Days</option>
                        <option value="28" selected>Last 28 Days</option>
                        <option value="custom">Custom Range</option>
                    </select>
                    <div id="customDateRange" style="display: none; gap: 8px;">
                        <input type="date" id="startDate" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary);">
                        <input type="date" id="endDate" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary);">
                        <button id="applyCustomRange" style="padding: 8px 16px; background: #7c3aed; color: white; border: none; border-radius: 8px; font-size: 0.875rem; cursor: pointer;">Apply</button>
                    </div>
                </div>
            </div>
            
            <div id="chartLoadingIndicator" style="display: none; text-align: center; padding: 40px; color: var(--text-secondary);">
                <div style="display: inline-block; width: 40px; height: 40px; border: 4px solid var(--border-color); border-top-color: #7c3aed; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                <div style="margin-top: 12px;">Loading chart data...</div>
            </div>
            
            <div style="margin-top: 20px; height: 300px; position: relative;">
                <canvas id="usersByPlanChart"></canvas>
            </div>
        </div>

        <!-- Ad Categories Chart -->
        <div class="chart-card">
            <div class="card-header">
                <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Top Ad Categories</h3>
                <div style="font-size: 0.875rem; color: var(--text-secondary);">Most popular categories by ad count</div>
            </div>
            
            <div style="margin-top: 20px; height: 300px; position: relative; display: flex; align-items: center; justify-content: center;">
                <?php if($adCategories->count() > 0): ?>
                    <canvas id="categoryChart"></canvas>
                <?php else: ?>
                    <div style="text-align: center; color: var(--text-secondary);">
                        <div style="font-size: 3rem; margin-bottom: 12px;">📊</div>
                        <div>No categories found. Create ads to see category distribution.</div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Recent Activity Table -->
        <div class="table-card">
            <div class="card-header">
                <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Recent Activity</h3>
                <div style="font-size: 0.875rem; color: var(--text-secondary);">Latest actions across platform</div>
            </div>
            
            <div style="margin-top: 20px;">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Subject</th>
                            <th>Action</th>
                            <th>Status</th>
                            <th style="text-align: right;">Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__empty_1 = true; $__currentLoopData = $recentActivity; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $activity): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <tr>
                                <td style="font-weight: 600;"><?php echo e($activity['subject']); ?></td>
                                <td><?php echo e($activity['description']); ?></td>
                                <td><span class="status-badge <?php echo e($activity['badge_class']); ?>"><?php echo e($activity['status']); ?></span></td>
                                <td style="text-align: right; color: var(--text-secondary); font-size: 0.875rem;">
                                    <?php echo e(\Carbon\Carbon::parse($activity['created_at'])->diffForHumans()); ?>

                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: var(--text-secondary); padding: 20px;">No recent activity found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- World Map Section -->
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 16px;">
            <div>
                <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">User Geographic Distribution</h3>
                <div style="font-size: 0.875rem; color: var(--text-secondary);">Interactive world map showing user locations by plan type</div>
            </div>
            <div style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
                <select id="mapPlanFilter" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary); cursor: pointer;">
                    <option value="all">All Users</option>
                    <option value="free">Free Users</option>
                    <option value="standard">Standard</option>
                    <option value="premium">All Premium</option>
                    <option value="vip">All VIP</option>
                    <option value="vip_buyer">VIP Buyer</option>
                    <option value="vip_seller">VIP Seller</option>
                    <option value="vip_pro">VIP Pro</option>
                </select>
                <select id="mapDateFilter" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary); cursor: pointer;">
                    <option value="lifetime">Lifetime</option>
                    <option value="today">Today</option>
                    <option value="yesterday">Yesterday</option>
                    <option value="7">Last 7 Days</option>
                    <option value="28">Last 28 Days</option>
                    <option value="custom">Custom Range</option>
                </select>
                <div id="mapCustomDateRange" style="display: none; gap: 8px;">
                    <input type="date" id="mapStartDate" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary);">
                    <input type="date" id="mapEndDate" style="padding: 8px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.875rem; background: var(--card-bg); color: var(--text-primary);">
                    <button id="applyMapDateFilter" style="padding: 8px 16px; background: #7c3aed; color: white; border: none; border-radius: 8px; font-size: 0.875rem; cursor: pointer;">Apply</button>
                </div>
            </div>
        </div>
        
        <div id="mapLoadingIndicator" style="display: none; text-align: center; padding: 40px; color: var(--text-secondary);">
            <div style="display: inline-block; width: 40px; height: 40px; border: 4px solid var(--border-color); border-top-color: #7c3aed; border-radius: 50%; animation: spin 1s linear infinite;"></div>
            <div style="margin-top: 12px;">Loading map data...</div>
        </div>
        
        <div id="mapStats" style="padding: 16px; background: var(--bg-color); border-radius: 8px; margin: 16px 0; display: none;">
            <div style="display: flex; justify-content: space-around; text-align: center;">
                <div>
                    <div style="font-size: 1.5rem; font-weight: 700; color: #7c3aed;" id="mapTotalUsers">0</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Total Users</div>
                </div>
                <div>
                    <div style="font-size: 1.5rem; font-weight: 700; color: #10b981;" id="mapTotalLocations">0</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Locations</div>
                </div>
                <div>
                    <div style="font-size: 0.875rem; font-weight: 600; color: var(--text-primary);" id="mapPeriod">Lifetime</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Period</div>
                </div>
            </div>
        </div>
        
        <div id="worldMap" style="height: 500px; position: relative; border-radius: 8px; overflow: hidden;"></div>
        
        <!-- Legend -->
        <div style="position: absolute; bottom: 70px; right: 30px; background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); z-index: 1000;">
            <h4 style="margin: 0 0 10px; font-size: 0.9em; font-weight: 600;">Plan Types</h4>
            <div style="display: grid; gap: 8px; font-size: 0.85em;">
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 20px; height: 20px; border-radius: 50%; background: #94a3b8;"></div>
                    <span>Free Users</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 20px; height: 20px; border-radius: 50%; background: #3b82f6;"></div>
                    <span>Standard</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 20px; height: 20px; border-radius: 50%; background: #10b981;"></div>
                    <span>VIP Buyer</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 20px; height: 20px; border-radius: 50%; background: #f59e0b;"></div>
                    <span>VIP Seller</span>
                </div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 20px; height: 20px; border-radius: 50%; background: #ef4444;"></div>
                    <span>VIP Pro</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Quick Actions</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Manage your platform</div>
        </div>
        
        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-top: 20px;">
            <a href="<?php echo e(route('admin.users.index')); ?>" style="text-decoration: none;">
                <div style="background: #f3e8ff; border: 1px solid var(--border-color); border-radius: 8px; padding: 16px; text-align: center; transition: all 0.2s ease;">
                    <div style="font-size: 24px; margin-bottom: 8px;">👥</div>
                    <div style="font-weight: 600; color: var(--text-primary);">Manage Users</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">View and manage users</div>
                </div>
            </a>
            
            <a href="<?php echo e(route('admin.ads.index')); ?>" style="text-decoration: none;">
                <div style="background: #dcfce7; border: 1px solid var(--border-color); border-radius: 8px; padding: 16px; text-align: center; transition: all 0.2s ease;">
                    <div style="font-size: 24px; margin-bottom: 8px;">📋</div>
                    <div style="font-weight: 600; color: var(--text-primary);">Manage Ads</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">Review and moderate ads</div>
                </div>
            </a>
            
            <a href="<?php echo e(route('admin.categories.index')); ?>" style="text-decoration: none;">
                <div style="background: #fef3c7; border: 1px solid var(--border-color); border-radius: 8px; padding: 16px; text-align: center; transition: all 0.2s ease;">
                    <div style="font-size: 24px; margin-bottom: 8px;">📁</div>
                    <div style="font-weight: 600; color: var(--text-primary);">Manage Categories</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">Organize categories</div>
                </div>
            </a>
            
            <a href="<?php echo e(route('admin.settings.index')); ?>" style="text-decoration: none;">
                <div style="background: #e0f2fe; border: 1px solid var(--border-color); border-radius: 8px; padding: 16px; text-align: center; transition: all 0.2s ease;">
                    <div style="font-size: 24px; margin-bottom: 8px;">⚙️</div>
                    <div style="font-weight: 600; color: var(--text-primary);">Platform Settings</div>
                    <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 4px;">Configure settings</div>
                </div>
            </a>
        </div>
    </div>

    <!-- Platform Statistics -->
    <div class="content-grid">
        <div class="chart-card">
            <div class="card-header">
                <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Ad Categories</h3>
                <div style="font-size: 0.875rem; color: var(--text-secondary);">Distribution by category</div>
            </div>
            
            <div style="margin-top: 20px; height: 300px; position: relative; display: flex; align-items: center; justify-content: center;">
                 <canvas id="categoryChart"></canvas>
            </div>
        </div>

        <div class="table-card">
            <div class="card-header">
                <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">System Status</h3>
                <div style="font-size: 0.875rem; color: var(--text-secondary);">Platform health</div>
            </div>
            
            <div style="margin-top: 20px;">
                <table class="table">
                    <tbody>
                        <tr>
                            <td style="font-weight: 600;">Database</td>
                            <td><span class="status-badge status-active">Healthy</span></td>
                        </tr>
                        <tr>
                            <td style="font-weight: 600;">API Status</td>
                            <td><span class="status-badge status-active">Operational</span></td>
                        </tr>
                        <tr>
                            <td style="font-weight: 600;">Storage</td>
                            <td><span class="status-badge status-active">Healthy</span></td>
                        </tr>
                        <tr>
                            <td style="font-weight: 600;">Cache</td>
                            <td><span class="status-badge status-active">Healthy</span></td>
                        </tr>
                        <tr>
                            <td style="font-weight: 600;">Last Backup</td>
                            <td><span style="color: var(--text-secondary); font-size: 0.875rem;"><?php echo e(now()->subHours(2)->diffForHumans()); ?></span></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Users by Plan Chart - Dynamic with Date Range
            let usersByPlanChart = null;
            const planColors = {
                'Free': '#94a3b8',
                'Standard': '#7c3aed',
                'VIP Buyer': '#10b981',
                'VIP Seller': '#f59e0b',
                'VIP Pro': '#ef4444',
                'VIP': '#ec4899'
            };
            
            // Function to fetch and update chart data
            function loadChartData(startDate, endDate) {
                const loadingIndicator = document.getElementById('chartLoadingIndicator');
                loadingIndicator.style.display = 'block';
                
                fetch(`/admin/dashboard/users-by-plan-data?start_date=${startDate}&end_date=${endDate}`)
                    .then(response => response.json())
                    .then(data => {
                        loadingIndicator.style.display = 'none';
                        updateChart(data);
                    })
                    .catch(error => {
                        console.error('Error loading chart data:', error);
                        loadingIndicator.style.display = 'none';
                    });
            }
            
            // Function to update chart with new data
            function updateChart(data) {
                const ctx = document.getElementById('usersByPlanChart').getContext('2d');
                
                // Prepare datasets
                const datasets = Object.keys(data.plans).map((planName, index) => {
                    const allColors = Object.values(planColors);
                    const color = planColors[planName] || allColors[index % allColors.length];
                    
                    return {
                        label: planName,
                        data: Object.values(data.plans[planName]),
                        borderColor: color,
                        backgroundColor: color + '20', // 20% opacity
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointRadius: 0,
                        pointHoverRadius: 6,
                        pointHoverBackgroundColor: color,
                        pointHoverBorderColor: '#fff',
                        pointHoverBorderWidth: 2
                    };
                });
                
                // Destroy existing chart if exists
                if (usersByPlanChart) {
                    usersByPlanChart.destroy();
                }
                
                // Create new chart with animation
                usersByPlanChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.dates.map(date => {
                            const d = new Date(date);
                            return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                        }),
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: {
                            mode: 'index',
                            intersect: false
                        },
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top',
                                labels: {
                                    usePointStyle: true,
                                    padding: 15,
                                    font: { size: 12, weight: '600' },
                                    color: '#64748b'
                                }
                            },
                            tooltip: {
                                backgroundColor: '#1e293b',
                                padding: 12,
                                titleFont: { size: 13, weight: '600' },
                                bodyFont: { size: 13 },
                                cornerRadius: 8,
                                displayColors: true,
                                callbacks: {
                                    label: function(context) {
                                        return context.dataset.label + ': ' + context.parsed.y + ' users';
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                stacked: false,
                                grid: {
                                    borderDash: [2, 4],
                                    color: '#e2e8f0',
                                    drawBorder: false
                                },
                                ticks: {
                                    font: { size: 11 },
                                    color: '#64748b',
                                    precision: 0
                                }
                            },
                            x: {
                                grid: {
                                    display: false,
                                    drawBorder: false
                                },
                                ticks: {
                                    font: { size: 11 },
                                    color: '#64748b',
                                    maxRotation: 45,
                                    minRotation: 0
                                }
                            }
                        },
                        animation: {
                            duration: 1000,
                            easing: 'easeInOutQuart'
                        }
                    }
                });
            }
            
            // Date range selector handling
            const dateRangeSelector = document.getElementById('dateRangeSelector');
            const customDateRange = document.getElementById('customDateRange');
            const startDateInput = document.getElementById('startDate');
            const endDateInput = document.getElementById('endDate');
            const applyButton = document.getElementById('applyCustomRange');
            
            dateRangeSelector.addEventListener('change', function() {
                if (this.value === 'custom') {
                    customDateRange.style.display = 'flex';
                } else {
                    customDateRange.style.display = 'none';
                    
                    let startDate, endDate;
                    const today = new Date();
                    endDate = today.toISOString().split('T')[0];
                    
                    if (this.value === 'today') {
                        startDate = endDate;
                    } else if (this.value === 'yesterday') {
                        const yesterday = new Date(today);
                        yesterday.setDate(yesterday.getDate() - 1);
                        startDate = yesterday.toISOString().split('T')[0];
                        endDate = startDate;
                    } else {
                        const daysAgo = new Date(today);
                        daysAgo.setDate(daysAgo.getDate() - parseInt(this.value));
                        startDate = daysAgo.toISOString().split('T')[0];
                    }
                    
                    loadChartData(startDate, endDate);
                }
            });
            
            applyButton.addEventListener('click', function() {
                if (startDateInput.value && endDateInput.value) {
                    loadChartData(startDateInput.value, endDateInput.value);
                }
            });
            
            // Load initial data (last 28 days)
            const today = new Date();
            const thirtyDaysAgo = new Date(today);
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 28);
            loadChartData(thirtyDaysAgo.toISOString().split('T')[0], today.toISOString().split('T')[0]);

            // Category Distribution Chart (Donut Chart)
            <?php if($adCategories->count() > 0): ?>
            const catCtx = document.getElementById('categoryChart').getContext('2d');
            const catLabels = <?php echo json_encode($adCategories->keys()); ?>;
            const catData = <?php echo json_encode($adCategories->values()); ?>;
            const backgroundColors = [
                '#7c3aed', '#10b981', '#f59e0b', '#3b82f6', '#ef4444', 
                '#ec4899', '#8b5cf6', '#06b6d4', '#84cc16', '#f97316'
            ];

            new Chart(catCtx, {
                type: 'doughnut',
                data: {
                    labels: catLabels,
                    datasets: [{
                        data: catData,
                        backgroundColor: backgroundColors,
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '65%',
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                boxWidth: 12,
                                padding: 15,
                                font: { size: 12, weight: '600' },
                                color: '#64748b'
                            }
                        },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            padding: 12,
                            titleFont: { size: 13, weight: '600' },
                            bodyFont: { size: 13 },
                            cornerRadius: 8,
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((context.parsed / total) * 100).toFixed(1);
                                    return context.label + ': ' + context.parsed + ' ads (' + percentage + '%)';
                                }
                            }
                        }
                    }
                }
            });
            <?php endif; ?>

            // ================================================
            // WORLD MAP - User Geographic Distribution
            // ================================================
            let worldMap = null;
            let markersLayer = null;
            // Note: planColors already declared above for chart, reusing the same object

            // Initialize map
            function initWorldMap() {
                if (worldMap) {
                    worldMap.remove();
                }

                worldMap = L.map('worldMap').setView([20, 0], 2);
                
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '© OpenStreetMap contributors',
                    maxZoom: 18,
                    minZoom: 2
                }).addTo(worldMap);

                markersLayer = L.markerClusterGroup({
                    maxClusterRadius: 80,
                    spiderfyOnMaxZoom: true,
                    showCoverageOnHover: false,
                    zoomToBoundsOnClick: true
                });

                worldMap.addLayer(markersLayer);
            }

            // Create pie chart icon
            function createPieChartIcon(location) {
                const size = Math.min(Math.max(location.total * 3, 30), 70);
                const iconId = 'icon-' + location.city.replace(/\s/g, '-');
                
                return L.divIcon({
                    className: 'pie-marker-icon',
                    html: `
                        <div style="position: relative; width: ${size}px; height: ${size}px;">
                            <canvas id="${iconId}" width="${size}" height="${size}"></canvas>
                            <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                                        font-size: 10px; font-weight: 700; color: white; text-shadow: 0 0 3px rgba(0,0,0,0.5);">
                                ${location.total}
                            </div>
                        </div>
                    `,
                    iconSize: [size, size],
                    iconAnchor: [size/2, size/2]
                });
            }

            // Draw pie chart on canvas
            function drawPieChart(canvasId, planBreakdown) {
                setTimeout(() => {
                    const canvas = document.getElementById(canvasId);
                    if (!canvas) return;
                    
                    const ctx = canvas.getContext('2d');
                    const centerX = canvas.width / 2;
                    const centerY = canvas.height / 2;
                    const radius = canvas.width / 2 - 2;
                    
                    const total = Object.values(planBreakdown).reduce((a, b) => a + b, 0);
                    if (total === 0) return;
                    
                    let currentAngle = -Math.PI / 2;
                    
                    Object.entries(planBreakdown).forEach(([plan, count]) => {
                        if (count === 0) return;
                        
                        const sliceAngle = (count / total) * 2 * Math.PI;
                        
                        ctx.beginPath();
                        ctx.moveTo(centerX, centerY);
                        ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
                        ctx.closePath();
                        ctx.fillStyle = planColors[plan];
                        ctx.fill();
                        
                        currentAngle += sliceAngle;
                    });
                    
                    // White border
                    ctx.beginPath();
                    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
                    ctx.strokeStyle = '#ffffff';
                    ctx.lineWidth = 3;
                    ctx.stroke();
                }, 50);
            }

            // Create popup content
            function createPopupContent(location) {
                return `
                    <div style="min-width: 220px; font-family: inherit;">
                        <h3 style="margin: 0 0 10px; font-size: 1.1em; color: #1e293b;">${location.city}, ${location.country}</h3>
                        <div style="font-size: 0.95em; color: #475569; margin-bottom: 12px;">
                            <strong>Total Users:</strong> ${location.total}
                        </div>
                        <div style="border-top: 1px solid #e2e8f0; padding-top: 10px; display: grid; gap: 6px;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="display: flex; align-items: center; gap: 6px;">
                                    <div style="width: 12px; height: 12px; border-radius: 50%; background: #94a3b8;"></div>
                                    Free
                                </span>
                                <strong>${location.plan_breakdown.free}</strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="display: flex; align-items: center; gap: 6px;">
                                    <div style="width: 12px; height: 12px; border-radius: 50%; background: #3b82f6;"></div>
                                    Standard
                                </span>
                                <strong>${location.plan_breakdown.standard}</strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="display: flex; align-items: center; gap: 6px;">
                                    <div style="width: 12px; height: 12px; border-radius: 50%; background: #10b981;"></div>
                                    VIP Buyer
                                </span>
                                <strong>${location.plan_breakdown.vip_buyer}</strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="display: flex; align-items: center; gap: 6px;">
                                    <div style="width: 12px; height: 12px; border-radius: 50%; background: #f59e0b;"></div>
                                    VIP Seller
                                </span>
                                <strong>${location.plan_breakdown.vip_seller}</strong>
                            </div>
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="display: flex; align-items: center; gap: 6px;">
                                    <div style="width: 12px; height: 12px; border-radius: 50%; background: #ef4444;"></div>
                                    VIP Pro
                                </span>
                                <strong>${location.plan_breakdown.vip_pro}</strong>
                            </div>
                        </div>
                    </div>
                `;
            }

            // Load map data
            function loadMapData(planFilter, dateRange) {
                const loadingIndicator = document.getElementById('mapLoadingIndicator');
                const mapStats = document.getElementById('mapStats');
                loadingIndicator.style.display = 'block';
                mapStats.style.display = 'none';
                
                let params = { plan: planFilter };
                
                if (dateRange !== 'lifetime') {
                    const dates = calculateMapDateRange(dateRange);
                    if (dates) {
                        params.start_date = dates.start;
                        params.end_date = dates.end;
                    }
                }
                
                fetch(`/admin/dashboard/user-locations?${new URLSearchParams(params)}`)
                    .then(response => response.json())
                    .then(data => {
                        loadingIndicator.style.display = 'none';
                        updateMap(data);
                        updateMapStats(data);
                    })
                    .catch(error => {
                        console.error('Error loading map data:', error);
                        loadingIndicator.style.display = 'none';
                    });
            }

            // Calculate date range
            function calculateMapDateRange(range) {
                const today = new Date();
                let startDate, endDate = today.toISOString().split('T')[0];
                
                if (range === 'today') {
                    startDate = endDate;
                } else if (range === 'yesterday') {
                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    startDate = yesterday.toISOString().split('T')[0];
                    endDate = startDate;
                } else {
                    const daysAgo = new Date(today);
                    daysAgo.setDate(daysAgo.getDate() - parseInt(range));
                    startDate = daysAgo.toISOString().split('T')[0];
                }
                
                return { start: startDate, end: endDate };
            }

            // Update map with data
            function updateMap(data) {
                markersLayer.clearLayers();
                
                if (!data.locations || data.locations.length === 0) {
                    return;
                }
                
                data.locations.forEach(location => {
                    const icon = createPieChartIcon(location);
                    const marker = L.marker([location.lat, location.lng], { icon });
                    
                    marker.bindPopup(createPopupContent(location), {
                        maxWidth: 300,
                        className: 'custom-popup'
                    });
                    
                    markersLayer.addLayer(marker);
                    
                    // Draw pie chart after marker is added
                    const iconId = 'icon-' + location.city.replace(/\s/g, '-');
                    drawPieChart(iconId, location.plan_breakdown);
                });
                
                // Fit map to show all markers
                if (data.locations.length > 0) {
                    const group = new L.featureGroup(markersLayer.getLayers());
                    worldMap.fitBounds(group.getBounds().pad(0.1));
                }
            }

            // Update stats panel
            function updateMapStats(data) {
                document.getElementById('mapTotalUsers').textContent = data.total_users || 0;
                document.getElementById('mapTotalLocations').textContent = data.locations ? data.locations.length : 0;
                document.getElementById('mapPeriod').textContent = data.period || 'Lifetime';
                document.getElementById('mapStats').style.display = 'block';
            }

            // Filter event listeners
            const mapPlanFilter = document.getElementById('mapPlanFilter');
            const mapDateFilter = document.getElementById('mapDateFilter');
            const mapCustomDateRange = document.getElementById('mapCustomDateRange');
            const applyMapDateFilter = document.getElementById('applyMapDateFilter');
            
            mapPlanFilter.addEventListener('change', function() {
                loadMapData(this.value, mapDateFilter.value);
            });
            
            mapDateFilter.addEventListener('change', function() {
                if (this.value === 'custom') {
                    mapCustomDateRange.style.display = 'flex';
                } else {
                    mapCustomDateRange.style.display = 'none';
                    loadMapData(mapPlanFilter.value, this.value);
                }
            });
            
            applyMapDateFilter.addEventListener('click', function() {
                const startDate = document.getElementById('mapStartDate').value;
                const endDate = document.getElementById('mapEndDate').value;
                
                if (startDate && endDate) {
                    fetch(`/admin/dashboard/user-locations?plan=${mapPlanFilter.value}&start_date=${startDate}&end_date=${endDate}`)
                        .then(response => response.json())
                        .then(data => {
                            updateMap(data);
                            updateMapStats(data);
                        });
                }
            });
            
            // Initialize map on page load
            initWorldMap();
            loadMapData('all', 'lifetime');
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\DND\Apps\CLXpro\clx_backend\resources\views/admin/dashboard.blade.php ENDPATH**/ ?>