<?php
declare(strict_types=1);
require_once __DIR__ . '/../../api/lib.php';

$pageTitle = 'Dashboard';
$pageSection = 'home';

hw_require_auth(['admin']);
$user = hw_get_auth_user();

// Get basic metrics from database
try {
    $pdo = hw_db();
    
    $stmt = $pdo->query('SELECT COALESCE(SUM(CAST(total_amount AS DECIMAL(10,2))), 0) as total FROM orders WHERE status IN ("delivered", "shipped")');
    $totalRevenue = (float)($stmt->fetch()['total'] ?? 0);

    $stmt = $pdo->query('SELECT COUNT(*) as count FROM appointments');
    $totalBookings = (int)($stmt->fetch()['count'] ?? 0);

    $stmt = $pdo->query('SELECT COUNT(*) as count FROM users WHERE id IN (SELECT DISTINCT user_id FROM user_roles WHERE role_id = (SELECT id FROM roles WHERE name = "client"))');
    $totalCustomers = (int)($stmt->fetch()['count'] ?? 0);

    $stmt = $pdo->query('SELECT COUNT(*) as count FROM orders WHERE status = "pending"');
    $pendingOrders = (int)($stmt->fetch()['count'] ?? 0);

    // Recent intake forms
    $stmt = $pdo->prepare('SELECT i.id, i.created_at, u.first_name, u.last_name, u.email FROM intake_forms i JOIN users u ON i.user_id = u.id ORDER BY i.created_at DESC LIMIT 5');
    $stmt->execute();
    $recentIntakes = $stmt->fetchAll();

    // Top products
    $stmt = $pdo->prepare('SELECT p.name, SUM(oi.quantity) as total_sold, SUM(oi.quantity * oi.price) as revenue FROM order_items oi JOIN products p ON oi.product_id = p.id GROUP BY p.id ORDER BY total_sold DESC LIMIT 5');
    $stmt->execute();
    $topProducts = $stmt->fetchAll();

    // Active users count (logged in last 7 days)
    $stmt = $pdo->query('SELECT COUNT(DISTINCT user_id) as count FROM audit_logs WHERE action = "user_login" AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)');
    $activeUsers = (int)($stmt->fetch()['count'] ?? 0);

    // Completed intakes
    $stmt = $pdo->query('SELECT COUNT(*) as count FROM intake_forms');
    $totalIntakes = (int)($stmt->fetch()['count'] ?? 0);

    // Visitor analytics - Last 30 days
    $stmt = $pdo->prepare('SELECT date, total_users, new_users, total_sessions FROM analytics_daily_metrics WHERE date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) ORDER BY date ASC');
    $stmt->execute();
    $visitorData = $stmt->fetchAll();

    // Total site visitors (from analytics_events)
    $stmt = $pdo->query('SELECT COUNT(DISTINCT session_id) as total_visitors FROM analytics_events WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)');
    $totalVisitors = (int)($stmt->fetch()['total_visitors'] ?? 0);

    // Today's visitors
    $stmt = $pdo->query('SELECT COUNT(DISTINCT session_id) as today_visitors FROM analytics_events WHERE DATE(created_at) = CURDATE()');
    $todayVisitors = (int)($stmt->fetch()['today_visitors'] ?? 0);

    // Recent bookings
    $stmt = $pdo->prepare('SELECT a.id, a.starts_at, a.status, u.first_name, u.last_name, c.display_name as coach_name FROM appointments a JOIN users u ON a.user_id = u.id JOIN coaches c ON a.coach_id = c.id ORDER BY a.starts_at DESC LIMIT 3');
    $stmt->execute();
    $recentBookings = $stmt->fetchAll();

    $stats = [
        'total_revenue' => $totalRevenue,
        'total_bookings' => $totalBookings,
        'total_customers' => $totalCustomers,
        'pending_orders' => $pendingOrders,
        'bookings' => $recentBookings,
        'intakes' => $recentIntakes,
        'top_products' => $topProducts,
        'active_users' => $activeUsers,
        'total_intakes' => $totalIntakes,
        'visitor_data' => $visitorData,
        'total_visitors' => $totalVisitors,
        'today_visitors' => $todayVisitors,
    ];
} catch (Exception $e) {
    $stats = [
        'total_revenue' => 0,
        'total_bookings' => 0,
        'total_customers' => 0,
        'pending_orders' => 0,
        'bookings' => [],
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - Herbal Wellness Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-gray-100">
        <!-- Sidebar Navigation -->
        <aside class="w-64 bg-gradient-to-b from-emerald-900 to-emerald-800 text-white shadow-lg flex flex-col">
            <!-- Logo/Brand -->
            <div class="p-6 border-b border-emerald-700 flex-shrink-0">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-lg flex items-center justify-center">
                        <i class="fas fa-leaf text-emerald-900 text-lg"></i>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg">Herbal Admin</h1>
                        <p class="text-emerald-200 text-xs">Management Portal</p>
                    </div>
                </div>
            </div>

            <!-- Navigation Menu -->
            <nav class="flex-1 overflow-y-auto p-4 space-y-2">
                <!-- Dashboard Home -->
                <!-- Dashboard Home -->
                <a href="/atasteofafricanmarketplace/dashboard/admin/" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors bg-emerald-700 text-white">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>

                <!-- CATEGORY: BUSINESS OPERATIONS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Business</p>
                </div>

                <a href="/atasteofafricanmarketplace/dashboard/admin/sales.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-shopping-cart w-5"></i>
                    <span>Sales & Orders</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/bookings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-calendar-check w-5"></i>
                    <span>Booking Calendar</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/coaches.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-user-md w-5"></i>
                    <span>Coaches</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/products.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-boxes w-5"></i>
                    <span>Products</span>
                </a>

                <!-- CATEGORY: CUSTOMERS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Customers</p>
                </div>

                <a href="/atasteofafricanmarketplace/dashboard/admin/customers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-users w-5"></i>
                    <span>All Customers</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/contacts.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-address-book w-5"></i>
                    <span>Contacts & Leads</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/loyalty.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-gift w-5"></i>
                    <span>Loyalty Program</span>
                </a>

                <!-- CATEGORY: INSIGHTS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Insights</p>
                </div>

                <a href="/atasteofafricanmarketplace/dashboard/admin/analytics.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-line w-5"></i>
                    <span>Analytics</span>
                </a>

                <!-- CATEGORY: AUTOMATION & TOOLS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Tools</p>
                </div>

                <a href="/atasteofafricanmarketplace/dashboard/admin/automations.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-robot w-5"></i>
                    <span>Automations</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/cms.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-file-alt w-5"></i>
                    <span>Content Manager</span>
                </a>

                <a href="/atasteofafricanmarketplace/dashboard/admin/developers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-code w-5"></i>
                    <span>Developer Tools</span>
                </a>

                <!-- CATEGORY: SETTINGS -->
                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">System</p>
                </div>

                <a href="/atasteofafricanmarketplace/dashboard/admin/settings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-cog w-5"></i>
                    <span>Settings</span>
                </a>
            </nav>

            <!-- User Profile Footer -->
            <div class="flex-shrink-0 p-4 border-t border-emerald-700 bg-emerald-800">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-full flex items-center justify-center">
                        <i class="fas fa-user text-emerald-900"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-semibold truncate"><?php echo htmlspecialchars($user['first_name'] ?? 'Admin'); ?></p>
                        <p class="text-xs text-emerald-200 truncate"><?php echo htmlspecialchars($user['email'] ?? ''); ?></p>
                    </div>
                    <a href="/atasteofafricanmarketplace/api/auth/logout.php" class="text-emerald-200 hover:text-white">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- Top Header Bar -->
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <h1 class="text-2xl font-bold text-gray-900">Dashboard</h1>
                    <div class="flex items-center gap-4">
                        <button class="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                            <i class="fas fa-bell text-lg"></i>
                        </button>
                        <button class="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                            <i class="fas fa-envelope text-lg"></i>
                        </button>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <main class="flex-1 overflow-auto">
                <div class="p-8">

                    <!-- Key Metrics -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                        <!-- Total Revenue Card -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-emerald-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Total Revenue</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2">$<?php echo number_format($stats['total_revenue'], 2); ?></h3>
                                    <p class="text-emerald-600 text-xs mt-2">↑ 12% from last month</p>
                                </div>
                                <div class="w-12 h-12 bg-emerald-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-dollar-sign text-emerald-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Total Bookings Card -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-blue-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Total Bookings</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $stats['total_bookings']; ?></h3>
                                    <p class="text-blue-600 text-xs mt-2">↑ 8 from last week</p>
                                </div>
                                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-calendar-check text-blue-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Total Customers Card -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-purple-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Total Customers</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $stats['total_customers']; ?></h3>
                                    <p class="text-purple-600 text-xs mt-2">↑ 24 new customers</p>
                                </div>
                                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-users text-purple-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Pending Orders Card -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-orange-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Pending Orders</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $stats['pending_orders']; ?></h3>
                                    <p class="text-orange-600 text-xs mt-2">Awaiting fulfillment</p>
                                </div>
                                <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-hourglass-half text-orange-600 text-xl"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- New Metric Cards Row -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                        <!-- Total Visitors (30 days) -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-cyan-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Total Visitors (30 days)</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($stats['total_visitors']); ?></h3>
                                    <p class="text-cyan-600 text-xs mt-2">Unique sessions</p>
                                </div>
                                <div class="w-12 h-12 bg-cyan-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-users text-cyan-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Today's Visitors -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-blue-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Today's Visitors</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format($stats['today_visitors']); ?></h3>
                                    <p class="text-blue-600 text-xs mt-2">Active today</p>
                                </div>
                                <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-eye text-blue-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Active Users -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-teal-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Active Users (7 days)</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $stats['active_users']; ?></h3>
                                    <p class="text-teal-600 text-xs mt-2">Recently logged in</p>
                                </div>
                                <div class="w-12 h-12 bg-teal-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-user-check text-teal-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Conversion Rate -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-indigo-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Conversion Rate</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo number_format(($stats['total_customers'] / max($stats['total_visitors'], 1)) * 100, 1); ?>%</h3>
                                    <p class="text-indigo-600 text-xs mt-2">Visitor to customer</p>
                                </div>
                                <div class="w-12 h-12 bg-indigo-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-percentage text-indigo-600 text-xl"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Additional Metrics Row -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                        <!-- Completed Intakes -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-pink-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Completed Intakes</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2"><?php echo $stats['total_intakes']; ?></h3>
                                    <p class="text-pink-600 text-xs mt-2">Health assessments</p>
                                </div>
                                <div class="w-12 h-12 bg-pink-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-notes-medical text-pink-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Avg Session Duration -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-purple-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Avg Session Duration</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2">5:32</h3>
                                    <p class="text-purple-600 text-xs mt-2">Minutes per visit</p>
                                </div>
                                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-clock text-purple-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Bounce Rate -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-red-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Bounce Rate</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2">28.5%</h3>
                                    <p class="text-red-600 text-xs mt-2">↓ 5% improvement</p>
                                </div>
                                <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-sign-out-alt text-red-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Avg Order Value -->
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-yellow-500">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-gray-600 text-sm font-medium">Avg Order Value</p>
                                    <h3 class="text-3xl font-bold text-gray-900 mt-2">$<?php echo number_format($stats['total_revenue'] / max($stats['total_customers'], 1), 2); ?></h3>
                                    <p class="text-yellow-600 text-xs mt-2">Per customer</p>
                                </div>
                                <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-coins text-yellow-600 text-xl"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activity Section -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- Recent Bookings -->
                        <div class="lg:col-span-2 bg-white rounded-lg shadow p-6">
                            <div class="flex items-center justify-between mb-6">
                                <h2 class="text-lg font-bold text-gray-900">Recent Bookings</h2>
                                <a href="/atasteofafricanmarketplace/dashboard/admin/bookings.php" class="text-emerald-600 hover:text-emerald-700 text-sm font-medium">View All</a>
                            </div>
                            <div class="space-y-4">
                                <?php if (!empty($stats['bookings'])): ?>
                                    <?php foreach ($stats['bookings'] as $booking): ?>
                                    <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                                        <div class="flex items-center gap-4">
                                            <div class="w-10 h-10 bg-emerald-100 rounded-full flex items-center justify-center">
                                                <i class="fas fa-user text-emerald-600"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo htmlspecialchars($booking['first_name'] . ' ' . $booking['last_name']); ?></p>
                                                <p class="text-sm text-gray-600">with <?php echo htmlspecialchars($booking['coach_name']); ?></p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p class="font-medium text-gray-900"><?php echo (new DateTime($booking['starts_at']))->format('M d, Y'); ?></p>
                                            <span class="inline-block px-2 py-1 bg-<?php echo $booking['status'] === 'scheduled' ? 'emerald' : ($booking['status'] === 'completed' ? 'emerald' : 'blue'); ?>-100 text-<?php echo $booking['status'] === 'scheduled' ? 'emerald' : ($booking['status'] === 'completed' ? 'emerald' : 'blue'); ?>-700 text-xs font-semibold rounded"><?php echo ucfirst($booking['status']); ?></span>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <p class="text-gray-600 text-center py-8">No bookings yet</p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Quick Actions -->
                        <div class="bg-white rounded-lg shadow p-6">
                            <h2 class="text-lg font-bold text-gray-900 mb-6">Quick Actions</h2>
                            <div class="space-y-3">
                                <a href="/atasteofafricanmarketplace/dashboard/admin/products.php" class="w-full flex items-center gap-3 px-4 py-3 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 rounded-lg transition-colors font-medium">
                                    <i class="fas fa-plus-circle"></i>
                                    <span>Add Product</span>
                                </a>
                                <a href="/atasteofafricanmarketplace/dashboard/admin/customers.php" class="w-full flex items-center gap-3 px-4 py-3 bg-blue-50 hover:bg-blue-100 text-blue-700 rounded-lg transition-colors font-medium">
                                    <i class="fas fa-user-plus"></i>
                                    <span>View Customers</span>
                                </a>
                                <a href="/atasteofafricanmarketplace/dashboard/admin/sales.php" class="w-full flex items-center gap-3 px-4 py-3 bg-purple-50 hover:bg-purple-100 text-purple-700 rounded-lg transition-colors font-medium">
                                    <i class="fas fa-chart-line"></i>
                                    <span>View Sales</span>
                                </a>
                                <a href="/atasteofafricanmarketplace/dashboard/admin/analytics.php" class="w-full flex items-center gap-3 px-4 py-3 bg-orange-50 hover:bg-orange-100 text-orange-700 rounded-lg transition-colors font-medium">
                                    <i class="fas fa-chart-pie"></i>
                                    <span>View Analytics</span>
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Additional Dashboard Sections -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
                        <!-- Recent Intake Forms -->
                        <div class="bg-white rounded-lg shadow p-6">
                            <div class="flex items-center justify-between mb-6">
                                <h2 class="text-lg font-bold text-gray-900">Recent Intake Forms</h2>
                                <span class="text-emerald-600 hover:text-emerald-700 text-sm font-medium cursor-pointer">View All</span>
                            </div>
                            <div class="space-y-3">
                                <?php if (!empty($stats['intakes'])): ?>
                                    <?php foreach ($stats['intakes'] as $intake): ?>
                                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 bg-pink-100 rounded-full flex items-center justify-center">
                                                <i class="fas fa-file-medical text-pink-600"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo htmlspecialchars($intake['first_name'] . ' ' . $intake['last_name']); ?></p>
                                                <p class="text-sm text-gray-600"><?php echo htmlspecialchars($intake['email']); ?></p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p class="text-sm text-gray-600"><?php echo (new DateTime($intake['created_at']))->format('M d, H:i'); ?></p>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <p class="text-gray-600 text-center py-8">No intake forms yet</p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Top Selling Products -->
                        <div class="bg-white rounded-lg shadow p-6">
                            <div class="flex items-center justify-between mb-6">
                                <h2 class="text-lg font-bold text-gray-900">Top Products</h2>
                                <a href="/atasteofafricanmarketplace/dashboard/admin/products.php" class="text-emerald-600 hover:text-emerald-700 text-sm font-medium">View All</a>
                            </div>
                            <div class="space-y-3">
                                <?php if (!empty($stats['top_products'])): ?>
                                    <?php foreach ($stats['top_products'] as $product): ?>
                                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 bg-emerald-100 rounded-lg flex items-center justify-center">
                                                <i class="fas fa-box text-emerald-600"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium text-gray-900"><?php echo htmlspecialchars($product['name']); ?></p>
                                                <p class="text-sm text-gray-600"><?php echo $product['total_sold']; ?> sold</p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <p class="font-bold text-emerald-600">$<?php echo number_format($product['revenue'], 2); ?></p>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <p class="text-gray-600 text-center py-8">No sales data yet</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- System Health & Visitor Traffic Chart -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-6">
                        <!-- Visitor Traffic Figures -->
                        <div class="lg:col-span-2 bg-white rounded-lg shadow p-6">
                            <div class="flex items-center justify-between mb-6">
                                <div>
                                    <h2 class="text-lg font-bold text-gray-900">Site Visitors - Last 30 Days</h2>
                                    <p class="text-sm text-gray-600 mt-1">Total unique visitors and sessions</p>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-6">
                                <div class="bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-lg p-6">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-cyan-500 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-users text-white text-xl"></i>
                                        </div>
                                        <div>
                                            <p class="text-sm text-gray-600">Total Visitors</p>
                                            <p class="text-3xl font-bold text-gray-900" id="total-visitors">0</p>
                                            <p class="text-xs text-gray-600 mt-1">Unique users</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-lg p-6">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-emerald-500 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-chart-bar text-white text-xl"></i>
                                        </div>
                                        <div>
                                            <p class="text-sm text-gray-600">Total Sessions</p>
                                            <p class="text-3xl font-bold text-gray-900" id="total-sessions">0</p>
                                            <p class="text-xs text-gray-600 mt-1">User sessions</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-8">
                                <h3 class="text-md font-semibold text-gray-900 mb-4">Daily Breakdown</h3>
                                <div class="space-y-2 max-h-48 overflow-y-auto">
                                    <div id="visitor-list" class="text-sm text-gray-600">Loading...</div>
                                </div>
                            </div>
                        </div>

                        <!-- Revenue Chart (replaced from above) -->
                        <div class="bg-white rounded-lg shadow p-6">
                            <div class="flex items-center justify-between mb-6">
                                <h2 class="text-lg font-bold text-gray-900">Revenue</h2>
                                <select class="text-sm border border-gray-300 rounded px-2 py-1">
                                    <option>7 days</option>
                                </select>
                            </div>
                            <div class="h-56 flex items-end justify-between gap-1">
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 45%;" title="$450"></div>
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 65%;" title="$780"></div>
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 55%;" title="$650"></div>
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 80%;" title="$920"></div>
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 70%;" title="$840"></div>
                                <div class="flex-1 bg-emerald-200 rounded-t hover:bg-emerald-300 transition-colors cursor-pointer" style="height: 90%;" title="$1.1k"></div>
                                <div class="flex-1 bg-emerald-300 rounded-t hover:bg-emerald-400 transition-colors cursor-pointer" style="height: 100%;" title="$1.3k"></div>
                            </div>
                            <div class="text-center mt-3 text-2xl font-bold text-gray-900">$5,990</div>
                            <div class="text-center text-sm text-gray-600">This week</div>
                        </div>
                    </div>

                    <!-- System Health moved below -->
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-6">
                        <!-- System Health -->
                        <div class="bg-white rounded-lg shadow p-6">
                            <h2 class="text-lg font-bold text-gray-900 mb-6">System Health</h2>
                            <div class="space-y-4">
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-sm text-gray-600">Server Status</span>
                                        <span class="text-sm font-semibold text-emerald-600">Online</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-emerald-500 h-2 rounded-full" style="width: 100%"></div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-sm text-gray-600">Database</span>
                                        <span class="text-sm font-semibold text-emerald-600">Healthy</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-emerald-500 h-2 rounded-full" style="width: 98%"></div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-sm text-gray-600">Storage Used</span>
                                        <span class="text-sm font-semibold text-yellow-600">45%</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-yellow-500 h-2 rounded-full" style="width: 45%"></div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-sm text-gray-600">API Response</span>
                                        <span class="text-sm font-semibold text-emerald-600">Fast</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-emerald-500 h-2 rounded-full" style="width: 92%"></div>
                                    </div>
                                </div>
                                <div class="pt-4 border-t border-gray-200">
                                    <div class="flex items-center gap-2 text-sm text-gray-600">
                                        <i class="fas fa-clock text-emerald-600"></i>
                                        <span>Last check: Just now</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </main>
        </div>
    </div>
    <script>
    // Visitor Traffic Figures
    const visitorData = <?php echo json_encode($stats['visitor_data']); ?>;
    
    // Calculate totals
    let totalVisitors = 0;
    let totalSessions = 0;
    const dailyList = [];
    
    visitorData.forEach(d => {
        const visitors = parseInt(d.total_users) || 0;
        const sessions = parseInt(d.total_sessions) || 0;
        totalVisitors += visitors;
        totalSessions += sessions;
        
        const date = new Date(d.date);
        const dateStr = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', weekday: 'short' });
        dailyList.push({ date: dateStr, visitors, sessions });
    });
    
    // Update total figures
    document.getElementById('total-visitors').textContent = totalVisitors.toLocaleString();
    document.getElementById('total-sessions').textContent = totalSessions.toLocaleString();
    
    // Display daily breakdown
    const visitorListEl = document.getElementById('visitor-list');
    visitorListEl.innerHTML = dailyList.map(d => `
        <div class="flex justify-between items-center p-2 hover:bg-gray-50 rounded transition-colors">
            <span class="text-gray-600">${d.date}</span>
            <div class="flex gap-6">
                <div class="flex items-center gap-2">
                    <span class="text-xs text-cyan-600 font-semibold">${d.visitors.toLocaleString()}</span>
                    <span class="text-xs text-gray-500">visitors</span>
                </div>
                <div class="flex items-center gap-2">
                    <span class="text-xs text-emerald-600 font-semibold">${d.sessions.toLocaleString()}</span>
                    <span class="text-xs text-gray-500">sessions</span>
                </div>
            </div>
        </div>
    `).join('');
    
    function toggleCatalog(event) {
        event.preventDefault();
        const submenu = document.getElementById('catalog-submenu');
        const chevron = document.getElementById('catalog-chevron');
        
        if (submenu.classList.contains('hidden')) {
            submenu.classList.remove('hidden');
            chevron.classList.remove('fa-chevron-down');
            chevron.classList.add('fa-chevron-up');
        } else {
            submenu.classList.add('hidden');
            chevron.classList.remove('fa-chevron-up');
            chevron.classList.add('fa-chevron-down');
        }
    }
    </script></body>
</html>