<?php
require_once __DIR__ . '/../../config/database.php';

requireLogin();
requireAnyRole(['regional_admin']);

$user = getCurrentUser();
if (!$user) {
    redirect('../login.php');
}

// Region-scoped statistics
$db = Database::getInstance();
$rfCourses = currentRegionFilter('c');
$rfUsers = currentRegionFilter('u');

$stats = [
  'courses' => 0,
  'users' => 0,
  'enrollments' => 0,
  'revenue' => 0.0,
];

// Courses in region (published)
$row = $db->get(
  "SELECT COUNT(*) AS cnt FROM courses c WHERE {$rfCourses['clause']} AND c.status = 'published'",
  $rfCourses['params']
);
$stats['courses'] = (int)($row['cnt'] ?? 0);

// Active users in region
$row = $db->get(
  "SELECT COUNT(*) AS cnt FROM users u WHERE {$rfUsers['clause']} AND u.status = 'active'",
  $rfUsers['params']
);
$stats['users'] = (int)($row['cnt'] ?? 0);

// Enrollments for courses in region
$row = $db->get(
  "SELECT COUNT(*) AS cnt
   FROM course_enrollments ce
   JOIN courses c ON ce.course_id = c.id
   WHERE {$rfCourses['clause']}",
  $rfCourses['params']
);
$stats['enrollments'] = (int)($row['cnt'] ?? 0);

// Revenue from payments for courses in region (completed)
$row = $db->get(
  "SELECT COALESCE(SUM(p.amount), 0) AS total
   FROM payments p
   JOIN courses c ON p.course_id = c.id
   WHERE {$rfCourses['clause']} AND p.payment_status = 'completed'",
  $rfCourses['params']
);
$stats['revenue'] = (float)($row['total'] ?? 0);

$currentPage = basename($_SERVER['PHP_SELF']);
$currentUser = $user;
$pageTitle = 'Regional Admin Dashboard';
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - SmartThink</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" crossorigin href="<?php echo APP_URL; ?>/smlms/dist-modern/assets/main-BQhM7myw.css">

    <script>
        (function() {
            try {
                localStorage.setItem('theme', 'light');
            } catch (e) {}
            document.documentElement.setAttribute('data-bs-theme', 'light');
        })();
    </script>

    <script type="module" crossorigin src="<?php echo APP_URL; ?>/smlms/dist-modern/assets/vendor-bootstrap-C9iorZI5.js"></script>
    <script type="module" crossorigin src="<?php echo APP_URL; ?>/smlms/dist-modern/assets/vendor-charts-DGwYAWel.js"></script>
    <script type="module" crossorigin src="<?php echo APP_URL; ?>/smlms/dist-modern/assets/vendor-ui-CflGdlft.js"></script>
    <script type="module" crossorigin src="<?php echo APP_URL; ?>/smlms/dist-modern/assets/main-B24LRf0x.js"></script>
</head>
<body data-page="regional-admin-dashboard" class="admin-layout">

    <div id="loading-screen" class="loading-screen">
        <div class="loading-spinner">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
    </div>

    <div class="admin-wrapper" id="admin-wrapper">

        <header class="admin-header">
            <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom">
                <div class="container-fluid">
                    <a class="navbar-brand d-flex align-items-center" href="../dashboard.php">
                        <img src="<?php echo APP_URL; ?>/assets/images/logo.jpeg" alt="SmartThink" height="32" class="d-inline-block align-text-top me-2">
                        <h1 class="h4 mb-0 fw-bold text-primary">SmartThink LMS</h1>
                    </a>

                    <button class="hamburger-menu" type="button" data-sidebar-toggle aria-label="Toggle sidebar">
                        <i class="bi bi-list"></i>
                    </button>

                    <div class="navbar-nav ms-auto flex-row align-items-center">
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary d-flex align-items-center" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <span class="rounded-circle bg-primary text-white d-inline-flex justify-content-center align-items-center me-2" style="width:32px;height:32px;">
                                    <?php
                                    $initials = '';
                                    if (!empty($currentUser['first_name']) || !empty($currentUser['last_name'])) {
                                        $initials = strtoupper(substr($currentUser['first_name'] ?? '', 0, 1) . substr($currentUser['last_name'] ?? '', 0, 1));
                                    } else {
                                        $initials = strtoupper(substr($_SESSION['username'] ?? 'U', 0, 2));
                                    }
                                    echo htmlspecialchars($initials);
                                    ?>
                                </span>
                                <span class="d-none d-md-inline">
                                    <?php
                                    $fullName = trim(($currentUser['first_name'] ?? '') . ' ' . ($currentUser['last_name'] ?? ''));
                                    echo htmlspecialchars($fullName !== '' ? $fullName : ($_SESSION['username'] ?? 'Regional Admin'));
                                    ?>
                                </span>
                                <i class="bi bi-chevron-down ms-1"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><h6 class="dropdown-header">Account</h6></li>
                                <li><a class="dropdown-item" href="../profile.php"><i class="bi bi-person me-2"></i>Profile</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="../logout.php"><i class="bi bi-box-arrow-right me-2"></i>Logout</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </nav>
        </header>

        <aside class="admin-sidebar" id="admin-sidebar">
            <div class="sidebar-content">
                <nav class="sidebar-nav">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="../dashboard.php">
                                <i class="bi bi-house"></i>
                                <span>Student Dashboard</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../courses.php">
                                <i class="bi bi-book"></i>
                                <span>Browse Courses</span>
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <small class="text-muted px-3 text-uppercase fw-bold">Regional</small>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $currentPage === 'regional_admin.php' ? 'active' : ''; ?>" href="regional_admin.php">
                                <i class="bi bi-geo-alt"></i>
                                <span>Regional Dashboard</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $currentPage === 'regional_cohorts.php' ? 'active' : ''; ?>" href="regional_cohorts.php">
                                <i class="bi bi-people"></i>
                                <span>Regional Cohorts</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../enrollments.php">
                                <i class="bi bi-people"></i>
                                <span>Enrollments</span>
                            </a>
                        </li>
                        <?php if (hasRole('admin') || hasRole('super_admin')): ?>
                        <li class="nav-item mt-3">
                            <small class="text-muted px-3 text-uppercase fw-bold">Admin</small>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../../cms/dashboard.php">
                                <i class="bi bi-sliders"></i>
                                <span>Admin Panel</span>
                            </a>
                        </li>
                        <?php endif; ?>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="../logout.php">
                                <i class="bi bi-box-arrow-right"></i>
                                <span>Logout</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </aside>

        <div class="sidebar-backdrop" aria-hidden="true"></div>

        <main class="admin-main">
            <div class="container-fluid p-4 p-lg-5">
                <div class="container-xxl">
                    <div class="row gy-6">
  <div class="col-12">
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <div>
          <h5 class="card-title mb-0">Welcome, <?php echo htmlspecialchars($user['first_name'] ?? 'Regional Admin'); ?></h5>
          <small class="text-body-secondary">Manage your region's courses, users and enrollments</small>
        </div>
        <span class="badge bg-label-primary">Region: <?php echo htmlspecialchars($_SESSION['region'] ?? DEFAULT_REGION); ?></span>
      </div>
      <div class="card-body">
        <div class="row g-6">
          <div class="col-sm-6 col-lg-3">
            <div class="d-flex align-items-center">
              <div class="avatar">
                <div class="avatar-initial bg-primary rounded shadow-xs"><i class="icon-base ri ri-book-open-line icon-24px"></i></div>
              </div>
              <div class="ms-3">
                <p class="mb-0">Courses (region)</p>
                <h5 class="mb-0"><?php echo number_format($stats['courses']); ?></h5>
              </div>
            </div>
          </div>
          <div class="col-sm-6 col-lg-3">
            <div class="d-flex align-items-center">
              <div class="avatar">
                <div class="avatar-initial bg-success rounded shadow-xs"><i class="icon-base ri ri-user-3-line icon-24px"></i></div>
              </div>
              <div class="ms-3">
                <p class="mb-0">Active Users</p>
                <h5 class="mb-0"><?php echo number_format($stats['users']); ?></h5>
              </div>
            </div>
          </div>
          <div class="col-sm-6 col-lg-3">
            <div class="d-flex align-items-center">
              <div class="avatar">
                <div class="avatar-initial bg-warning rounded shadow-xs"><i class="icon-base ri ri-task-line icon-24px"></i></div>
              </div>
              <div class="ms-3">
                <p class="mb-0">Enrollments</p>
                <h5 class="mb-0"><?php echo number_format($stats['enrollments']); ?></h5>
              </div>
            </div>
          </div>
          <div class="col-sm-6 col-lg-3">
            <div class="d-flex align-items-center">
              <div class="avatar">
                <div class="avatar-initial bg-info rounded shadow-xs"><i class="icon-base ri ri-bar-chart-2-line icon-24px"></i></div>
              </div>
              <div class="ms-3">
                <p class="mb-0">Revenue</p>
                <h5 class="mb-0">$<?php echo number_format($stats['revenue'], 2); ?></h5>
              </div>
            </div>
          </div>
        </div>
        <div class="mt-4">
          <a href="../courses.php" class="btn btn-primary btn-sm me-2">Manage Courses</a>
          <a href="../dashboard.php" class="btn btn-outline-primary btn-sm">Back to Student View</a>
        </div>
      </div>
    </div>
  </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

</body>
</html>

