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

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

$db = Database::getInstance();

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$course = isset($_GET['course']) ? (int)$_GET['course'] : 0;
$student = isset($_GET['student']) ? (int)$_GET['student'] : 0;
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'ce.status = ?';
    $params[] = $status;
}
if ($course > 0) {
    $where[] = 'ce.course_id = ?';
    $params[] = $course;
}
if ($student > 0) {
    $where[] = 'ce.student_id = ?';
    $params[] = $student;
}
if ($q !== '') {
    $where[] = '(c.title LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR CONCAT_WS(" ", u.first_name, u.last_name) LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$enrollments = $db->getAll(
    "SELECT ce.*, c.title AS course_title, u.username, u.email, u.first_name, u.last_name,
            (SELECT COUNT(*) FROM course_modules WHERE course_id = c.id) AS module_count,
            (SELECT COUNT(*) FROM lesson_progress lp
             JOIN course_lessons cl ON lp.lesson_id = cl.id
             WHERE lp.enrollment_id = ce.id AND lp.status = 'completed') AS completed_lessons
     FROM course_enrollments ce
     JOIN courses c ON ce.course_id = c.id
     JOIN users u ON ce.student_id = u.id
     $whereSql
     ORDER BY ce.enrollment_date DESC
     LIMIT 200",
    $params
);

$courses = $db->getAll("SELECT id, title FROM courses ORDER BY title");
$students = $db->getAll(
    "SELECT u.id, u.username, u.first_name, u.last_name
     FROM users u
     JOIN user_roles ur ON u.id = ur.user_id
     WHERE ur.role = 'student' AND u.status = 'active'
     ORDER BY u.last_name, u.first_name"
);

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Enrollments</h1>
    <p class="text-muted mb-0">Manage student enrollments and progress</p>
  </div>
  <div>
    <a href="enrollments_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>Enroll Student
    </a>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">All</option>
          <?php foreach (['active','completed','cancelled','suspended'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $status===$opt?'selected':''; ?>><?php echo ucfirst($opt); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Course</label>
        <select name="course" class="form-select">
          <option value="">All</option>
          <?php foreach ($courses as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo $course===$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Student</label>
        <select name="student" class="form-select">
          <option value="">All</option>
          <?php foreach ($students as $s): ?>
            <option value="<?php echo (int)$s['id']; ?>" <?php echo $student===$s['id']?'selected':''; ?>><?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name'] . ' (' . $s['username'] . ')'); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Search</label>
        <input type="text" name="q" class="form-control" placeholder="course, username, email, name" value="<?php echo htmlspecialchars($q); ?>">
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Student</th>
            <th>Course</th>
            <th>Status</th>
            <th>Progress</th>
            <th>Enrolled</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$enrollments): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">No enrollments found.</td></tr>
          <?php else: foreach ($enrollments as $e): ?>
            <tr>
              <td><?php echo (int)$e['id']; ?></td>
              <td>
                <div>
                  <strong><?php echo htmlspecialchars(($e['first_name'] ?? '') . ' ' . ($e['last_name'] ?? '')); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($e['username'] ?? ''); ?> &lt;<?php echo htmlspecialchars($e['email'] ?? ''); ?>&gt;</small>
                </div>
              </td>
              <td><?php echo htmlspecialchars($e['course_title'] ?? ''); ?></td>
              <td>
                <span class="badge bg-<?php echo $e['status']==='active'?'success':($e['status']==='completed'?'info':'secondary'); ?>">
                  <?php echo htmlspecialchars(ucfirst($e['status'] ?? '')); ?>
                </span>
              </td>
              <td>
                <div class="progress" style="height: 6px;">
                  <div class="progress-bar" style="width: <?php echo min(100, (float)($e['progress_percentage'] ?? 0)); ?>%"></div>
                </div>
                <small><?php echo (int)($e['completed_lessons'] ?? 0); ?>/<?php echo (int)($e['module_count'] ?? 0); ?> lessons</small>
              </td>
              <td><?php echo htmlspecialchars($e['enrollment_date'] ?? ''); ?></td>
              <td class="text-nowrap">
                <a href="enrollments_edit.php?id=<?php echo (int)$e['id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                  <i class="fas fa-edit"></i>
                </a>
                <a href="enrollments_view.php?id=<?php echo (int)$e['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">
                  <i class="fas fa-eye"></i>
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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