<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json; charset=utf-8");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") { http_response_code(200); exit; }

ini_set('display_errors', 0);
require_once(__DIR__ . "/../config.php");
require_once(__DIR__ . "/../auth_guard.php");

$authUser   = requireAuth($JWT_KEY);
$activeUser = requireActiveUser($mysqli, $authUser);

function fail(string $m, int $c = 400): void { http_response_code($c); echo json_encode(["success" => false, "message" => $m]); exit; }
function ok(array $d = [], string $m = "OK"): void { echo json_encode(["success" => true, "message" => $m] + $d); exit; }

if ($_SERVER["REQUEST_METHOD"] !== "POST") fail("Método no permitido.", 405);

$file = $_FILES["imagen"] ?? null;
if (!$file || $file["error"] !== UPLOAD_ERR_OK) fail("No se recibió archivo válido.");

$allowed = ["image/jpeg", "image/png", "image/gif", "image/webp"];
$mime    = mime_content_type($file["tmp_name"]);
if (!in_array($mime, $allowed)) fail("Tipo de archivo no permitido. Solo JPG, PNG, GIF, WEBP.");

$maxSize = 5 * 1024 * 1024;
if ($file["size"] > $maxSize) fail("Archivo demasiado grande. Máximo 5MB.");

$extMap  = ["image/jpeg" => "jpg", "image/png" => "png", "image/gif" => "gif", "image/webp" => "webp"];
$ext     = $extMap[$mime];
$nombre  = uniqid("preg_", true) . "." . $ext;
$carpeta = __DIR__ . "/../../api_corp/IMG_EV/";
$urlBase = "https://devsoul.co/api_corp/IMG_EV/";

if (!is_dir($carpeta)) mkdir($carpeta, 0755, true);

if (!move_uploaded_file($file["tmp_name"], $carpeta . $nombre)) fail("Error al guardar la imagen.");

ok(["url" => $urlBase . $nombre], "Imagen subida correctamente");