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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $studentId   = (int)($_POST['student_id'] ?? 0);
    $courseId    = (int)($_POST['course_id'] ?? 0);
    $name        = trim($_POST['certificate_name'] ?? '');

    if ($studentId <= 0) {
        $errors[] = 'Please select a student.';
    }
    if ($courseId <= 0) {
        $errors[] = 'Please select a course.';
    }
    if ($name === '') {
        $errors[] = 'Certificate name is required.';
    }

    // Prevent duplicate certificate
    $existing = $db->get(
        "SELECT id FROM certificates WHERE student_id = ? AND course_id = ? AND is_revoked = 0",
        [$studentId, $courseId]
    );
    if ($existing) {
        $errors[] = 'An active certificate already exists for this student and course.';
    }

    if (empty($errors)) {
        try {
            $certData = [
                'student_id' => $studentId,
                'course_id' => $courseId,
                'certificate_name' => $name,
                'verification_code' => strtoupper(generateToken(12)),
                'issue_date' => formatDate(),
                'is_revoked' => 0,
            ];
            $db->insert('certificates', $certData);
            $_SESSION['flash']['success'] = 'Certificate issued successfully.';
            header('Location: certificates.php');
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$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 = 'Issue Certificate';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Issue Certificate</h1>
    <p class="text-muted mb-0">Create a new certificate for a student</p>
  </div>
  <div>
    <a href="certificates.php" class="btn btn-outline-secondary">
      <i class="fas fa-arrow-left me-2"></i>Back to Certificates
    </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 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 htmlspecialchars($c['title']); ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="mb-3">
        <label for="certificate_name" class="form-label">Certificate Name</label>
        <input type="text" name="certificate_name" id="certificate_name" class="form-control" required placeholder="e.g. Certificate of Completion">
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="certificates.php" class="btn btn-outline-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">
          <i class="fas fa-certificate me-2"></i>Issue Certificate
        </button>
      </div>
    </form>
  </div>
</div>

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