<?php
session_start();
include 'includes/header.php';
require_once 'includes/pexels.php';

$pdo = db();
$stmt = $pdo->query('SELECT * FROM competitions WHERE deleted_at IS NULL ORDER BY start_date DESC');
$competitions = $stmt->fetchAll();
?>

<div class="container py-5">
    <h1 class="display-4 fw-bold">Coding Competitions</h1>
    <p class="fs-5 text-muted">Join our coding competitions and win exciting prizes.</p>

    <div class="row">
        <?php if (count($competitions) > 0) : ?>
            <?php foreach ($competitions as $competition) : ?>
                <?php
                $image_url = 'https://via.placeholder.com/600x400'; // Default placeholder
                $query = preg_replace('/[^a-zA-Z0-9\s]/', '', $competition['title']);
                $pexels_data = pexels_get('https://api.pexels.com/v1/search?query=' . urlencode($query) . '&per_page=1');
                if ($pexels_data && !empty($pexels_data['photos'])) {
                    $image_url = $pexels_data['photos'][0]['src']['large'];
                }
                ?>
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <img src="<?php echo $image_url; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($competition['title']); ?>">
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title"><a href="competition.php?id=<?php echo $competition['id']; ?>"><?php echo htmlspecialchars($competition['title']); ?></a></h5>
                            <p class="card-text flex-grow-1"><?php echo htmlspecialchars(substr($competition['description'], 0, 100)); ?>...</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">Starts: <?php echo date('M d, Y', strtotime($competition['start_date'])); ?></small>
                                <small class="text-muted">Ends: <?php echo date('M d, Y', strtotime($competition['end_date'])); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else : ?>
            <div class="alert alert-info">No competitions available yet. Please check back later.</div>
        <?php endif; ?>
    </div>
</div>

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