<?php
// api/public/podcasts.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';

$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;

try {
    $stmt = $pdo->prepare("
        SELECT p.id, p.title, p.description, p.thumbnail, p.created_at,
               COUNT(m.id) as episode_count
        FROM podcasts p
        LEFT JOIN media m ON m.podcast_id = p.id
        GROUP BY p.id
        ORDER BY p.created_at DESC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $podcasts = $stmt->fetchAll();
    
    define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
    foreach ($podcasts as &$podcast) {
        if ($podcast['thumbnail']) {
            $podcast['thumbnail_url'] = R2_PUBLIC_URL . '/' . $podcast['thumbnail'];
        }
    }
    
    sendSuccess([
        'data' => $podcasts,
        'pagination' => [
            'total' => count($podcasts),
            'limit' => $limit,
            'offset' => $offset
        ]
    ]);
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>