<?php
// api/upload/thumbnail.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;
}

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

$user = requireAuth();

if (!isset($_FILES['thumbnail'])) {
    sendError('No thumbnail uploaded', 400);
}

$file = $_FILES['thumbnail'];
$podcast_id = isset($_POST['podcast_id']) && $_POST['podcast_id'] !== '' ? intval($_POST['podcast_id']) : null;

// Validate file
if ($file['error'] !== UPLOAD_ERR_OK) {
    sendError('Upload failed: ' . $file['error'], 400);
}

// Validate image type
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', '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)) {
    sendError('Invalid image format. Allowed: JPEG, PNG, WEBP, GIF', 400);
}

// Max size 5MB
if ($file['size'] > 5 * 1024 * 1024) {
    sendError('Thumbnail too large. Max size: 5MB', 400);
}

// Get file extension from mime type
$extension_map = [
    'image/jpeg' => 'jpg',
    'image/jpg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp',
    'image/gif' => 'gif'
];
$extension = $extension_map[$mime_type];

// Generate unique filename for R2
$safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$timestamp = time();
$uniqueId = uniqid();
$thumbnail_key = "thumbnails/{$safeTitle}_{$timestamp}_{$uniqueId}.{$extension}";

// Upload to R2
$uploadResult = uploadToR2($file['tmp_name'], $thumbnail_key, $mime_type);

if (!$uploadResult['success']) {
    sendError('R2 upload failed: ' . $uploadResult['error'], 500);
}

// If podcast_id provided, update the podcast thumbnail
if ($podcast_id) {
    try {
        // Check if podcast exists
        $stmt = $pdo->prepare("SELECT id, thumbnail FROM podcasts WHERE id = :id");
        $stmt->execute([':id' => $podcast_id]);
        $podcast = $stmt->fetch();
        
        if (!$podcast) {
            // Delete the uploaded thumbnail since podcast doesn't exist
            deleteFromR2($thumbnail_key);
            sendError('Podcast not found', 404);
        }
        
        // Delete old thumbnail from R2 if exists
        if ($podcast['thumbnail']) {
            deleteFromR2($podcast['thumbnail']);
        }
        
        // Update podcast with new thumbnail
        $stmt = $pdo->prepare("UPDATE podcasts SET thumbnail = :thumbnail WHERE id = :id");
        $stmt->execute([
            ':thumbnail' => $thumbnail_key,
            ':id' => $podcast_id
        ]);
        
        sendSuccess([
            'id' => $podcast_id,
            'thumbnail_key' => $thumbnail_key,
            'thumbnail_url' => $uploadResult['url']
        ], 'Thumbnail uploaded and assigned to podcast');
        
    } catch (PDOException $e) {
        // Delete from R2 if database update fails
        deleteFromR2($thumbnail_key);
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
} else {
    // Just return the thumbnail info for later assignment
    sendSuccess([
        'thumbnail_key' => $thumbnail_key,
        'thumbnail_url' => $uploadResult['url']
    ], 'Thumbnail uploaded successfully. Use the thumbnail_key to assign to a podcast via PUT /api/podcasts/item.php');
}
?>