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

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

$db = Database::getInstance();
$errors = [];
$success = false;
$enrollment = null;

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id > 0) {
    $enrollment = $db->get(
        "SELECT ce.*, c.title AS course_title, u.username, u.email, u.first_name, u.last_name
         FROM course_enrollments ce
         JOIN courses c ON ce.course_id = c.id
         JOIN users u ON ce.student_id = u.id
         WHERE ce.id = ?",
        [$id]
    );
    if (!$enrollment) {
        $_SESSION['flash']['danger'] = 'Enrollment not found.';
        header('Location: enrollments.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $studentId   = (int)($_POST['student_id'] ?? 0);
    $courseId    = (int)($_POST['course_id'] ?? 0);
    $status      = trim($_POST['status'] ?? 'active');
    $progress    = (float)($_POST['progress_percentage'] ?? 0);

    if ($studentId <= 0) {
        $errors[] = 'Please select a student.';
    }
    if ($courseId <= 0) {
        $errors[] = 'Please select a course.';
    }
    if (!in_array($status, ['active','completed','cancelled','suspended'], true)) {
        $errors[] = 'Invalid status.';
    }
    if ($progress < 0 || $progress > 100) {
        $errors[] = 'Progress must be between 0 and 100.';
    }

    // Prevent duplicate enrollment
    $existing = $db->get(
        "SELECT id FROM course_enrollments WHERE student_id = ? AND course_id = ? AND id != ?",
        [$studentId, $courseId, $id]
    );
    if ($existing) {
        $errors[] = 'Student is already enrolled in this course.';
    }

    if (empty($errors)) {
        try {
            $enrollmentData = [
                'student_id' => $studentId,
                'course_id' => $courseId,
                'status' => $status,
                'progress_percentage' => $progress,
                'updated_at' => formatDate(),
            ];

            if ($id > 0) {
                $db->update('course_enrollments', $enrollmentData, 'id = ?', [$id]);
                $_SESSION['flash']['success'] = 'Enrollment updated successfully.';
            } else {
                $enrollmentData['enrollment_date'] = formatDate();
                $db->insert('course_enrollments', $enrollmentData);
                $_SESSION['flash']['success'] = 'Student enrolled successfully.';
            }
            header('Location: enrollments.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (!$enrollment && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $enrollment = [
        'student_id' => 0,
        'course_id' => 0,
        'status' => 'active',
        'progress_percentage' => 0,
    ];
}

$courses = $db->getAll("SELECT id, title FROM courses WHERE status = 'published' 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 = $id > 0 ? 'Edit Enrollment' : 'Enroll Student';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
    <p class="text-muted mb-0"><?php echo $id > 0 ? 'Update enrollment details' : 'Enroll a student in a course'; ?></p>
  </div>
  <div>
    <a href="enrollments.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Enrollments
    </a>
  </div>
</div>

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

<div class="card">
  <div class="card-body">
    <form method="post" action="">
      <div class="row mb-3">
        <div class="col-md-6">
          <label for="student_id" class="form-label">Student</label>
          <select name="student_id" id="student_id" class="form-select" required>
            <option value="">Select Student</option>
            <?php foreach ($students as $s): ?>
              <option value="<?php echo (int)$s['id']; ?>" <?php echo (($_POST['student_id'] ?? ($enrollment['student_id'] ?? 0)) === $s['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name'] . ' (' . $s['username'] . ')'); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label for="course_id" class="form-label">Course</label>
          <select name="course_id" id="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 (($_POST['course_id'] ?? ($enrollment['course_id'] ?? 0)) === $c['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($c['title']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="row mb-3">
        <div class="col-md-6">
          <label for="status" class="form-label">Status</label>
          <select name="status" id="status" class="form-select" required>
            <?php foreach (['active','completed','cancelled','suspended'] as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (($_POST['status'] ?? ($enrollment['status'] ?? '')) === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-6">
          <label for="progress_percentage" class="form-label">Progress (%)</label>
          <input type="number" name="progress_percentage" id="progress_percentage" class="form-control" min="0" max="100" step="0.1" value="<?php echo htmlspecialchars($_POST['progress_percentage'] ?? ($enrollment['progress_percentage'] ?? 0)); ?>">
        </div>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="enrollments.php" class="btn btn-outline-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-save me-2"></i><?php echo $id > 0 ? 'Update' : 'Enroll'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

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