<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "../user/db.php";

// Protect admin page
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

// Fetch stats from database
// 1. Students count
$studentsQuery = $conn->query("SELECT COUNT(*) AS total_students FROM users WHERE role='user'");
$students = $studentsQuery->fetch_assoc()['total_students'];

// 2. Courses count
$coursesQuery = $conn->query("SELECT COUNT(*) AS total_courses FROM courses");
$courses = $coursesQuery->fetch_assoc()['total_courses'];

// 3. Revenue (sum of successful payments)
$revenueQuery = $conn->query("SELECT SUM(amount) AS total_revenue FROM user_payments ");
$revenue = $revenueQuery->fetch_assoc()['total_revenue'];
if (!$revenue) $revenue = 0;

// 4. Purchases count
$purchasesQuery = $conn->query("SELECT COUNT(*) AS total_purchases FROM user_payments");
$purchases = $purchasesQuery->fetch_assoc()['total_purchases'];

// 5. Student growth (number of new students per month, last 6 months)
$growthData = [];
$monthLabels = [];
for ($i = 5; $i >= 0; $i--) {
    $month = date("Y-m", strtotime("-$i month"));
    $monthName = date("M", strtotime("-$i month"));
    $monthLabels[] = $monthName;

    $growthQuery = $conn->query("SELECT COUNT(*) AS count FROM users WHERE role='user' AND DATE_FORMAT(created_at, '%Y-%m') = '$month'");
    $growthData[] = $growthQuery->fetch_assoc()['count'];
}
?>

<!doctype html>
<html lang="en" class="scroll-smooth">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Admin Dashboard</title>

  <!-- Tailwind CDN -->
  <script src="https://cdn.tailwindcss.com"></script>

  <!-- Chart.js -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          colors: {
            primary: '#4f46e5',
            accent: '#22c55e'
          }
        }
      }
    }
  </script>

  <style>
    ::-webkit-scrollbar { width: 8px }
    ::-webkit-scrollbar-thumb { background: rgba(100,100,100,.35); border-radius: 8px }
  </style>
</head>

<body class="bg-slate-100 dark:bg-slate-950 text-slate-800 dark:text-slate-200">

<div class="min-h-screen flex relative">

  <!-- Mobile Overlay -->
  <div id="overlay" class="fixed inset-0 bg-black/40 z-20 hidden md:hidden"></div>

  <!-- SIDEBAR -->
  <aside id="sidebar"
    class="fixed md:static inset-y-0 left-0 z-30 w-64 bg-white dark:bg-slate-900 shadow-lg
           transform -translate-x-full md:translate-x-0 transition-all duration-300">

    <div class="flex flex-col h-full">
      <!-- Logo -->
      <div class="flex items-center gap-3 px-5 py-4 border-b dark:border-slate-800">
        <!--<div class="w-10 h-10 rounded-lg bg-primary text-white flex items-center justify-center font-bold">-->
        <!--  PM-->
        <!--</div>-->
        <div>
          <h2 class="font-semibold">Admin</h2>
          <p class="text-xs text-slate-500">Dashboard</p>
        </div>
      </div>

      <!-- Nav -->
      <nav class="flex-1 px-4 py-4 space-y-1">
        <a class="block px-3 py-2 rounded-md bg-indigo-50 text-primary font-medium dark:bg-indigo-500/10" href="#">Dashboard</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="courses.php"> Add Courses</a>
         <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="manage_course.php">Manage Courses</a>
          <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="course_outline.php"> Courses Outlines</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="announcements.php">Anouncements</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="messages.php">Messages</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="users.php">Students</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="payments.php">Purchases</a>
        <a class="block px-3 py-2 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800" href="#">Settings</a>
      </nav>

      <!-- Footer -->
      <div class="p-4 border-t dark:border-slate-800">
        <form method="post" action="logout.php">
          <button type="submit" class="w-full py-2 rounded-md bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 dark:hover:bg-slate-700 text-sm">
            Logout
          </button>
        </form>
      </div>
    </div>
  </aside>

  <!-- MAIN -->
  <div class="flex-1 md:ml-64">

    <!-- TOPBAR -->
    <header class="sticky top-0 z-10 bg-white dark:bg-slate-900 border-b dark:border-slate-800">
      <div class="flex items-center justify-between px-4 py-3">
        <div class="flex items-center gap-3">
          <button id="menuBtn" class="md:hidden p-2 rounded-md hover:bg-slate-200 dark:hover:bg-slate-800">
            ☰
          </button>
          <h1 class="font-semibold text-lg">Dashboard</h1>
        </div>

        <div class="flex items-center gap-3">
          <button id="themeToggle" class="p-2 rounded-md hover:bg-slate-200 dark:hover:bg-slate-800">
            🌓
          </button>
          <img class="w-9 h-9 rounded-full"
               src="https://ui-avatars.com/api/?name=Admin&background=4f46e5&color=fff">
        </div>
      </div>
    </header>

    <!-- CONTENT -->
    <main class="p-4 sm:p-6 space-y-6">

      <!-- CARDS -->
      <section class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow">
          <p class="text-sm text-slate-500">Students</p>
          <h3 class="text-2xl font-bold"><?= number_format($students) ?></h3>
        </div>

        <div class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow">
          <p class="text-sm text-slate-500">Courses</p>
          <h3 class="text-2xl font-bold"><?= number_format($courses) ?></h3>
        </div>

        <div class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow">
          <p class="text-sm text-slate-500">Revenue</p>
          <h3 class="text-2xl font-bold text-accent">₦<?= number_format($revenue) ?></h3>
        </div>

        <div class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow">
          <p class="text-sm text-slate-500">Purchases</p>
          <h3 class="text-2xl font-bold"><?= number_format($purchases) ?></h3>
        </div>
      </section>

      <!-- CHART -->
      <section class="bg-white dark:bg-slate-900 p-4 rounded-xl shadow">
        <h2 class="font-semibold mb-3">Student Growth</h2>
        <canvas id="growthChart" height="120"></canvas>
      </section>

    </main>
  </div>
</div>

<script>
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('overlay');
  const menuBtn = document.getElementById('menuBtn');

  menuBtn.onclick = () => {
    sidebar.classList.toggle('-translate-x-full');
    overlay.classList.toggle('hidden');
  };

  overlay.onclick = () => {
    sidebar.classList.add('-translate-x-full');
    overlay.classList.add('hidden');
  };

  const themeToggle = document.getElementById('themeToggle');
  themeToggle.onclick = () => {
    document.documentElement.classList.toggle('dark');
  };

  // Chart
  const ctx = document.getElementById('growthChart');
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: <?= json_encode($monthLabels) ?>,
      datasets: [{
        label: 'New Students',
        data: <?= json_encode($growthData) ?>,
        borderColor: '#4f46e5',
        backgroundColor: 'rgba(79,70,229,0.2)',
        borderWidth: 2,
        tension: 0.4,
        fill: true
      }]
    },
    options: {
      plugins: { legend: { display: false } },
      responsive: true
    }
  });
</script>

</body>
</html>
<?php include "footer.php"; ?>
