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

$pageTitle = 'Analytics';
$pageSection = 'analytics';

hw_require_auth(['admin']);
$user = hw_get_auth_user();
?>
<!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"></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 -->
                <a href="/atasteofafricanmarketplace/dashboard/admin/" 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-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 bg-emerald-700 text-white">
                    <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">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">Analytics Dashboard</h1>
                        <p class="text-sm text-gray-600 mt-1">Platform analytics and reporting</p>
                    </div>
                    <div class="flex gap-2">
                        <select id="date-range" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent">
                            <option value="7">Last 7 days</option>
                            <option value="30">Last 30 days</option>
                            <option value="90">Last 90 days</option>
                        </select>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <main class="flex-1 overflow-auto p-8">
      <div class="space-y-6">
        <!-- Key Metrics -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="bg-white p-6 rounded-lg shadow border-l-4 border-blue-500">
            <h3 class="font-semibold text-gray-600 text-sm mb-2">Total Users</h3>
            <p id="total-users" class="text-3xl font-bold text-gray-900">-</p>
            <p id="users-change" class="text-sm text-green-600 mt-1">-</p>
          </div>
          <div class="bg-white p-6 rounded-lg shadow border-l-4 border-emerald-500">
            <h3 class="font-semibold text-gray-600 text-sm mb-2">Revenue</h3>
            <p id="total-revenue" class="text-3xl font-bold text-gray-900">-</p>
            <p id="revenue-change" class="text-sm text-green-600 mt-1">-</p>
          </div>
          <div class="bg-white p-6 rounded-lg shadow border-l-4 border-purple-500">
            <h3 class="font-semibold text-gray-600 text-sm mb-2">Appointments</h3>
            <p id="total-appointments" class="text-3xl font-bold text-gray-900">-</p>
            <p id="appointments-change" class="text-sm text-green-600 mt-1">-</p>
          </div>
          <div class="bg-white p-6 rounded-lg shadow border-l-4 border-orange-500">
            <h3 class="font-semibold text-gray-600 text-sm mb-2">Active Users</h3>
            <p id="active-users" class="text-3xl font-bold text-gray-900">-</p>
            <p id="active-change" class="text-sm text-green-600 mt-1">-</p>
          </div>
        </div>

        <!-- Charts -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- Revenue Chart -->
          <div class="bg-white p-6 rounded-lg shadow">
            <h3 class="font-bold text-gray-900 mb-4">Revenue Trend</h3>
            <canvas id="revenue-chart" width="400" height="200"></canvas>
          </div>
          
          <!-- User Growth Chart -->
          <div class="bg-white p-6 rounded-lg shadow">
            <h3 class="font-bold text-gray-900 mb-4">User Growth</h3>
            <canvas id="users-chart" width="400" height="200"></canvas>
          </div>
        </div>

        <!-- Top Coaches -->
        <div class="bg-white p-6 rounded-lg shadow">
          <h3 class="font-bold text-gray-900 mb-4">Top Performing Coaches</h3>
          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr class="border-b border-gray-200">
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Coach</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Sessions</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Revenue</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Rating</th>
                </tr>
              </thead>
              <tbody id="coaches-table">
                <!-- Coaches data will be loaded here -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
            </main>
        </div>
    </div>

<script>
let revenueChart, usersChart;

// Load analytics data
async function loadAnalytics() {
  try {
    const response = await fetch('/atasteofafricanmarketplace/api/analytics/data.php?type=overview');
    const data = await response.json();
    
    if (data.success) {
      updateMetrics(data.latest, data.trend);
      updateCharts(data.trend);
    }
    
    // Load coaches data
    const coachResponse = await fetch('/atasteofafricanmarketplace/api/analytics/data.php?type=coaches');
    const coachData = await coachResponse.json();
    
    if (coachData.success) {
      updateCoachesTable(coachData.coaches);
    }
  } catch (error) {
    console.error('Error loading analytics:', error);
  }
}

// Update metrics
function updateMetrics(latest, trend) {
  document.getElementById('total-users').textContent = latest.total_users.toLocaleString();
  document.getElementById('total-revenue').textContent = '$' + latest.total_revenue.toLocaleString();
  document.getElementById('total-appointments').textContent = latest.total_appointments.toLocaleString();
  document.getElementById('active-users').textContent = latest.active_users.toLocaleString();
  
  // Calculate changes
  if (trend.length >= 2) {
    const prev = trend[trend.length - 2];
    const userChange = ((latest.total_users - prev.total_users) / prev.total_users * 100).toFixed(1);
    const revenueChange = ((latest.total_revenue - prev.total_revenue) / prev.total_revenue * 100).toFixed(1);
    
    document.getElementById('users-change').textContent = `${userChange > 0 ? '+' : ''}${userChange}% from yesterday`;
    document.getElementById('revenue-change').textContent = `${revenueChange > 0 ? '+' : ''}${revenueChange}% from yesterday`;
  }
}

// Update charts
function updateCharts(trend) {
  const labels = trend.map(d => new Date(d.date).toLocaleDateString());
  const revenueData = trend.map(d => parseFloat(d.total_revenue));
  const usersData = trend.map(d => parseInt(d.total_users));
  
  // Revenue Chart
  const revenueCtx = document.getElementById('revenue-chart').getContext('2d');
  if (revenueChart) revenueChart.destroy();
  revenueChart = new Chart(revenueCtx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'Revenue',
        data: revenueData,
        borderColor: '#10B981',
        backgroundColor: 'rgba(16, 185, 129, 0.1)',
        tension: 0.4
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value) {
              return '$' + value.toLocaleString();
            }
          }
        }
      }
    }
  });
  
  // Users Chart
  const usersCtx = document.getElementById('users-chart').getContext('2d');
  if (usersChart) usersChart.destroy();
  usersChart = new Chart(usersCtx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'Total Users',
        data: usersData,
        borderColor: '#3B82F6',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.4
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
}

// Update coaches table
function updateCoachesTable(coaches) {
  const tbody = document.getElementById('coaches-table');
  tbody.innerHTML = coaches.map(coach => `
    <tr class="border-b border-gray-100 hover:bg-gray-50">
      <td class="py-3 px-4">${coach.first_name} ${coach.last_name}</td>
      <td class="py-3 px-4">${coach.total_sessions || 0}</td>
      <td class="py-3 px-4">$${parseFloat(coach.total_revenue || 0).toLocaleString()}</td>
      <td class="py-3 px-4">${coach.avg_rating ? '⭐ ' + parseFloat(coach.avg_rating).toFixed(1) : 'N/A'}</td>
    </tr>
  `).join('');
}

// Initialize
loadAnalytics();
</script>
</body>
</html>