<?php
// api/podcasts/item.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';

// Detect the actual HTTP method
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST' && isset($_POST['_method'])) {
    $method = strtoupper($_POST['_method']);
}

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

$user = requireAdmin();

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

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

// ========== GET - Retrieve single podcast ==========
if ($method === 'GET') {
    try {
        $stmt = $pdo->prepare("
            SELECT p.*, COUNT(m.id) as episode_count 
            FROM podcasts p 
            LEFT JOIN media m ON m.podcast_id = p.id 
            WHERE p.id = :id 
            GROUP BY p.id
        ");
        $stmt->execute([':id' => $id]);
        $podcast = $stmt->fetch();
        
        if (!$podcast) {
            sendError('Podcast not found', 404);
        }
        
        define('R2_PUBLIC_URL', 'https://pub-4a26074f63ae4203a6de95f3b950b21c.r2.dev');
        if ($podcast['thumbnail']) {
            $podcast['thumbnail_url'] = R2_PUBLIC_URL . '/' . $podcast['thumbnail'];
        }
        
        sendSuccess($podcast);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}

// ========== PUT - Update podcast ==========
elseif ($method === 'PUT') {
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        // FormData with file upload
        $title = $_POST['title'] ?? null;
        $description = $_POST['description'] ?? null;
        $thumbnail = null;
        
        $stmt = $pdo->prepare("SELECT id, thumbnail FROM podcasts WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $podcast = $stmt->fetch();
        
        if (!$podcast) {
            sendError('Podcast not found', 404);
        }
        
        // 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)) {
                if ($podcast['thumbnail']) {
                    deleteFromR2($podcast['thumbnail']);
                }
                
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', $title ?? 'podcast');
                $thumbnail_key = 'thumbnails/podcasts/' . $safeTitle . '_' . time() . '_' . uniqid() . '.' . $extension;
                
                $uploadResult = uploadToR2($file['tmp_name'], $thumbnail_key, $mime_type);
                if ($uploadResult['success']) {
                    $thumbnail = $thumbnail_key;
                }
            }
        }
        
        $updates = [];
        $params = [':id' => $id];
        
        if ($title !== null) {
            $updates[] = "title = :title";
            $params[':title'] = $title;
        }
        if ($description !== null) {
            $updates[] = "description = :description";
            $params[':description'] = $description;
        }
        if ($thumbnail !== null) {
            $updates[] = "thumbnail = :thumbnail";
            $params[':thumbnail'] = $thumbnail;
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE podcasts SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Podcast updated successfully');
        
    } else {
        // JSON data
        $data = getRequestData();
        
        $updates = [];
        $params = [':id' => $id];
        
        if (isset($data['title'])) {
            $updates[] = "title = :title";
            $params[':title'] = $data['title'];
        }
        if (isset($data['description'])) {
            $updates[] = "description = :description";
            $params[':description'] = $data['description'];
        }
        if (isset($data['thumbnail'])) {
            $updates[] = "thumbnail = :thumbnail";
            $params[':thumbnail'] = $data['thumbnail'];
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE podcasts SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Podcast updated successfully');
    }
}

// ========== DELETE - Remove podcast ==========
elseif ($method === 'DELETE') {
    try {
        $stmt = $pdo->prepare("SELECT thumbnail FROM podcasts WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $podcast = $stmt->fetch();
        
        if (!$podcast) {
            sendError('Podcast not found', 404);
        }
        
        if ($podcast['thumbnail']) {
            deleteFromR2($podcast['thumbnail']);
        }
        
        $stmt = $pdo->prepare("DELETE FROM podcasts WHERE id = :id");
        $stmt->execute([':id' => $id]);
        
        sendSuccess(null, 'Podcast deleted successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
}

// ========== POST - Create new podcast ==========
elseif ($method === 'POST') {
    $isMultipart = !empty($_FILES);
    
    if ($isMultipart) {
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $thumbnail = null;
        
        if (!$title) {
            sendError('Title is required', 400);
        }
        
        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
        ]);
        
        sendSuccess(['id' => $pdo->lastInsertId()], 'Podcast created successfully');
        
    } else {
        $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
        ]);
        
        sendSuccess(['id' => $pdo->lastInsertId()], 'Podcast created successfully');
    }
}

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