<?php
require_once '../db/config.php';
require_once '../includes/pexels.php';

$difficulty = $_POST['difficulty'] ?? 'all';
$learning_style = $_POST['learning_style'] ?? 'all';
$sort_by = $_POST['sort_by'] ?? 'date_desc';

$pdo = db();

$sql = 'SELECT * FROM challenges WHERE deleted_at IS NULL';
$params = [];

if ($difficulty !== 'all') {
    $sql .= ' AND difficulty = ?';
    $params[] = $difficulty;
}

if ($learning_style !== 'all') {
    $sql .= ' AND learning_style = ?';
    $params[] = $learning_style;
}

switch ($sort_by) {
    case 'date_asc':
        $sql .= ' ORDER BY created_at ASC';
        break;
    case 'popularity':
        // Popularity can be implemented later, for now, let's sort by number of submissions
        $sql .= ' ORDER BY (SELECT COUNT(*) FROM challenge_submissions WHERE challenge_id = challenges.id) DESC';
        break;
    default:
        $sql .= ' ORDER BY created_at DESC';
        break;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$challenges = $stmt->fetchAll();

if (count($challenges) > 0) {
    foreach ($challenges as $challenge) {
        $image_data = pexels_get('https://api.pexels.com/v1/search?query=' . urlencode($challenge['title']) . '&per_page=1');
        if ($image_data && isset($image_data['photos'][0])) {
            $image_url = $image_data['photos'][0]['src']['large'];
        } else {
            $image_url = 'https://via.placeholder.com/600x400'; // Default placeholder
        }

        echo '<div class="col-md-4 mb-4">';
        echo '<div class="card h-100">';
        echo '<div class="card-img-container">';
        echo '<img src="' . $image_url . '" class="card-img-top" alt="' . htmlspecialchars($challenge['title']) . '">';
        echo '<div class="card-img-overlay d-flex flex-column justify-content-end">';
        echo '<h5 class="card-title text-white"><a href="challenge.php?id=' . $challenge['id'] . '">' . htmlspecialchars($challenge['title']) . '</a></h5>';
        echo '<span class="badge bg-primary">' . htmlspecialchars($challenge['difficulty']) . '</span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="card-body d-flex flex-column">';
        echo '<p class="card-text flex-grow-1">' . htmlspecialchars(substr($challenge['description'], 0, 100)) . '...</p>';
        echo '<div class="d-flex justify-content-between align-items-center">';
        echo '<small class="text-muted">' . htmlspecialchars($challenge['learning_style']) . '</small>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }
} else {
    echo '<div class="alert alert-info">No challenges match your criteria.</div>';
}
