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

$id = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$id) {
    sendError('Presenter ID required', 400);
}

try {
    // Get presenter details
    $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
        WHERE p.id = :id
    ");
    $stmt->execute([':id' => $id]);
    $presenter = $stmt->fetch();
    
    if (!$presenter) {
        sendError('Presenter not found', 404);
    }
    
    // Get podcasts this presenter hosts
    $podcastStmt = $pdo->prepare("
        SELECT pp.podcast_id, pp.role, p.title, p.thumbnail
        FROM podcast_presenters pp
        JOIN podcasts p ON p.id = pp.podcast_id
        WHERE pp.presenter_id = :presenter_id
        ORDER BY p.created_at DESC
    ");
    $podcastStmt->execute([':presenter_id' => $id]);
    $podcasts = $podcastStmt->fetchAll();
    
    // Get media this presenter appears in
    $mediaStmt = $pdo->prepare("
        SELECT mp.media_id, mp.role, m.title, m.type, m.media_id as file_key, m.created_at
        FROM media_presenters mp
        JOIN media m ON m.id = mp.media_id
        WHERE mp.presenter_id = :presenter_id
        ORDER BY m.created_at DESC
        LIMIT 20
    ");
    $mediaStmt->execute([':presenter_id' => $id]);
    $media = $mediaStmt->fetchAll();
    
    define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
    
    if ($presenter['image']) {
        $presenter['image_url'] = R2_PUBLIC_URL . '/' . $presenter['image'];
    }
    
    foreach ($podcasts as &$podcast) {
        if ($podcast['thumbnail']) {
            $podcast['thumbnail_url'] = R2_PUBLIC_URL . '/' . $podcast['thumbnail'];
        }
    }
    
    foreach ($media as &$item) {
        $item['url'] = R2_PUBLIC_URL . '/' . $item['file_key'];
    }
    
    sendSuccess([
        ...$presenter,
        'podcasts' => $podcasts,
        'media' => $media
    ]);
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>