<?php

/**** RUTAS A LOS EJECUTABLES ****/
$INKSCAPE  = 'D:\\inkscape\\bin\\inkscape.exe';
$POTRACE   = 'D:\\Portrace\\potrace.exe';
$AUTOTRACE = 'D:\\autotrace\\autotrace.exe';
$MAGICK    = 'C:\\ImageMagick\\magick.exe';

/**** SUBIDA Y CONVERSIÓN ****/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['archivo'])) {

    /* 1. Datos básicos */
    $tmp      = $_FILES['archivo']['tmp_name'];
    $origName = pathinfo($_FILES['archivo']['name'], PATHINFO_FILENAME);
    $ext      = strtolower(pathinfo($_FILES['archivo']['name'], PATHINFO_EXTENSION));
    $outDir   = __DIR__ . '\\salida\\' . date('Ymd');
    if (!is_dir($outDir)) mkdir($outDir, 0777, true);

    $input    = "$outDir\\input.$ext";                 // copia estable
    $output   = "$outDir\\{$origName}.svg";            // destino final
    move_uploaded_file($tmp, $input);

    /* 2. Clasificar formato */
    $vectorExt = ['ai', 'cdr', 'pdf', 'eps', 'svg'];
    $rasterExt = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'tif', 'tiff', 'webp'];

    if (in_array($ext, $vectorExt)) {
        /* --- ARCHIVO VECTORIAL ---  */
        /* --- ARCHIVO VECTORIAL --- */
        $in  = escapeshellarg(str_replace('\\', '/', $input));   // entrada
        $out = escapeshellarg(str_replace('\\', '/', $output));  // salida

        $cmd = "\"$INKSCAPE\" $in " .                      // abre el AI/CDR/PDF
            "--export-type=svg " .                      // tipo de salida (sin comillas)
            "--export-filename=$out " .                 // ruta destino
            "--export-text-to-path 2>&1";               // convierte texto a curvas

    } elseif (in_array($ext, $rasterExt)) {
        /* --- IMAGEN RASTER, ELEGIR MODO --- */
        $colorMode = ($_POST['raster_mode'] ?? 'mono');   // mono | color

        if ($colorMode === 'mono') {
            // ---- 1 tinta ---------------------------------------------------------
            $pbm = "$outDir\\temp.pbm";
            $ppmCmd  = "\"$MAGICK\" " . escapeshellarg($input) .
                " -colorspace Gray -threshold 50% " . escapeshellarg($pbm);
            $traceCmd = "\"$POTRACE\" -s -o " . escapeshellarg($output) .
                ' ' . escapeshellarg($pbm);
        } else {
            // ---- a color ---------------------------------------------------------
            $ppm = "$outDir\\temp.ppm";
            $ppmCmd  = "\"$MAGICK\" " . escapeshellarg($input) .
                " -flatten " . escapeshellarg($ppm);
            $traceCmd = "\"$AUTOTRACE\" --output-format=svg --output-file=" .
                escapeshellarg($output) . ' ' . escapeshellarg($ppm);
        }

        $cmd = $ppmCmd . ' && ' . $traceCmd . ' 2>&1';
        $log = shell_exec($cmd);
    } else {
        die('Extensión no soportada.');
    }

    /* 3. Ejecutar y mostrar resultado */
    $log = shell_exec($cmd);

    if (file_exists($output)) {
        echo "✔ Conversión exitosa:<br><a href='salida/" . date('Ymd') . "/$origName.svg' target='_blank'>Descargar SVG</a>";
    } else {
        echo "<pre>ERROR durante la conversión:\n$log</pre>";
    }
}
?>

<!-- FORMULARIO -->
<h3>Vectorizar logo → SVG</h3>
<form method="post" enctype="multipart/form-data">
    <input type="file" name="archivo" required accept=".ai,.cdr,.pdf,.eps,.png,.jpg,.jpeg,.bmp,.gif,.tif,.tiff,.webp"><br><br>

    <!-- Opciones para raster -->
    <label>
        <input type="radio" name="raster_mode" value="mono" checked>
        Imagen ← 1 tinta (monocromo)
    </label>
    <label style="margin-left:1rem;">
        <input type="radio" name="raster_mode" value="color">
        Conservar colores básicos
    </label><br><br>

    <button>Convertir a SVG</button>
</form>