<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
$user = getCurrentUser();
$db = Database::getInstance();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    setFlashMessage('error', 'Certificate not found.');
    redirect('certificates.php');
}

$cert = $db->get("SELECT * FROM certificates WHERE id = ?", [$id]);
if (!$cert) {
    setFlashMessage('error', 'Certificate not found.');
    redirect('certificates.php');
}

// Access control: owner or admins
if ($cert['student_id'] !== $user['id'] && !in_array($_SESSION['role'] ?? '', ['admin', 'super_admin'], true)) {
    setFlashMessage('error', 'Access denied.');
    redirect('certificates.php');
}

$pageTitle = 'Certificate ' . ($cert['certificate_number'] ?? '');
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Certificate</h1>
    <p class="text-muted mb-0"><?php echo htmlspecialchars($cert['course_name']); ?> • Issued <?php echo date('Y-m-d', strtotime($cert['issue_date'])); ?></p>
  </div>
  <div>
    <a href="certificates.php" class="btn btn-outline-secondary"><i class="ri ri-arrow-left-line me-1"></i>Back</a>
  </div>
</div>

<div class="card">
  <div class="card-body text-center">
    <?php if (!empty($cert['certificate_url'])): ?>
      <?php $url = $cert['certificate_url']; ?>
      <?php if (preg_match('/\.pdf$/i', $url)): ?>
        <iframe src="<?php echo htmlspecialchars($url); ?>" style="width:100%;height:600px;border:0"></iframe>
      <?php else: ?>
        <img src="<?php echo htmlspecialchars($url); ?>" alt="Certificate" class="img-fluid" style="max-height:600px;">
      <?php endif; ?>

      <div class="mt-3">
        <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" class="btn btn-outline-primary me-2">Open</a>
        <a href="<?php echo htmlspecialchars($url); ?>" download class="btn btn-primary">Download</a>
      </div>
    <?php else: ?>
      <p class="text-muted">No certificate file available for this record.</p>
    <?php endif; ?>

    <?php if (!empty($cert['verification_url'])): ?>
      <div class="mt-3">
        <a href="<?php echo htmlspecialchars($cert['verification_url']); ?>" target="_blank" class="small">Verify Certificate</a>
      </div>
    <?php endif; ?>
  </div>
</div>

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