<?php
// api/media/index.php

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

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}
$user = requireAdmin(); 
// Handle GET request (list media)
if ($method === 'GET') {
    // Get query parameters
    $type = isset($_GET['type']) ? $_GET['type'] : null;
    $podcast_id = isset($_GET['podcast_id']) ? intval($_GET['podcast_id']) : null;
    $is_premium = isset($_GET['is_premium']) ? filter_var($_GET['is_premium'], FILTER_VALIDATE_BOOLEAN) : null;
    $status = isset($_GET['status']) ? $_GET['status'] : null;
    $search = isset($_GET['search']) ? $_GET['search'] : null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
    $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';
    
    // Validate sort order
    $sort_order = ($sort_order === 'ASC') ? 'ASC' : 'DESC';
    
    // Allowed sort columns
    $allowed_sort = ['id', 'title', 'type', 'created_at', 'file_size', 'is_premium'];
    if (!in_array($sort_by, $allowed_sort)) {
        $sort_by = 'created_at';
    }
    
    try {
        // Build query
        $sql = "SELECT m.*, p.title as podcast_title 
                FROM media m 
                LEFT JOIN podcasts p ON m.podcast_id = p.id 
                WHERE 1=1";
        $params = [];
        
        // Apply filters
        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;
        }
        
        if ($is_premium !== null) {
            $sql .= " AND m.is_premium = :is_premium";
            $params[':is_premium'] = $is_premium ? 1 : 0;
        }
        
        if ($status) {
            $sql .= " AND m.status = :status";
            $params[':status'] = $status;
        }
        
        if ($search) {
            $sql .= " AND (m.title LIKE :search OR m.description LIKE :search)";
            $params[':search'] = "%{$search}%";
        }
        
        // Get total count
        $countSql = preg_replace('/SELECT m.*, p.title as podcast_title /', 'SELECT COUNT(*) as total ', $sql);
        $countStmt = $pdo->prepare($countSql);
        foreach ($params as $key => $value) {
            $countStmt->bindValue($key, $value);
        }
        $countStmt->execute();
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // Add sorting and pagination
        $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 full R2 URLs
        foreach ($media as &$item) {
            $item['url'] = R2_PUBLIC_URL . '/' . $item['media_id'];
        }
        
        sendSuccess([
            'data' => $media,
            'pagination' => [
                'total' => intval($total),
                'limit' => $limit,
                'offset' => $offset,
                'returned' => count($media)
            ]
        ]);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} elseif ($method === 'POST') {
    sendError('Use the upload endpoint to create media', 400);
} else {
    sendError('Method not allowed', 405);
}
?>