<?php
// Mostrar errores
ini_set('display_errors', 1);
error_reporting(E_ALL);

// CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

if (!isset($_GET['slug'])) {
    echo json_encode(["success" => false, "message" => "Falta el parámetro slug"]);
    exit;
}

$slug = preg_replace('/[^a-z0-9\-]/', '', strtolower($_GET['slug']));
$rutaCarpeta = __DIR__ . "/../tiendas/$slug/banners/";

if (!file_exists($rutaCarpeta)) {
    mkdir($rutaCarpeta, 0755, true);
}

$imagenes = [];

foreach ($_FILES as $file) {
    if ($file['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $nuevoNombre = 'banner_' . time() . '_' . rand(100, 999) . '.' . $ext;
        $rutaDestino = $rutaCarpeta . $nuevoNombre;

        if (move_uploaded_file($file['tmp_name'], $rutaDestino)) {
            $imagenes[] = "https://nivor.co/tiendas/$slug/banners/$nuevoNombre";
        }
    }
}

if (!empty($imagenes)) {
    echo json_encode(["success" => true, "imagenes" => $imagenes]);
} else {
    echo json_encode(["success" => false, "message" => "No se subieron imágenes"]);
}
