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

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

$db = Database::getInstance();

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
    $_SESSION['flash']['danger'] = 'Invalid enrollment ID.';
    header('Location: enrollments.php');
    exit;
}

$enrollment = $db->get(
    "SELECT ce.*, c.title AS course_title, c.description AS course_description,
            u.username, u.email, u.first_name, u.last_name, u.region,
            ins.first_name AS ins_first_name, ins.last_name AS ins_last_name
     FROM course_enrollments ce
     JOIN courses c ON ce.course_id = c.id
     JOIN users u ON ce.student_id = u.id
     LEFT JOIN users ins ON c.instructor_id = ins.id
     WHERE ce.id = ?",
    [$id]
);

if (!$enrollment) {
    $_SESSION['flash']['danger'] = 'Enrollment not found.';
    header('Location: enrollments.php');
    exit;
}

$modules = $db->getAll(
    "SELECT m.*, COUNT(l.id) AS lesson_count,
            (SELECT COUNT(*) FROM lesson_progress lp
             JOIN course_lessons cl ON lp.lesson_id = cl.id
             WHERE lp.enrollment_id = ? AND cl.module_id = m.id AND lp.status = 'completed') AS completed_lessons
     FROM course_modules m
     JOIN courses c ON m.course_id = c.id
     WHERE c.id = ?
     GROUP BY m.id
     ORDER BY m.sort_order",
    [$id, $enrollment['course_id']]
);

$certificates = $db->getAll(
    "SELECT * FROM certificates WHERE enrollment_id = ? AND is_revoked = 0",
    [$id]
);

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Enrollment Details</h1>
    <p class="text-muted mb-0">View student enrollment and progress</p>
  </div>
  <div>
    <a href="enrollments_edit.php?id=<?php echo $id; ?>" class="btn btn-primary me-2">
      <i class="fas fa-edit me-2"></i>Edit
    </a>
    <a href="enrollments.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Enrollments
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Student</h5>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Name</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars(($enrollment['first_name'] ?? '') . ' ' . ($enrollment['last_name'] ?? '')); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Username</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($enrollment['username'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Email</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($enrollment['email'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Region</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars(ucfirst($enrollment['region'] ?? '')); ?></div>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Course</h5>
      </div>
      <div class="card-body">
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Title</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($enrollment['course_title'] ?? ''); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Instructor</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars(($enrollment['ins_first_name'] ?? '') . ' ' . ($enrollment['ins_last_name'] ?? '')); ?></div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Status</strong></div>
          <div class="col-sm-9">
            <span class="badge bg-<?php echo $enrollment['status']==='active'?'success':($enrollment['status']==='completed'?'info':'secondary'); ?>">
              <?php echo htmlspecialchars(ucfirst($enrollment['status'] ?? '')); ?>
            </span>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Progress</strong></div>
          <div class="col-sm-9">
            <div class="progress" style="height: 6px;">
              <div class="progress-bar" style="width: <?php echo min(100, (float)($enrollment['progress_percentage'] ?? 0)); ?>%"></div>
            </div>
            <?php echo round((float)($enrollment['progress_percentage'] ?? 0), 1); ?>%
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-sm-3"><strong>Enrolled</strong></div>
          <div class="col-sm-9"><?php echo htmlspecialchars($enrollment['enrollment_date'] ?? ''); ?></div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row mt-4">
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Modules Progress</h5>
      </div>
      <div class="card-body">
        <?php if (!$modules): ?>
          <p class="text-muted">No modules in this course.</p>
        <?php else: foreach ($modules as $m): ?>
          <div class="border rounded p-3 mb-3">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <h6 class="mb-1"><?php echo htmlspecialchars($m['title'] ?? ''); ?></h6>
                <small class="text-muted"><?php echo (int)($m['lesson_count'] ?? 0); ?> lessons</small>
              </div>
              <div class="text-end">
                <small><?php echo (int)($m['completed_lessons'] ?? 0); ?>/<?php echo (int)($m['lesson_count'] ?? 0); ?> completed</small>
              </div>
            </div>
          </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>

  <div class="col-md-4">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">Certificates</h5>
      </div>
      <div class="card-body">
        <?php if (!$certificates): ?>
          <p class="text-muted">No certificates issued.</p>
        <?php else: foreach ($certificates as $c): ?>
          <div class="border rounded p-3 mb-2">
            <div>
              <strong><?php echo htmlspecialchars($c['certificate_name'] ?? ''); ?></strong><br>
              <small class="text-muted">Issued: <?php echo htmlspecialchars($c['issue_date'] ?? ''); ?></small>
            </div>
          </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>
</div>

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