<?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 b.name, b.description, b.icon_url FROM user_badges ub JOIN badges b ON ub.badge_id = b.id WHERE ub.user_id = ?');
$stmt->execute([$user_id]);
$badges = $stmt->fetchAll();
?>

<div class="container py-5">
    <h1 class="display-4 fw-bold">My Badges</h1>
    <p class="fs-5 text-muted">Here are the badges you have earned.</p>

    <div class="row">
        <?php if (count($badges) > 0) : ?>
            <?php foreach ($badges as $badge) : ?>
                <div class="col-md-4">
                    <div class="card mb-4">
                        <div class="card-body text-center">
                            <?php if (!empty($badge['icon_url'])) : ?>
                                <img src="<?php echo htmlspecialchars($badge['icon_url']); ?>" alt="<?php echo htmlspecialchars($badge['name']); ?>" class="img-fluid mb-3" style="max-height: 100px;">
                            <?php else : ?>
                                <i class="bi bi-award-fill fs-1 text-primary mb-3"></i>
                            <?php endif; ?>
                            <h5 class="card-title"><?php echo htmlspecialchars($badge['name']); ?></h5>
                            <p class="card-text"><?php echo htmlspecialchars($badge['description']); ?></p>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else : ?>
            <div class="alert alert-info">You have not earned any badges yet.</div>
        <?php endif; ?>
    </div>
</div>

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