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

$pageTitle = 'Certificates';

// Get user's certificates
$certificates = $db->getAll(
    "SELECT * FROM certificates WHERE student_id = ? AND is_revoked = 0 ORDER BY issue_date DESC",
    [$user['id']]
);

include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Certificates</h1>
    <p class="text-muted mb-0">View and download your issued certificates.</p>
  </div>
</div>

<div class="card">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Certificate #</th>
            <th>Course</th>
            <th>Issued</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$certificates): ?>
            <tr><td colspan="4" class="text-center text-muted py-4">No certificates found.</td></tr>
          <?php else: foreach ($certificates as $cert): ?>
            <tr>
              <td><?php echo htmlspecialchars($cert['certificate_number']); ?></td>
              <td><?php echo htmlspecialchars($cert['course_name']); ?></td>
              <td><?php echo date('Y-m-d', strtotime($cert['issue_date'])); ?></td>
              <td class="text-end">
                <?php if (!empty($cert['certificate_url'])): ?>
                  <a href="<?php echo htmlspecialchars($cert['certificate_url']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">View</a>
                  <a href="<?php echo htmlspecialchars($cert['certificate_url']); ?>" download class="btn btn-sm btn-primary ms-1">Download</a>
                <?php else: ?>
                  <a href="certificate.php?id=<?php echo (int)$cert['id']; ?>" class="btn btn-sm btn-outline-secondary">View</a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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