<?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);
    }
    
    $file = $_FILES['file'];
    
    // Validate file
    if ($file['error'] !== UPLOAD_ERR_OK) {
        jsonResponse(['error' => 'File upload failed'], 400);
    }
    
    // Check file size
    if ($file['size'] > MAX_UPLOAD_SIZE) {
        jsonResponse(['error' => 'File too large. Maximum size is 5MB'], 400);
    }
    
    // Check file type
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        jsonResponse(['error' => 'Invalid file type. Only JPG, PNG, and WebP allowed'], 400);
    }
    
    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = generateUuid() . '.' . $extension;
    $filepath = UPLOAD_DIR . $filename;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        jsonResponse(['error' => 'Failed to save file'], 500);
    }
    
    $fileUrl = '/api/uploads/' . $filename;
    
    jsonResponse([
        'url' => $fileUrl,
        'filename' => $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);
