<?php
session_start();
require_once 'includes/header.php';
require_once 'db/config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

$pdo = db();
$stmt = $pdo->prepare('SELECT c.id, com.title as competition_title, c.certificate_type, c.issued_at FROM certificates c JOIN competitions com ON c.competition_id = com.id WHERE c.user_id = ? ORDER BY c.issued_at DESC');
$stmt->execute([$user_id]);
$certificates = $stmt->fetchAll();
?>

<div class="container py-5">
    <h1 class="display-4 fw-bold">My Certificates</h1>
    <p class="fs-5 text-muted">Here is a list of your certificates.</p>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>Competition</th>
                <th>Certificate Type</th>
                <th>Date Issued</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($certificates) > 0) : ?>
                <?php foreach ($certificates as $certificate) : ?>
                    <tr>
                        <td><?php echo htmlspecialchars($certificate['competition_title']); ?></td>
                        <td><?php echo htmlspecialchars($certificate['certificate_type']); ?></td>
                        <td><?php echo $certificate['issued_at']; ?></td>
                        <td><a href="generate_certificate.php?id=<?php echo $certificate['id']; ?>" class="btn btn-primary btn-sm" target="_blank">Download</a></td>
                    </tr>
                <?php endforeach; ?>
            <?php else : ?>
                <tr>
                    <td colspan="4" class="text-center">You have not earned any certificates yet.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

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