<?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;
}

$cohort = null;
if (!empty($enrollment['cohort_id'])) {
    $cohort = $db->get('SELECT * FROM cohorts WHERE id = ?', [$enrollment['cohort_id']]);
}

$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]
);

$agreement = $db->get(
    "SELECT * FROM course_enrollment_agreements WHERE enrollment_id = ? AND status = 'signed' ORDER BY signed_at DESC LIMIT 1",
    [$id]
);

$paymentPolicy = $db->get(
    "SELECT * FROM course_enrollment_payment_policies WHERE enrollment_id = ? ORDER BY accepted_at DESC LIMIT 1",
    [$id]
);

$privacyPolicy = $db->get(
    "SELECT * FROM course_enrollment_privacy_policies WHERE enrollment_id = ? ORDER BY accepted_at DESC LIMIT 1",
    [$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 class="row mb-0">
          <div class="col-sm-3"><strong>Cohort</strong></div>
          <div class="col-sm-9">
            <?php if ($cohort): ?>
              <?php
              $parts = [];
              $parts[] = 'ID ' . (int)$cohort['id'];
              if (!empty($cohort['title'])) {
                  $parts[] = $cohort['title'];
              }
              if (!empty($cohort['region'])) {
                  $parts[] = strtoupper($cohort['region']);
              }
              if (!empty($cohort['start_date'])) {
                  $parts[] = date('M j, Y', strtotime($cohort['start_date']));
              }
              echo htmlspecialchars(implode(' \\ ', $parts));
              ?>
            <?php else: ?>
              <span class="text-muted">Not assigned</span>
            <?php endif; ?>
          </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 class="card mt-3">
      <div class="card-header">
        <h5 class="mb-0">Agreements &amp; Policies</h5>
      </div>
      <div class="card-body">
        <h6 class="mb-2">Training Agreement</h6>
        <?php if (!$agreement): ?>
          <p class="text-muted mb-2">No signed training agreement recorded for this enrollment.</p>
        <?php else: ?>
          <div class="mb-2">
            <strong>Status:</strong>
            <span class="badge bg-success">Signed</span>
          </div>
          <div class="mb-2">
            <strong>Signed At:</strong>
            <?php echo htmlspecialchars($agreement['signed_at'] ?? ''); ?>
          </div>
          <a href="<?php echo APP_URL; ?>/lms/view_agreement.php?enrollment_id=<?php echo (int)$id; ?>" class="btn btn-sm btn-outline-secondary mb-3">
            View Full Details
          </a>
        <?php endif; ?>

        <hr class="my-3">

        <h6 class="mb-2">Non-Refundable Payment Policy</h6>
        <?php if (!$paymentPolicy): ?>
          <p class="text-muted mb-2">No payment policy acceptance recorded for this enrollment.</p>
        <?php else: ?>
          <div class="mb-2">
            <strong>Status:</strong>
            <span class="badge bg-<?php echo ($paymentPolicy['status'] ?? '') === 'accepted' ? 'success' : (($paymentPolicy['status'] ?? '') === 'revoked' ? 'danger' : 'secondary'); ?>">
              <?php echo htmlspecialchars(ucfirst($paymentPolicy['status'] ?? 'pending')); ?>
            </span>
          </div>
          <div class="mb-2">
            <strong>Accepted At:</strong>
            <?php echo htmlspecialchars($paymentPolicy['accepted_at'] ?? ''); ?>
          </div>
        <?php endif; ?>

        <hr class="my-3">

        <h6 class="mb-2">Data Privacy Policy</h6>
        <?php if (!$privacyPolicy): ?>
          <p class="text-muted mb-0">No privacy policy acceptance recorded for this enrollment.</p>
        <?php else: ?>
          <div class="mb-2">
            <strong>Status:</strong>
            <span class="badge bg-<?php echo ($privacyPolicy['status'] ?? '') === 'accepted' ? 'success' : (($privacyPolicy['status'] ?? '') === 'revoked' ? 'danger' : 'secondary'); ?>">
              <?php echo htmlspecialchars(ucfirst($privacyPolicy['status'] ?? 'pending')); ?>
            </span>
          </div>
          <div class="mb-2">
            <strong>Accepted At:</strong>
            <?php echo htmlspecialchars($privacyPolicy['accepted_at'] ?? ''); ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

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