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

<?php $__env->startSection('content'); ?>
<!-- Filter Period Panel -->
<div class="mb-6 rounded-2xl border border-slate-200 bg-white p-4 shadow-soft dark:border-slate-800 dark:bg-slate-900 flex flex-wrap items-center justify-between gap-4">
    <div class="flex items-center gap-3">
        <div class="flex items-center gap-2">
            <i class="fa-solid fa-calendar text-emerald-600 dark:text-emerald-400"></i>
            <span class="text-sm font-semibold text-slate-800 dark:text-slate-200">Filter Period:</span>
        </div>
        <select id="dateFilterSelect" class="rounded-lg border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1.5 text-xs font-semibold text-slate-800 dark:text-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500">
            <option value="today">Today</option>
            <option value="yesterday">Yesterday</option>
            <option value="this_week">This Week</option>
            <option value="this_month" selected>This Month</option>
            <option value="last_month">Last Month</option>
            <option value="this_year">This Year</option>
            <option value="custom">Custom Date Range</option>
        </select>
    </div>

    <!-- Custom Date Picker Inputs -->
    <div id="customDateContainer" class="hidden flex items-center gap-2">
        <input type="date" id="startDateInput" class="rounded-lg border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1 text-xs text-slate-800 dark:text-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500">
        <span class="text-xs text-slate-500">to</span>
        <input type="date" id="endDateInput" class="rounded-lg border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1 text-xs text-slate-800 dark:text-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500">
        <button type="button" id="applyCustomDateBtn" class="px-3 py-1.5 text-xs bg-emerald-600 hover:bg-emerald-700 text-white font-semibold rounded-lg transition-colors">Apply</button>
    </div>

    <div>
        <button type="button" id="refreshDashboardBtn" class="flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 dark:bg-slate-800/60 dark:border-slate-800 px-3 py-1.5 text-xs font-semibold text-slate-700 dark:text-slate-300 hover:bg-slate-100 transition-colors">
            <i class="fa-solid fa-arrows-rotate animate-spin-hover"></i> Refresh
        </button>
    </div>
</div>

<!-- KPI Cards Grid -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 relative">
    <div class="relative overflow-hidden bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out">
        <div class="flex items-center justify-between mb-4">
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Revenue</span>
            <div class="w-8 h-8 rounded-lg bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 flex items-center justify-center"><i class="fas fa-dollar-sign text-sm"></i></div>
        </div>
        <h3 class="text-2xl font-bold text-gray-900 dark:text-white" id="val-total-revenue">$<?php echo e(number_format($stats['total_revenue'], 2)); ?></h3>
        <p class="text-xs text-gray-400 mt-1">Calculated from paid orders</p>
    </div>

    <div class="relative overflow-hidden bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out">
        <div class="flex items-center justify-between mb-4">
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Orders</span>
            <div class="w-8 h-8 rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 flex items-center justify-center"><i class="fas fa-shopping-cart text-sm"></i></div>
        </div>
        <h3 class="text-2xl font-bold text-gray-900 dark:text-white" id="val-total-orders"><?php echo e($stats['total_orders']); ?></h3>
        <p class="text-xs text-gray-400 mt-1">All processed transactions</p>
    </div>

    <div class="relative overflow-hidden bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out">
        <div class="flex items-center justify-between mb-4">
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Paid / Pending</span>
            <div class="w-8 h-8 rounded-lg bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 flex items-center justify-center"><i class="fas fa-clock text-sm"></i></div>
        </div>
        <h3 class="text-2xl font-bold text-gray-900 dark:text-white flex items-baseline gap-1">
            <span class="text-green-600 dark:text-green-400" id="val-paid-orders"><?php echo e($stats['paid_orders']); ?></span>
            <span class="text-gray-400 dark:text-gray-600 text-lg">/</span>
            <span class="text-yellow-600 dark:text-yellow-500" id="val-pending-orders"><?php echo e($stats['pending_orders']); ?></span>
        </h3>
        <p class="text-xs text-gray-400 mt-1">Paid vs pending confirmation</p>
    </div>

    <div class="relative overflow-hidden bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out">
        <div class="flex items-center justify-between mb-4">
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Customers</span>
            <div class="w-8 h-8 rounded-lg bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 flex items-center justify-center"><i class="fas fa-users text-sm"></i></div>
        </div>
        <h3 class="text-2xl font-bold text-gray-900 dark:text-white" id="val-total-customers"><?php echo e($stats['total_customers']); ?></h3>
        <p class="text-xs text-gray-400 mt-1">Registered clients</p>
    </div>
</div>

<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
    <!-- Active Products -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out flex items-center justify-between">
        <div>
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Catalog Products</span>
            <h4 class="text-xl font-bold text-gray-900 dark:text-white mt-1" id="val-total-products"><?php echo e($stats['total_products']); ?></h4>
        </div>
        <div class="w-10 h-10 bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 rounded-lg flex items-center justify-center">
            <i class="fas fa-box text-base"></i>
        </div>
    </div>

    <!-- Low Stock Alert -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out flex items-center justify-between">
        <div>
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Out of Stock</span>
            <h4 class="text-xl font-bold mt-1 <?php echo e($stats['low_stock_products'] > 0 ? 'text-red-600 dark:text-red-400' : 'text-gray-900 dark:text-white'); ?>" id="val-low-stock-products"><?php echo e($stats['low_stock_products']); ?></h4>
        </div>
        <div class="w-10 h-10 <?php echo e($stats['low_stock_products'] > 0 ? 'bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400' : 'bg-gray-50 dark:bg-gray-900 text-gray-400'); ?> rounded-lg flex items-center justify-center">
            <i class="fas fa-exclamation-triangle text-base"></i>
        </div>
    </div>

    <!-- Cancelled Orders -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out flex items-center justify-between">
        <div>
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Cancelled Orders</span>
            <h4 class="text-xl font-bold text-gray-900 dark:text-white mt-1" id="val-cancelled-orders"><?php echo e($stats['cancelled_orders']); ?></h4>
        </div>
        <div class="w-10 h-10 bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 rounded-lg flex items-center justify-center">
            <i class="fas fa-ban text-base"></i>
        </div>
    </div>

    <!-- Quick Navigation -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft hover:-translate-y-px transition duration-150 ease-in-out flex items-center justify-between">
        <div>
            <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Payment Options</span>
            <h4 class="text-xl font-bold text-gray-900 dark:text-white mt-1">ABA & COD</h4>
        </div>
        <div class="w-10 h-10 bg-teal-50 dark:bg-teal-900/20 text-teal-600 dark:text-teal-400 rounded-lg flex items-center justify-center">
            <i class="fas fa-credit-card text-base"></i>
        </div>
    </div>
</div>

<!-- Charts Section -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
    <!-- Revenue Trend Chart -->
    <div class="lg:col-span-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-chart-line mr-2 text-green-500"></i> Revenue Trend
            </h3>
        </div>
        <div class="relative h-64 w-full">
            <div id="revenueChartNoData" class="hidden absolute inset-0 flex items-center justify-center text-center py-20 text-gray-400 dark:text-gray-600 z-10">No revenue data available</div>
            <canvas id="revenueChart"></canvas>
        </div>
    </div>

    <!-- Order Status Chart -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft flex flex-col justify-between">
        <div class="mb-4">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-chart-pie mr-2 text-indigo-500"></i> Order Status Breakdown
            </h3>
        </div>
        <div class="relative h-48 w-full flex items-center justify-center">
            <div id="orderStatusesChartNoData" class="hidden absolute inset-0 flex items-center justify-center text-center py-6 text-gray-400 dark:text-gray-600 z-10">No statuses to report</div>
            <canvas id="orderStatusesChart"></canvas>
        </div>
        <div class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-900 flex justify-around text-xs">
            <div class="flex items-center"><span class="w-3 h-3 bg-yellow-400 rounded-full mr-1.5"></span>Pending</div>
            <div class="flex items-center"><span class="w-3 h-3 bg-blue-500 rounded-full mr-1.5"></span>Processing</div>
            <div class="flex items-center"><span class="w-3 h-3 bg-purple-500 rounded-full mr-1.5"></span>Delivering</div>
            <div class="flex items-center"><span class="w-3 h-3 bg-green-500 rounded-full mr-1.5"></span>Completed</div>
        </div>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
    <!-- Top Selling Products -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-fire mr-2 text-orange-500"></i> Top Products Sold
            </h3>
        </div>
        <div class="relative h-64 w-full">
            <div id="topProductsChartNoData" class="hidden absolute inset-0 flex items-center justify-center text-center py-20 text-gray-400 dark:text-gray-600 z-10">No items sold yet</div>
            <canvas id="topProductsChart"></canvas>
        </div>
    </div>

    <!-- Payment Methods Split -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-wallet mr-2 text-teal-500"></i> Payment Methods (ABA vs COD)
            </h3>
        </div>
        <div class="relative h-64 w-full flex items-center justify-center">
            <div id="paymentMethodsChartNoData" class="hidden absolute inset-0 flex items-center justify-center text-center py-20 text-gray-400 dark:text-gray-600 z-10">No transaction logs available</div>
            <canvas id="paymentMethodsChart"></canvas>
        </div>
    </div>

    <!-- Quick Actions Panel -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-5 shadow-soft">
        <div class="mb-4">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-bolt mr-2 text-yellow-500"></i> Quick Business Actions
            </h3>
        </div>
        <div class="grid grid-cols-2 gap-3">
            <a href="<?php echo e(route('admin.products.create')); ?>" class="p-3 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900 flex flex-col items-center justify-center text-center transition-colors">
                <i class="fas fa-plus-circle text-blue-600 dark:text-blue-400 text-lg mb-2"></i>
                <span class="text-xs font-semibold text-gray-800 dark:text-gray-200">Add Product</span>
            </a>
            <a href="<?php echo e(route('admin.categories.create')); ?>" class="p-3 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900 flex flex-col items-center justify-center text-center transition-colors">
                <i class="fas fa-folder-plus text-green-600 dark:text-green-400 text-lg mb-2"></i>
                <span class="text-xs font-semibold text-gray-800 dark:text-gray-200">Create Category</span>
            </a>
            <a href="<?php echo e(route('admin.orders.index')); ?>?status=pending" class="p-3 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900 flex flex-col items-center justify-center text-center transition-colors">
                <i class="fas fa-tasks text-yellow-600 dark:text-yellow-500 text-lg mb-2"></i>
                <span class="text-xs font-semibold text-gray-800 dark:text-gray-200">Pending Orders</span>
            </a>
            <a href="<?php echo e(route('admin.slides.index')); ?>" class="p-3 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900 flex flex-col items-center justify-center text-center transition-colors">
                <i class="fas fa-images text-indigo-600 dark:text-indigo-400 text-lg mb-2"></i>
                <span class="text-xs font-semibold text-gray-800 dark:text-gray-200">Banners</span>
            </a>
            <a href="<?php echo e(route('admin.settings.index')); ?>" class="col-span-2 p-3 border border-gray-200 dark:border-gray-800 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-900 flex items-center justify-center gap-2 transition-colors">
                <i class="fas fa-sliders-h text-gray-600 dark:text-gray-400"></i>
                <span class="text-xs font-semibold text-gray-800 dark:text-gray-200">Configure System Settings</span>
            </a>
        </div>
    </div>
</div>

<!-- Lists Section -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
    <!-- Recent Orders -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl overflow-hidden shadow-soft">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-receipt mr-2 text-gray-500 dark:text-gray-400"></i> Recent Orders
            </h3>
            <a href="<?php echo e(route('admin.orders.index')); ?>" class="text-xs font-semibold text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                View All
            </a>
        </div>
        <div class="p-6">
            <div id="recent-orders-list" class="space-y-4">
                <?php if($recentOrders->count() > 0): ?>
                    <?php $__currentLoopData = $recentOrders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $order): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="flex items-center justify-between p-3 rounded-lg border border-gray-100 dark:border-gray-900 hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors">
                            <div>
                                <span class="text-xs text-gray-400 dark:text-gray-500"><?php echo e($order->created_at->format('M d, Y H:i')); ?></span>
                                <h4 class="text-sm font-semibold text-gray-900 dark:text-white mt-0.5">
                                    <a href="<?php echo e(route('admin.orders.show', $order)); ?>" class="hover:text-emerald-600 dark:hover:text-emerald-400"><?php echo e($order->order_number); ?></a>
                                </h4>
                                <p class="text-xs text-gray-500 dark:text-gray-400">By <?php echo e($order->customer_name); ?></p>
                            </div>
                            <div class="text-right">
                                <span class="text-sm font-bold text-gray-950 dark:text-white block">$<?php echo e(number_format($order->total, 2)); ?></span>
                                <?php
                                    $paymentBadge = match($order->payment_status) {
                                        'paid' => 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
                                        'pending' => 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
                                        default => 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
                                    };
                                ?>
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold <?php echo e($paymentBadge); ?>">
                                    <?php echo e(ucfirst($order->payment_status)); ?>

                                </span>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php else: ?>
                    <div class="text-center py-10 text-gray-500 dark:text-gray-400 text-sm">
                        No orders registered yet for this period.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Recent Customers -->
    <div class="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl overflow-hidden shadow-soft">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between">
            <h3 class="text-base font-bold text-gray-900 dark:text-white flex items-center">
                <i class="fas fa-users mr-2 text-gray-500 dark:text-gray-400"></i> Recent Registrations
            </h3>
            <a href="<?php echo e(route('admin.customers.index')); ?>" class="text-xs font-semibold text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                View All
            </a>
        </div>
        <div class="p-6">
            <div id="recent-registrations-list" class="space-y-4">
                <?php if($recentCustomers->count() > 0): ?>
                    <?php $__currentLoopData = $recentCustomers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="flex items-center justify-between p-3 rounded-lg border border-gray-100 dark:border-gray-900 hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors">
                            <div class="flex items-center space-x-3">
                                <div class="w-9 h-9 bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-full flex items-center justify-center font-bold text-sm">
                                    <?php echo e(substr($customer->name, 0, 1)); ?>

                                </div>
                                <div>
                                    <h4 class="text-sm font-semibold text-gray-900 dark:text-white"><?php echo e($customer->name); ?></h4>
                                    <p class="text-xs text-gray-500 dark:text-gray-400"><?php echo e($customer->email); ?></p>
                                </div>
                            </div>
                            <div class="text-right">
                                <span class="text-xs text-gray-400 dark:text-gray-500 block">Registered</span>
                                <span class="text-xs text-gray-700 dark:text-gray-300 font-semibold"><?php echo e($customer->created_at->format('M d, Y')); ?></span>
                            </div>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php else: ?>
                    <div class="text-center py-10 text-gray-500 dark:text-gray-400 text-sm">
                        No customer accounts found for this period.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Chart JS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
    // Global chart instances
    window.revenueChart = null;
    window.orderStatusesChart = null;
    window.topProductsChart = null;
    window.paymentMethodsChart = null;

    // Initial load setup
    var initialChartsData = <?php echo json_encode($chartsData); ?>;
    renderCharts(initialChartsData);

    // Filter Change Event Listener
    var filterSelect = document.getElementById('dateFilterSelect');
    var customDateContainer = document.getElementById('customDateContainer');

    filterSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customDateContainer.classList.remove('hidden');
        } else {
            customDateContainer.classList.add('hidden');
            fetchStats(this.value);
        }
    });

    document.getElementById('applyCustomDateBtn').addEventListener('click', function() {
        var start = document.getElementById('startDateInput').value;
        var end = document.getElementById('endDateInput').value;
        if (start && end) {
            fetchStats('custom', start, end);
        } else {
            alert('Please select both start and end dates.');
        }
    });

    document.getElementById('refreshDashboardBtn').addEventListener('click', function() {
        var filter = filterSelect.value;
        var start = document.getElementById('startDateInput').value;
        var end = document.getElementById('endDateInput').value;
        
        var icon = this.querySelector('i');
        icon.classList.add('fa-spin');
        
        fetchStats(filter, start, end, function() {
            setTimeout(function() {
                icon.classList.remove('fa-spin');
            }, 300);
        });
    });

    // Fetch Stats function
    function fetchStats(filter, start = '', end = '', callback = null) {
        // Show loaders or opacity on stats surface
        var statsCards = document.querySelectorAll('#val-total-revenue, #val-total-orders, #val-paid-orders, #val-pending-orders, #val-total-customers, #val-low-stock-products, #val-cancelled-orders');
        statsCards.forEach(function(el) {
            el.style.opacity = '0.5';
        });

        var url = "<?php echo e(route('admin.dashboard.stats')); ?>?filter=" + filter;
        if (filter === 'custom') {
            url += "&start_date=" + start + "&end_date=" + end;
        }

        fetch(url, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            // 1. Update cards text
            document.getElementById('val-total-revenue').innerText = '$' + data.stats.total_revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            document.getElementById('val-total-orders').innerText = data.stats.total_orders;
            document.getElementById('val-paid-orders').innerText = data.stats.paid_orders;
            document.getElementById('val-pending-orders').innerText = data.stats.pending_orders;
            document.getElementById('val-total-customers').innerText = data.stats.total_customers;
            document.getElementById('val-total-products').innerText = data.stats.total_products;
            
            var lowStockEl = document.getElementById('val-low-stock-products');
            lowStockEl.innerText = data.stats.low_stock_products;
            if (data.stats.low_stock_products > 0) {
                lowStockEl.className = 'text-xl font-bold mt-1 text-red-600 dark:text-red-400';
            } else {
                lowStockEl.className = 'text-xl font-bold mt-1 text-gray-900 dark:text-white';
            }

            document.getElementById('val-cancelled-orders').innerText = data.stats.cancelled_orders;

            // Restore cards opacity
            statsCards.forEach(function(el) {
                el.style.opacity = '1';
            });

            // 2. Update Charts
            updateCharts(data.chartsData);

            // 3. Update Recent Lists
            updateRecentLists(data.recentOrders, data.recentCustomers);

            if (callback) callback();
        })
        .catch(err => {
            console.error('Error fetching dashboard stats:', err);
            statsCards.forEach(function(el) {
                el.style.opacity = '1';
            });
            if (callback) callback();
        });
    }

    // Render all charts
    function renderCharts(chartsData) {
        // A. Revenue Trend Chart
        var revenueCtx = document.getElementById('revenueChart').getContext('2d');
        window.revenueChart = new Chart(revenueCtx, {
            type: 'line',
            data: {
                labels: chartsData.revenue.labels,
                datasets: [{
                    label: 'Paid Revenue ($)',
                    data: chartsData.revenue.values,
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.05)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, grid: { color: 'rgba(156, 163, 175, 0.08)' } },
                    x: { grid: { display: false } }
                }
            }
        });

        // B. Order Statuses Chart
        var orderStatusCtx = document.getElementById('orderStatusesChart').getContext('2d');
        window.orderStatusesChart = new Chart(orderStatusCtx, {
            type: 'doughnut',
            data: {
                labels: chartsData.order_statuses.labels,
                datasets: [{
                    data: chartsData.order_statuses.values,
                    backgroundColor: ['#f59e0b', '#3b82f6', '#8b5cf6', '#10b981', '#ef4444'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                cutout: '72%'
            }
        });

        // C. Top Products Chart
        var topProductsCtx = document.getElementById('topProductsChart').getContext('2d');
        window.topProductsChart = new Chart(topProductsCtx, {
            type: 'bar',
            data: {
                labels: chartsData.top_products.labels,
                datasets: [{
                    data: chartsData.top_products.values,
                    backgroundColor: '#f97316',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true, grid: { color: 'rgba(156, 163, 175, 0.08)' } },
                    x: { grid: { display: false } }
                }
            }
        });

        // D. Payment Methods Chart
        var paymentMethodsCtx = document.getElementById('paymentMethodsChart').getContext('2d');
        window.paymentMethodsChart = new Chart(paymentMethodsCtx, {
            type: 'pie',
            data: {
                labels: chartsData.payment_methods.labels,
                datasets: [{
                    data: chartsData.payment_methods.values,
                    backgroundColor: ['#0d9488', '#0ea5e9'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 10, padding: 12, font: { size: 11 } }
                    }
                }
            }
        });

        // Initial toggle placeholders based on empty datasets
        togglePlaceholders(chartsData);
    }

    // Update existing charts
    function updateCharts(chartsData) {
        if (window.revenueChart) {
            window.revenueChart.data.labels = chartsData.revenue.labels;
            window.revenueChart.data.datasets[0].data = chartsData.revenue.values;
            window.revenueChart.update();
        }

        if (window.orderStatusesChart) {
            window.orderStatusesChart.data.labels = chartsData.order_statuses.labels;
            window.orderStatusesChart.data.datasets[0].data = chartsData.order_statuses.values;
            window.orderStatusesChart.update();
        }

        if (window.topProductsChart) {
            window.topProductsChart.data.labels = chartsData.top_products.labels;
            window.topProductsChart.data.datasets[0].data = chartsData.top_products.values;
            window.topProductsChart.update();
        }

        if (window.paymentMethodsChart) {
            window.paymentMethodsChart.data.labels = chartsData.payment_methods.labels;
            window.paymentMethodsChart.data.datasets[0].data = chartsData.payment_methods.values;
            window.paymentMethodsChart.update();
        }

        togglePlaceholders(chartsData);
    }

    // Toggle canvas display vs no data placeholders
    function togglePlaceholders(chartsData) {
        toggleChartPlaceholder('revenueChart', chartsData.revenue.values);
        toggleChartPlaceholder('orderStatusesChart', chartsData.order_statuses.values);
        toggleChartPlaceholder('topProductsChart', chartsData.top_products.values);
        toggleChartPlaceholder('paymentMethodsChart', chartsData.payment_methods.values);
    }

    function toggleChartPlaceholder(canvasId, valuesArray) {
        var canvas = document.getElementById(canvasId);
        var noData = document.getElementById(canvasId + 'NoData');
        var hasValues = valuesArray && valuesArray.length > 0 && valuesArray.reduce((a, b) => a + b, 0) > 0;
        
        if (canvas && noData) {
            if (hasValues) {
                canvas.style.display = 'block';
                noData.classList.add('hidden');
            } else {
                canvas.style.display = 'none';
                noData.classList.remove('hidden');
            }
        }
    }

    // Update list arrays
    function updateRecentLists(recentOrders, recentCustomers) {
        var ordersContainer = document.getElementById('recent-orders-list');
        var customersContainer = document.getElementById('recent-registrations-list');

        // Orders
        if (recentOrders && recentOrders.length > 0) {
            var ordersHtml = '';
            recentOrders.forEach(function(order) {
                var paymentBadge = order.payment_status === 'paid' 
                    ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                    : (order.payment_status === 'pending' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400' : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400');

                ordersHtml += '<div class="flex items-center justify-between p-3 rounded-lg border border-gray-100 dark:border-gray-900 hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors">'
                    + '<div>'
                    + '<span class="text-xs text-gray-400 dark:text-gray-500">' + order.created_at + '</span>'
                    + '<h4 class="text-sm font-semibold text-gray-900 dark:text-white mt-0.5">'
                    + '<a href="' + order.url + '" class="hover:text-emerald-600 dark:hover:text-emerald-400">' + order.order_number + '</a>'
                    + '</h4>'
                    + '<p class="text-xs text-gray-500 dark:text-gray-400">By ' + order.customer_name + '</p>'
                    + '</div>'
                    + '<div class="text-right">'
                    + '<span class="text-sm font-bold text-gray-950 dark:text-white block">$' + order.total + '</span>'
                    + '<span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ' + paymentBadge + '">'
                    + order.payment_status.charAt(0).toUpperCase() + order.payment_status.slice(1)
                    + '</span>'
                    + '</div>'
                    + '</div>';
            });
            ordersContainer.innerHTML = ordersHtml;
        } else {
            ordersContainer.innerHTML = '<div class="text-center py-10 text-gray-500 dark:text-gray-400 text-sm">No orders registered yet for this period.</div>';
        }

        // Customers
        if (recentCustomers && recentCustomers.length > 0) {
            var customersHtml = '';
            recentCustomers.forEach(function(customer) {
                customersHtml += '<div class="flex items-center justify-between p-3 rounded-lg border border-gray-100 dark:border-gray-900 hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors">'
                    + '<div class="flex items-center space-x-3">'
                    + '<div class="w-9 h-9 bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-full flex items-center justify-center font-bold text-sm">'
                    + customer.avatar
                    + '</div>'
                    + '<div>'
                    + '<h4 class="text-sm font-semibold text-gray-900 dark:text-white">' + customer.name + '</h4>'
                    + '<p class="text-xs text-gray-500 dark:text-gray-400">' + customer.email + '</p>'
                    + '</div>'
                    + '</div>'
                    + '<div class="text-right">'
                    + '<span class="text-xs text-gray-400 dark:text-gray-500 block">Registered</span>'
                    + '<span class="text-xs text-gray-700 dark:text-gray-300 font-semibold">' + customer.created_at + '</span>'
                    + '</div>'
                    + '</div>';
            });
            customersContainer.innerHTML = customersHtml;
        } else {
            customersContainer.innerHTML = '<div class="text-center py-10 text-gray-500 dark:text-gray-400 text-sm">No customer accounts found for this period.</div>';
        }
    }
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Users/mac/Documents/e-com/resources/views/admin/dashboard.blade.php ENDPATH**/ ?>