<?php
// api/podcasts/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();

// ========== GET - List podcasts ==========
if ($method === 'GET') {
    $search = isset($_GET['search']) ? $_GET['search'] : null;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    
    try {
        $sql = "SELECT p.*, COUNT(m.id) as episode_count 
                FROM podcasts p 
                LEFT JOIN media m ON m.podcast_id = p.id 
                WHERE 1=1";
        $params = [];
        
        if ($search) {
            $sql .= " AND (p.title LIKE :search OR p.description LIKE :search)";
            $params[':search'] = "%{$search}%";
        }
        
        $sql .= " GROUP BY p.id ORDER BY p.created_at DESC 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();
        
        $podcasts = $stmt->fetchAll();
        
        foreach ($podcasts as &$podcast) {
            if ($podcast['thumbnail']) {
                $podcast['thumbnail_url'] = R2_PUBLIC_URL . '/' . $podcast['thumbnail'];
            }
        }
        
        $countStmt = $pdo->query("SELECT COUNT(*) FROM podcasts");
        $total = $countStmt->fetchColumn();
        
        sendSuccess([
            'data' => $podcasts,
            'pagination' => [
                'total' => intval($total),
                'limit' => $limit,
                'offset' => $offset
            ]
        ]);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}

// ========== POST - Create new podcast ==========
elseif ($method === 'POST') {
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        // Handle FormData with file upload
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $thumbnail = null;
        
        if (!$title) {
            sendError('Title is required', 400);
        }
        
        // Handle thumbnail upload
        if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['thumbnail'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime_type = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            
            if (in_array($mime_type, $allowedTypes)) {
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', $title);
                $thumbnail_key = 'thumbnails/podcasts/' . $safeTitle . '_' . time() . '_' . uniqid() . '.' . $extension;
                
                $uploadResult = uploadToR2($file['tmp_name'], $thumbnail_key, $mime_type);
                if ($uploadResult['success']) {
                    $thumbnail = $thumbnail_key;
                }
            }
        }
        
        $stmt = $pdo->prepare("
            INSERT INTO podcasts (title, description, thumbnail) 
            VALUES (:title, :description, :thumbnail)
        ");
        
        $stmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':thumbnail' => $thumbnail
        ]);
        
        $podcast_id = $pdo->lastInsertId();
        
        sendSuccess([
            'id' => $podcast_id,
            'title' => $title,
            'description' => $description,
            'thumbnail' => $thumbnail
        ], 'Podcast created successfully');
        
    } else {
        // Handle JSON data (original way)
        $data = getRequestData();
        validateRequiredFields($data, ['title']);
        
        $stmt = $pdo->prepare("
            INSERT INTO podcasts (title, description, thumbnail) 
            VALUES (:title, :description, :thumbnail)
        ");
        
        $stmt->execute([
            ':title' => $data['title'],
            ':description' => $data['description'] ?? null,
            ':thumbnail' => $data['thumbnail'] ?? null
        ]);
        
        $podcast_id = $pdo->lastInsertId();
        
        sendSuccess([
            'id' => $podcast_id,
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'thumbnail' => $data['thumbnail'] ?? null
        ], 'Podcast created successfully');
    }
}

else {
    sendError('Method not allowed', 405);
}
?>