<?php
// api/media/item.php

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

$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}
$user = requireAdmin(); 
// Get ID from query parameter
$id = isset($_GET['id']) ? intval($_GET['id']) : null;

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

// GET - Retrieve single media
if ($method === 'GET') {
    try {
        $stmt = $pdo->prepare("
            SELECT m.*, p.title as podcast_title 
            FROM media m 
            LEFT JOIN podcasts p ON m.podcast_id = p.id 
            WHERE m.id = :id
        ");
        $stmt->execute([':id' => $id]);
        $media = $stmt->fetch();
        
        if (!$media) {
            sendError('Media not found', 404);
        }
        
        $media['url'] = R2_PUBLIC_URL . '/' . $media['media_id'];
        
        sendSuccess($media);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// PUT - Update media
} elseif ($method === 'PUT') {
    $user = requireAuth();
    $data = getRequestData();
    
    try {
        // Check if media exists
        $stmt = $pdo->prepare("SELECT id FROM media WHERE id = :id");
        $stmt->execute([':id' => $id]);
        if (!$stmt->fetch()) {
            sendError('Media not found', 404);
        }
        
        // Build update query
        $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['is_premium'])) {
            $updates[] = "is_premium = :is_premium";
            $params[':is_premium'] = $data['is_premium'] ? 1 : 0;
        }
        
        if (isset($data['podcast_id'])) {
            $updates[] = "podcast_id = :podcast_id";
            $params[':podcast_id'] = $data['podcast_id'] ?: null;
        }
        
        if (isset($data['status'])) {
            $allowed_status = ['processing', 'ready', 'failed'];
            if (in_array($data['status'], $allowed_status)) {
                $updates[] = "status = :status";
                $params[':status'] = $data['status'];
            }
        }
        
        if (empty($updates)) {
            sendError('No fields to update', 400);
        }
        
        $sql = "UPDATE media SET " . implode(', ', $updates) . " WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        sendSuccess(null, 'Media updated successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// DELETE - Remove media
} elseif ($method === 'DELETE') {
    $user = requireAuth();
      $user = requirePermission('delete_media');
    try {
        // Get media info before deleting
        $stmt = $pdo->prepare("SELECT media_id FROM media WHERE id = :id");
        $stmt->execute([':id' => $id]);     
        $media = $stmt->fetch();
        
        if (!$media) {
            sendError('Media not found', 404);
        }
        
        // Delete from database
        $stmt = $pdo->prepare("DELETE FROM media WHERE id = :id");
        $stmt->execute([':id' => $id]);
        
        // Delete from R2
        $deleteResult = deleteFromR2($media['media_id']);
        
        if (!$deleteResult['success']) {
            // Log error but still return success since DB record is gone
            error_log('Failed to delete from R2: ' . $deleteResult['error']);
        }
        
        sendSuccess(null, 'Media deleted successfully');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} else {
    sendError('Method not allowed', 405);
}
?>