<?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.name, p.bio, p.image,
               (SELECT COUNT(*) FROM media_presenters WHERE presenter_id = p.id) as media_count,
               (SELECT COUNT(*) FROM podcast_presenters WHERE presenter_id = p.id) as podcast_count
        FROM presenters p
        ORDER BY p.name ASC
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $presenters = $stmt->fetchAll();
    
    define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
    foreach ($presenters as &$presenter) {
        if ($presenter['image']) {
            $presenter['image_url'] = R2_PUBLIC_URL . '/' . $presenter['image'];
        }
    }
    
    sendSuccess([
        'data' => $presenters
    ]);
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>