<?php
/**
 * Image Upload Endpoint
 */

requireAuth(); // Only authenticated users can upload

if ($method === 'POST' && $id === 'image') {
    if (!isset($_FILES['file'])) {
        jsonResponse(['error' => 'No file uploaded'], 400);
    }
    
    $result = handleImageUpload($_FILES['file']);
    if (isset($result['error'])) {
        jsonResponse(['error' => $result['error']], $result['status']);
    }

    jsonResponse([
        'url' => $result['url'],
        'filename' => $result['filename']
    ]);
}

// Serve uploaded images
if ($method === 'GET' && isset($pathParts[1]) && $pathParts[1] === 'uploads' && isset($pathParts[2])) {
    $filename = basename($pathParts[2]);
    $filepath = UPLOAD_DIR . $filename;
    
    if (!file_exists($filepath)) {
        jsonResponse(['error' => 'Image not found'], 404);
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $filepath);
    finfo_close($finfo);
    
    header('Content-Type: ' . $mimeType);
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
    exit;
}

jsonResponse(['error' => 'Invalid upload endpoint'], 404);
