<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'uploads';
$maxBytes = 12 * 1024 * 1024;
$allowedExtensions = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif'];
$allowedMime = [
    'image/png' => 'png',
    'image/jpeg' => 'jpg',
    'image/webp' => 'webp',
    'image/gif' => 'gif',
    'image/avif' => 'avif'
];

function send_json(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

function slugify(string $value): string
{
    $slug = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower($value));
    $slug = trim((string) $slug, '-');
    return $slug !== '' ? $slug : 'item';
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_json(405, ['error' => 'Método no permitido']);
}

if (!isset($_FILES['image'])) {
    send_json(400, ['error' => 'No se recibió image']);
}

$file = $_FILES['image'];

if (!is_array($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    send_json(400, ['error' => 'Error al subir el archivo']);
}

$tmpPath = (string) ($file['tmp_name'] ?? '');
$size = (int) ($file['size'] ?? 0);

if ($size <= 0) {
    send_json(400, ['error' => 'Archivo vacío']);
}

if ($size > $maxBytes) {
    send_json(413, ['error' => 'El archivo excede 12MB']);
}

$originalName = (string) ($file['name'] ?? '');
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

if (!in_array($extension, $allowedExtensions, true)) {
    $extension = '';
}

$mime = '';
if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    if ($finfo !== false) {
        $detected = finfo_file($finfo, $tmpPath);
        if (is_string($detected)) {
            $mime = $detected;
        }
        finfo_close($finfo);
    }
}

if ($mime !== '' && isset($allowedMime[$mime])) {
    $extension = $allowedMime[$mime];
}

if ($extension === '') {
    send_json(400, ['error' => 'Formato no permitido']);
}

if (!is_dir($uploadDir)) {
    $ok = mkdir($uploadDir, 0775, true);
    if (!$ok && !is_dir($uploadDir)) {
        send_json(500, ['error' => 'No se pudo crear assets/uploads']);
    }
}

$itemId = isset($_POST['itemId']) ? slugify((string) $_POST['itemId']) : 'item';
$filename = $itemId . '-' . (string) round(microtime(true) * 1000) . '.' . $extension;
$targetPath = $uploadDir . DIRECTORY_SEPARATOR . $filename;

$moved = move_uploaded_file($tmpPath, $targetPath);
if (!$moved) {
    send_json(500, ['error' => 'No se pudo guardar la imagen']);
}

send_json(200, [
    'uploaded' => true,
    'path' => './assets/uploads/' . $filename,
    'bytes' => $size
]);
