<?php
/**
 * Product Image Upload API
 * 
 * Handles image uploads for products
 * Returns JSON response with image details and variant URLs
 */

header('Content-Type: application/json');

require_once __DIR__ . '/config/image_config.php';

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Check if file was uploaded
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'No image uploaded or upload error']);
    exit;
}

// Optional: Custom filename (from POST data)
$customName = isset($_POST['name']) ? trim($_POST['name']) : '';

// Upload image and generate variants
$result = uploadProductImage($_FILES['image'], $customName);

if (!$result['success']) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => $result['error']]);
    exit;
}

// Build response with image URLs for different sections
$response = [
    'success' => true,
    'image' => [
        'filename' => $result['filename'],
        'url' => $result['url'],
        'info' => getImageInfo($result['filename'])
    ]
];

http_response_code(200);
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
