<?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 certificate ID.';
    header('Location: certificates.php');
    exit;
}

$cert = $db->get("SELECT * FROM certificates WHERE id = ?", [$id]);
if (!$cert) {
    $_SESSION['flash']['danger'] = 'Certificate not found.';
    header('Location: certificates.php');
    exit;
}

if ($cert['is_revoked']) {
    $_SESSION['flash']['warning'] = 'Certificate is already revoked.';
    header('Location: certificates.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reason = trim($_POST['revocation_reason'] ?? '');
    if ($reason === '') {
        $errors[] = 'Revocation reason is required.';
    } else {
        $db->update(
            'certificates',
            [
                'is_revoked' => 1,
                'revoked_at' => formatDate(),
                'revocation_reason' => $reason,
            ],
            'id = ?',
            [$id]
        );
        $_SESSION['flash']['success'] = 'Certificate revoked successfully.';
        header('Location: certificates.php');
        exit;
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Revoke Certificate</h1>
    <p class="text-muted mb-0">Confirm certificate revocation</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>

<div class="card">
  <div class="card-body">
    <p class="mb-3">You are about to revoke the following certificate:</p>
    <ul class="mb-4">
      <li><strong>Certificate:</strong> <?php echo htmlspecialchars($cert['certificate_name'] ?? ''); ?></li>
      <li><strong>Student:</strong> <?php echo htmlspecialchars($cert['student_id'] ?? ''); ?></li>
      <li><strong>Course:</strong> <?php echo htmlspecialchars($cert['course_id'] ?? ''); ?></li>
      <li><strong>Issued:</strong> <?php echo htmlspecialchars($cert['issue_date'] ?? ''); ?></li>
    </ul>

    <form method="post" action="">
      <div class="mb-3">
        <label for="revocation_reason" class="form-label">Revocation Reason</label>
        <textarea name="revocation_reason" id="revocation_reason" class="form-control" rows="4" required></textarea>
      </div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-danger">
          <i class="fas fa-ban me-2"></i>Revoke Certificate
        </button>
        <a href="certificates.php" class="btn btn-outline-secondary">Cancel</a>
      </div>
    </form>
  </div>
</div>

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