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

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

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

$db = Database::getInstance();

$rfCourses = currentRegionFilter('c');

$cohorts = $db->getAll(
    "SELECT coh.*, c.title AS course_title,
            u.first_name, u.last_name,
            (SELECT COUNT(*) FROM course_enrollments ce WHERE ce.cohort_id = coh.id) AS enrolled_count
       FROM cohorts coh
       JOIN courses c ON coh.course_id = c.id
  LEFT JOIN users u ON coh.instructor_id = u.id
      WHERE {$rfCourses['clause']}
   ORDER BY coh.start_date IS NULL, coh.start_date ASC, coh.created_at DESC",
    $rfCourses['params']
);

$currentPage = basename($_SERVER['PHP_SELF']);
$currentUser = $user;
$pageTitle = 'Regional Cohorts';
?>
<!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-cohorts" 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">Regional Cohorts</h5>
                                        <small class="text-body-secondary">Cohorts for courses in your region</small>
                                    </div>
                                    <span class="badge bg-label-primary">Region: <?php echo htmlspecialchars($_SESSION['region'] ?? DEFAULT_REGION); ?></span>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($cohorts)): ?>
                                        <p class="text-muted mb-0">No cohorts found for this region.</p>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-striped align-middle">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>Course</th>
                                                        <th>Instructor</th>
                                                        <th>Region</th>
                                                        <th>Title</th>
                                                        <th>Start</th>
                                                        <th>End</th>
                                                        <th>Status</th>
                                                        <th>Enrollment</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($cohorts as $row): ?>
                                                        <tr>
                                                            <td><?php echo (int)$row['id']; ?></td>
                                                            <td><?php echo htmlspecialchars($row['course_title']); ?></td>
                                                            <td><?php echo htmlspecialchars(trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))); ?></td>
                                                            <td><?php echo htmlspecialchars(strtoupper($row['region'])); ?></td>
                                                            <td><?php echo htmlspecialchars($row['title'] ?: ''); ?></td>
                                                            <td><?php echo $row['start_date'] ? htmlspecialchars(date('M j, Y H:i', strtotime($row['start_date']))) : 'TBA'; ?></td>
                                                            <td><?php echo $row['end_date'] ? htmlspecialchars(date('M j, Y H:i', strtotime($row['end_date']))) : 'TBA'; ?></td>
                                                            <td>
                                                                <span class="badge bg-label-<?php echo $row['status'] === 'open' ? 'success' : ($row['status'] === 'ongoing' ? 'primary' : 'secondary'); ?>">
                                                                    <?php echo htmlspecialchars(ucfirst($row['status'])); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $max = isset($row['max_capacity']) && (int)$row['max_capacity'] > 0 ? (int)$row['max_capacity'] : null;
                                                                $enrolled = (int)($row['enrolled_count'] ?? 0);
                                                                echo $max ? ($enrolled . ' / ' . $max) : $enrolled;
                                                                ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

</body>
</html>
