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

requireLogin();
requireAnyRole(['admin','super_admin']);

$db = Database::getInstance();
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $courseId = (int)($_POST['course_id'] ?? 0);
    $instructorId = (int)($_POST['instructor_id'] ?? 0);
    $region = trim($_POST['region'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $maxCapacity = trim($_POST['max_capacity'] ?? '');
    $start = trim($_POST['start_date'] ?? '');
    $end = trim($_POST['end_date'] ?? '');
    $status = trim($_POST['status'] ?? 'open');
    $cohortType = trim($_POST['cohort_type'] ?? '');

    if ($courseId <= 0) {
        $errors[] = 'Course is required.';
    }
    if ($instructorId <= 0) {
        $errors[] = 'Instructor is required.';
    }
    if ($region === '') {
        $errors[] = 'Region is required.';
    }

    $startDate = $start !== '' ? date('Y-m-d H:i:s', strtotime($start)) : null;
    $endDate = $end !== '' ? date('Y-m-d H:i:s', strtotime($end)) : null;
    $maxCapacityVal = $maxCapacity !== '' ? (int)$maxCapacity : null;

    if (empty($errors)) {
        try {
            $db->insert('cohorts', [
                'course_id' => $courseId,
                'instructor_id' => $instructorId,
                'region' => $region,
                'cohort_type' => $cohortType !== '' ? $cohortType : null,
                'title' => $title !== '' ? $title : null,
                'max_capacity' => $maxCapacityVal,
                'start_date' => $startDate,
                'end_date' => $endDate,
                'status' => $status,
                'created_at' => formatDate()
            ]);

            setFlashMessage('success', 'Cohort created successfully.');
            header('Location: cohorts.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$courses = $db->getAll("SELECT id, title FROM courses ORDER BY title");
$instructors = $db->getAll(
    "SELECT u.id, u.first_name, u.last_name
       FROM users u
       JOIN user_roles ur ON ur.user_id = u.id
      WHERE ur.role = 'instructor' AND ur.is_active = 1
   ORDER BY u.first_name, u.last_name"
);

$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
       JOIN users u ON coh.instructor_id = u.id
   ORDER BY coh.created_at DESC",
    []
);

$pageTitle = 'Cohorts';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Cohorts</h1>
    <p class="text-muted mb-0">Manage course cohorts, capacity, and schedules.</p>
  </div>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<div class="card mb-4">
  <div class="card-header">Create New Cohort</div>
  <div class="card-body">
    <form method="post" class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Course</label>
        <select name="course_id" class="form-select" required>
          <option value="">Select course</option>
          <?php foreach ($courses as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo ((int)($_POST['course_id'] ?? 0) === (int)$c['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Instructor</label>
        <select name="instructor_id" class="form-select" required>
          <option value="">Select instructor</option>
          <?php foreach ($instructors as $i): ?>
            <option value="<?php echo (int)$i['id']; ?>" <?php echo ((int)($_POST['instructor_id'] ?? 0) === (int)$i['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars(trim(($i['first_name'] ?? '') . ' ' . ($i['last_name'] ?? ''))); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Region</label>
        <select name="region" class="form-select" required>
          <?php foreach (['usa','europe','africa','global'] as $r): ?>
            <option value="<?php echo $r; ?>" <?php echo (($_POST['region'] ?? '') === $r) ? 'selected' : ''; ?>><?php echo strtoupper($r); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Title (optional)</label>
        <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($_POST['title'] ?? ''); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Cohort Type (optional)</label>
        <input type="text" name="cohort_type" class="form-control" maxlength="50" placeholder="e.g. evening, weekend, bootcamp" value="<?php echo htmlspecialchars($_POST['cohort_type'] ?? ''); ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Max Capacity (optional)</label>
        <input type="number" name="max_capacity" class="form-control" min="0" value="<?php echo htmlspecialchars($_POST['max_capacity'] ?? ''); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">Start Date (optional)</label>
        <input type="datetime-local" name="start_date" class="form-control" value="<?php echo htmlspecialchars($_POST['start_date'] ?? ''); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">End Date (optional)</label>
        <input type="datetime-local" name="end_date" class="form-control" value="<?php echo htmlspecialchars($_POST['end_date'] ?? ''); ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <?php foreach (['open','ongoing','closed','completed'] as $s): ?>
            <option value="<?php echo $s; ?>" <?php echo (($_POST['status'] ?? 'open') === $s) ? 'selected' : ''; ?>><?php echo ucfirst($s); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-12 text-end">
        <button class="btn btn-primary">Create Cohort</button>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-header">Existing Cohorts</div>
  <div class="card-body">
    <?php if (empty($cohorts)): ?>
      <p class="text-muted mb-0">No cohorts defined yet.</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>Cohort Type</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 isset($row['cohort_type']) && $row['cohort_type'] !== '' ? htmlspecialchars($row['cohort_type']) : ''; ?></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-<?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>

<?php include __DIR__ . '/includes/footer.php'; ?>
