<?php
require_once __DIR__ . '/includes/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') json_error('Método no permitido.', 405);
require_admin($config);

if (empty($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    json_error('Sube un archivo de imagen válido.', 422);
}

$file = $_FILES['image'];

$allowed = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp',
];

// Trust getimagesize() over the client-sent mime type — it decodes the
// actual file header instead of the (spoofable) Content-Type the browser
// sent, so a renamed .php can't slip through as an "image/jpeg".
$info = @getimagesize($file['tmp_name']);
$mime = $info['mime'] ?? null;

if (!$mime || !isset($allowed[$mime])) {
    json_error('Formato no soportado. Usa JPG, PNG o WebP.', 422);
}

if ($file['size'] > 5 * 1024 * 1024) {
    json_error('La imagen no puede superar 5MB.', 422);
}

$ext = $allowed[$mime];
$name = bin2hex(random_bytes(16)) . '.' . $ext;
$uploadsDir = __DIR__ . '/uploads';
if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);

$destination = $uploadsDir . '/' . $name;
if (!move_uploaded_file($file['tmp_name'], $destination)) {
    json_error('No se pudo guardar la imagen.', 500);
}

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$baseDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])), '/');
$url = "$scheme://$host$baseDir/uploads/$name";

json_ok(['url' => $url], 201);
