<?php
// purgarimagenes.php
require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;

/* 1. CONFIG */

set_time_limit(0);
header('Content-Type: text/html; charset=UTF-8');
while (ob_get_level()) ob_end_clean();
ob_implicit_flush(true);

// 2. INTERFAZ
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Purgar Imágenes WP</title></head><body>';
echo '<h1>Purgar y Actualizar Imágenes</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(t){document.getElementById('log').textContent+=t+"\\n";}
function prog(c,t){const b=document.getElementById('progressBar');b.max=t;b.value=c;}
</script>
JS;

// 3. CONEXIÓN MySQL
$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet');
if ($mysqli->connect_error) die('MySQL error: ' . $mysqli->connect_error);

// 4. CLIENTE WooCommerce (timeout + connect_timeout)
$wc = new Client(
    'https://compranet.com.co',
    'ck_910af40e780677e03593d388885a2e58b7c4fa43',
    'cs_2983cea05dbc631dc6236c61c79feb35a61666cf',
    [
        'wp_api'          => true,
        'version'         => 'wc/v3',
        'query_string_auth' => true,
        'timeout'         => 120,
        'connect_timeout' => 30,
        'verify_ssl'      => false
    ]
);

// 5. LEER imágenes desde tu tabla
$sql = "
  SELECT tp.wp_id, tip.linkImagen, tip.esPrincipal
    FROM tb_imagenes_principal tip
    JOIN tb_productos tp ON tp.id = tip.idProducto
   WHERE tip.idEstado = 1
     AND tp.wp_id    > 0
ORDER BY tp.wp_id, tip.esPrincipal DESC
";
$res = $mysqli->query($sql);
if (!$res) die('Consulta error: ' . $mysqli->error);

// 6. AGRUPAR
$byProduct = [];
while ($r = $res->fetch_assoc()) {
    $byProduct[(int)$r['wp_id']][] = [
        'url'     => $r['linkImagen'],
        'is_main' => (int)$r['esPrincipal'] === 1
    ];
}
$res->close();

$total = count($byProduct);
$curr  = 0;
$batchSize   = 20;
$batch       = [];

/**
 * Envía un batch con reintentos
 */
function sendBatch($wc, $items, $label)
{
    try {
        $wc->post('products/batch', ['update' => $items]);
        echo "<script>log('  → Batch {$label} OK (" . count($items) . " productos)');</script>";
    } catch (HttpClientException $e) {
        echo "<script>log('  → ERROR batch {$label}: {$e->getMessage()}');</script>";
    }
}

// 7. PROCESAR
foreach ($byProduct as $wp_id => $rawImgs) {
    $curr++;
    echo "<script>prog($curr,$total);log('Procesando wp_id={$wp_id} ($curr/$total)');</script>";

    // 7.1. Normalizar y preparar
    $expected = count($rawImgs);
    $temp     = [];
    foreach ($rawImgs as $r) {
        $u = trim($r['url']);
        if (preg_match('~^j:[/\\\\]~i', $u)) {
            $u = preg_replace('~^j:[/\\\\]~i', 'https://sistema.compranet.com.co/', $u, 1);
        }
        $u = str_replace('\\', '/', $u);
        $u = strtolower($u);
        if (!filter_var($u, FILTER_VALIDATE_URL)) {
            echo "<script>log('  → URL inválida omitida: {$u}');</script>";
            continue;
        }
        $temp[] = ['src' => $u, 'is_main' => $r['is_main']];
    }

    // 7.2. Ordenar: la principal primero
    usort($temp, function ($a, $b) {
        return ($a['is_main'] === $b['is_main']) ? 0 : ($a['is_main'] ? -1 : 1);
    });

    // 7.3. Asignar posición
    $images = [];
    foreach ($temp as $pos => $img) {
        $images[] = ['src' => $img['src'], 'position' => $pos];
    }
    $prepared = count($images);
    echo "<script>log('  → Ítems BD: {$expected}, a subir: {$prepared}');</script>";

    // 7.4. Si tiene muchas imágenes, actualizamos individualmente
    if ($prepared > 8) {
        echo "<script>log('  → Más de 8 imágenes: uso PUT individual');</script>";
        try {
            $wc->put("products/{$wp_id}", ['images' => $images]);
            echo "<script>log('  → wp_id={$wp_id} OK (PUT)');</script>";
        } catch (HttpClientException $e) {
            echo "<script>log('  → ERROR PUT wp_id={$wp_id}: {$e->getMessage()}');</script>";
        }
        continue;
    }

    // 7.5. Sino, lo agregamos al batch
    $batch[] = ['id' => $wp_id, 'images' => $images];
    if (count($batch) >= $batchSize) {
        sendBatch($wc, $batch, "Hasta $curr");
        $batch = [];
    }
}

// 7.6. Último batch
if ($batch) {
    sendBatch($wc, $batch, "Final");
}

echo "<script>log('¡Listo!');</script>";
echo '</body></html>';
$mysqli->close();
