<?php
// arreglar_nombres_imagenes_variantes.php
set_time_limit(0);
header('Content-Type: text/html; charset=UTF-8');
while (ob_get_level()) ob_end_clean();
ob_implicit_flush(true);

echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Arreglar Imágenes Variantes</title></head><body>';
echo '<h1>Arreglar Nombres de Imágenes Variantes en BD y Disco</h1>';
echo '<progress id="progressBar" value="0" max="0" style="width:100%;height:20px;"></progress>';
echo '<pre id="log" style="background:#f0f0f0;padding:10px;font-family:monospace;"></pre>';
echo <<<JS
<script>
function log(msg){ document.getElementById('log').textContent += msg + "\\n"; }
function prog(curr,total){ let b=document.getElementById('progressBar'); b.max=total; b.value=curr; }
</script>
JS;

// Conexión MySQL
$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet');
if ($mysqli->connect_error) die('MySQL error: ' . $mysqli->connect_error);
$mysqli->set_charset('utf8mb4');

// Directorio base
$baseDirRaw = 'E:/www/sistema.compranet.com.co/public/images';
$baseDir    = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $baseDirRaw);
if (!is_dir($baseDir)) {
    echo "<script>log(" . json_encode("Error: no existe directorio {$baseDir}") . ");</script>";
    exit;
}

// Normalización (quita acentos, etc.)
function normalizeName(string $s): string
{
    if (class_exists('Normalizer')) {
        $s = Normalizer::normalize($s, Normalizer::FORM_C);
    }
    $t = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s) ?: $s;
    return mb_strtolower($t, 'UTF-8');
}

// Consulta variantes
$sql = "
  SELECT
    tiv.id         AS variant_id,
    tiv.linkImagen AS linkImagen
  FROM tb_imagenes_principal tiv
  ORDER BY tiv.id
";
$res = $mysqli->query($sql);
if (!$res) die('Error en consulta: ' . $mysqli->error);

$total = $res->num_rows;
$curr  = 0;

while ($row = $res->fetch_assoc()) {
    $curr++;
    $vid      = $row['variant_id'];
    $link     = $row['linkImagen'];

    echo "<script>prog({$curr},{$total}); log(" . json_encode("[$curr/$total] Procesando variant_id={$vid}") . ");</script>";

    // Construir ruta real
    $relative = preg_replace('~^[A-Za-z]:[\\\\/]images~i', '', $link);
    $relative = str_replace(['\\', '/'], '/', $relative);
    $relative = ltrim($relative, '/');
    $oldPath  = $baseDir . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);

    $dir      = dirname($oldPath);
    $original = basename($oldPath);

    // Generar nombre sanitizado
    $sanitized = preg_replace('/[^A-Za-z0-9\-\._]/', '_', $original);
    $sanitized = preg_replace('/_+/', '_', $sanitized);
    $sanitized = trim($sanitized, '_');
    $sanitized = strtolower($sanitized);

    $newPath = $dir . DIRECTORY_SEPARATOR . $sanitized;
    $newRel  = 'J:/images/' . str_replace(DIRECTORY_SEPARATOR, '/', ltrim(str_replace($baseDir, '', $newPath), DIRECTORY_SEPARATOR));

    $existsFlag = 0;

    // 1) Intentar renombrar archivo original
    if (file_exists($oldPath)) {
        if ($sanitized !== $original && @rename($oldPath, $newPath)) {
            echo "<script>log(" . json_encode("  → Renombrado disco: {$original} → {$sanitized}") . ");</script>";
            $existsFlag = 1;
            $stmt = $mysqli->prepare("UPDATE tb_imagenes_principal SET linkImagen=?, existe=1 WHERE id=?");
            $stmt->bind_param('si', $newRel, $vid);
            $stmt->execute();
            $stmt->close();
        } else {
            // si no hace falta renombrar o fallo de rename
            echo "<script>log(" . json_encode("  → No renombrado o sin cambios: {$original}") . ");</script>";
        }
    } else {
        echo "<script>log(" . json_encode("  → No existe archivo original: {$oldPath}") . ");</script>";
    }

    // 2) Si no renombró, buscar si ya existe con nombre sanitizado
    if (!$existsFlag && file_exists($newPath)) {
        echo "<script>log(" . json_encode("  → Encontrado con nombre sanitizado: {$sanitized}") . ");</script>";
        $existsFlag = 1;
        $stmt = $mysqli->prepare("UPDATE tb_imagenes_principal SET linkImagen=?, existe=1 WHERE id=?");
        $stmt->bind_param('si', $newRel, $vid);
        $stmt->execute();
        $stmt->close();
    }

    // 3) Si aún no existe, marcar existe=0
    if (!$existsFlag) {
        echo "<script>log(" . json_encode("  → Archivo no encontrado tras intentos") . ");</script>";
        $stmt = $mysqli->prepare("UPDATE tb_imagenes_principal SET existe=0 WHERE id=?");
        $stmt->bind_param('i', $vid);
        $stmt->execute();
        $stmt->close();
    }

    // 4) Verificar existencia final y reintentar renombrar original si falta
    if ($existsFlag === 0) {
        // reintentar desde nombre antiguo
        if (file_exists($oldPath) && !file_exists($newPath)) {
            if (@rename($oldPath, $newPath)) {
                echo "<script>log(" . json_encode("  → Renombrado en reintento: {$original} → {$sanitized}") . ");</script>";
                $stmt = $mysqli->prepare("UPDATE tb_imagenes_principal SET linkImagen=?, existe=1 WHERE id=?");
                $stmt->bind_param('si', $newRel, $vid);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
}

echo "<script>log('Proceso variantes completado.');</script>";
echo '</body></html>';
$mysqli->close();
