<?php
// api/public/media.php

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

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($method !== 'GET') {
    sendError('Method not allowed', 405);
}

// No authentication required for public endpoints
$type = isset($_GET['type']) ? $_GET['type'] : null;
$podcast_id = isset($_GET['podcast_id']) ? intval($_GET['podcast_id']) : null;
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
$sort_by = isset($_GET['sort_by']) ? $_GET['sort_by'] : 'created_at';
$sort_order = isset($_GET['sort_order']) ? strtoupper($_GET['sort_order']) : 'DESC';

try {
    $sql = "SELECT m.id, m.title, m.description, m.type, m.media_id, m.podcast_id, 
                   m.is_premium, m.file_size, m.created_at,
                   p.title as podcast_title
            FROM media m
            LEFT JOIN podcasts p ON p.id = m.podcast_id
            WHERE m.status = 'ready'";
    $params = [];
    
    if ($type) {
        $sql .= " AND m.type = :type";
        $params[':type'] = $type;
    }
    
    if ($podcast_id) {
        $sql .= " AND m.podcast_id = :podcast_id";
        $params[':podcast_id'] = $podcast_id;
    }
    
    $sql .= " ORDER BY m.{$sort_by} {$sort_order} LIMIT :limit OFFSET :offset";
    $params[':limit'] = $limit;
    $params[':offset'] = $offset;
    
    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => &$val) {
        if ($key === ':limit' || $key === ':offset') {
            $stmt->bindParam($key, $val, PDO::PARAM_INT);
        } else {
            $stmt->bindParam($key, $val);
        }
    }
    $stmt->execute();
    
    $media = $stmt->fetchAll();
    
    // Add public URL
    define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
    foreach ($media as &$item) {
        $item['url'] = R2_PUBLIC_URL . '/' . $item['media_id'];
    }
    
    sendSuccess([
        'data' => $media,
        'pagination' => [
            'total' => count($media),
            'limit' => $limit,
            'offset' => $offset
        ]
    ]);
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>