<?php
// actualizarimageneswp.php
require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;

/* --------------------------------------------------------------------------
 * 1. CONFIGURACIÓN BÁSICA
 * -------------------------------------------------------------------------- */

set_time_limit(0);
header('Content-Type: text/html; charset=UTF-8');
while (ob_get_level()) ob_end_clean();
ob_implicit_flush(true);

/* --------------------------------------------------------------------------
 * 2. SALIDA HTML INICIAL (LOG + PROGRESO)
 * -------------------------------------------------------------------------- */
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Actualizar Imágenes WP</title></head><body>';
echo '<h1>Actualización de Imágenes</h1>';
echo '<progress id="progressBar" value="0" max="10" 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. PARÁMETROS GET
 * -------------------------------------------------------------------------- */
$idFilter = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$force    = $idFilter > 0 && isset($_GET['force']) && $_GET['force'] == 1;

/* --------------------------------------------------------------------------
 * 4. CONEXIÓN MYSQL
 * -------------------------------------------------------------------------- */
$mysqli = new mysqli('localhost', 'ndconsulta', 'Nitro2021', 'db_compranet');
if ($mysqli->connect_error) die('Conexión fallida: ' . $mysqli->connect_error);

/* --------------------------------------------------------------------------
 * 5. CLIENTE WOOCOMMERCE
 * -------------------------------------------------------------------------- */
$wc = new Client(
    'https://compranet.com.co',
    'ck_910af40e780677e03593d388885a2e58b7c4fa43',
    'cs_2983cea05dbc631dc6236c61c79feb35a61666cf',
    [
        'wp_api'            => true,
        'version'           => 'wc/v3',
        'query_string_auth' => true,
        'timeout'           => 60,
        'verify_ssl'        => false
    ]
);

/* --------------------------------------------------------------------------
 * 6. CONSULTA DE IMÁGENES
 * -------------------------------------------------------------------------- */
$sql = "
SELECT
  tip.idProducto,
  tip.linkImagen,
  tip.esPrincipal,
  tp.wp_id
FROM tb_imagenes_principal tip
JOIN tb_productos tp ON tp.id = tip.idProducto
WHERE tip.idEstado = 1
  AND tp.wp_id      > 0
";

if ($idFilter)       $sql .= " AND tip.idProducto = {$idFilter}";
$sql .= " AND LOWER(tip.linkImagen) LIKE 'j:%'";

$sql .= ' ORDER BY tp.wp_id DESC';

$res = $mysqli->query($sql);
if (!$res) die('Error en la consulta: ' . $mysqli->error);

$total    = $res->num_rows;
$curr     = 0;
$cleaned  = [];

/* --------------------------------------------------------------------------
 * 7. BUCLE PRINCIPAL
 * -------------------------------------------------------------------------- */
while ($row = $res->fetch_assoc()) {
    $curr++;
    echo "<script>prog($curr,$total);log('Procesando wp_id={$row['wp_id']} ($curr/$total)');</script>";

    /* ---------- URL NORMALIZADA ---------- */
    $url = trim($row['linkImagen'] ?? '');
    if ($url === '') {
        echo "<script>log('  → URL vacía, skip.');</script>";
        continue;
    }

    if (preg_match('~^j:[/\\\\]~i', $url)) {
        $url = preg_replace('~^j:[/\\\\]~i', 'https://sistema.compranet.com.co/', $url, 1);
    }
    $url = str_replace('\\', '/', $url);   // forzar separadores /
    $url = strtolower($url);

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        echo "<script>log('  → URL inválida ($url), skip.');</script>";
        continue;
    }

    $isMain = (int)$row['esPrincipal'] === 1;

    /* ---------- FORCE: vaciar una sola vez ---------- */
    if ($force && empty($cleaned[$row['wp_id']])) {
        try {
            $wc->put("products/{$row['wp_id']}", ['images' => []]);
            echo "<script>log('  → Galería vaciada (force=1).');</script>";
        } catch (HttpClientException $e) {
            echo "<script>log('  → ERROR vaciando: {$e->getMessage()}');</script>";
        }
        $cleaned[$row['wp_id']] = true;
    }

    /* ---------- 1) OBTENER PRODUCTO ---------- */
    try {
        $product = $wc->get("products/{$row['wp_id']}");
    } catch (HttpClientException $e) {
        echo "<script>log('  → ERROR get producto: {$e->getMessage()}');</script>";
        continue;
    }

    $images = [];
    foreach ($product->images as $i => $img)
        $images[] = ['id' => $img->id, 'src' => $img->src, 'position' => $i];

    /* --------------------------------------------------------------------------
 * 2) PREPARAR IMAGEN (ahora con manejo claro de force y sin goto)
 * -------------------------------------------------------------------------- */
    $file = basename(parse_url($url, PHP_URL_PATH));  // "3016001a.jpg"

    // ➊ — Levantamos las imágenes actuales y sus basenames
    $product = $wc->get("products/{$row['wp_id']}");
    $images  = [];
    foreach ($product->images as $i => $img) {
        $images[] = ['id' => $img->id, 'src' => $img->src, 'position' => $i];
    }
    $enlazados = array_map(fn($img) => basename(parse_url($img['src'], PHP_URL_PATH)), $images);

    // ➋ — Caso FORCE = re-suba TODO y saltamos el resto
    if ($force) {
        $new = ['src' => $url];
        if ($isMain) array_unshift($images, $new);
        else         $images[] = $new;

        // reindexamos
        foreach ($images as $pos => &$img) {
            $img['position'] = $pos;
        }

        // actualizamos solo una vez
        try {
            $wc->put("products/{$row['wp_id']}", ['images' => $images]);
            echo "<script>log('  → OK (force)');</script>";
        } catch (HttpClientException $e) {
            echo "<script>log('  → ERROR put force: {$e->getMessage()}');</script>";
        }
        continue;   // IMPORTANTE: no siga evaluando el resto
    }

    // ➌ — Si ya está enlazada por nombre, nada que hacer
    if (in_array($file, $enlazados, true)) {
        echo "<script>log('  → {$file} ya enlazada (por nombre).');</script>";
        continue;
    }

    // ➍ — Buscamos attachment ID en WP
    $stmt = $mysqli->prepare("
    SELECT post_id
      FROM db_compranet_wp.wp_postmeta
     WHERE meta_key   = '_wp_attached_file'
       AND meta_value LIKE CONCAT('%/', ?)
     LIMIT 1
");
    $stmt->bind_param('s', $file);
    $stmt->execute();
    $stmt->bind_result($attachmentID);
    $exists = (bool)$stmt->fetch();
    $stmt->close();

    $attachmentID = $exists ? (int)$attachmentID : null;
    $galleryIDs   = array_column($images, 'id');
    $inGallery    = $attachmentID && in_array($attachmentID, $galleryIDs, true);

    // ➎ — Si ya existía y está en la galería, nada que hacer
    if ($inGallery) {
        echo "<script>log('  → {$file} ya enlazada (por ID).');</script>";
        continue;
    }

    // ➏ — Si existe en la librería pero no estaba en este producto, lo enlazamos
    if ($attachmentID) {
        $link = ['id' => $attachmentID];
        if ($isMain) array_unshift($images, $link);
        else         $images[] = $link;

        // ➐ — Si ni existe, lo subimos por URL
    } else {
        $new = ['src' => $url];
        if ($isMain) array_unshift($images, $new);
        else         $images[] = $new;
    }

    // ➑ — Reindexamos posiciones y actualizamos
    foreach ($images as $pos => &$img) {
        $img['position'] = $pos;
    }
    try {
        $wc->put("products/{$row['wp_id']}", ['images' => $images]);
        echo "<script>log('  → OK (actualizado)');</script>";
    } catch (HttpClientException $e) {
        echo "<script>log('  → ERROR put: {$e->getMessage()}');</script>";
    }


    /* ---------- 3) REINDEXAR POSITIONS ---------- */
    foreach ($images as $pos => &$img) $img['position'] = $pos;

    /* ---------- 4) ACTUALIZAR PRODUCTO ---------- */
    putProduct:
    try {
        $wc->put("products/{$row['wp_id']}", ['images' => $images]);
        echo "<script>log('  → OK');</script>";
    } catch (HttpClientException $e) {
        echo "<script>log('  → ERROR put: {$e->getMessage()}');</script>";
    }
}

echo "<script>log('Proceso finalizado.');</script>";
echo '</body></html>';
$mysqli->close();
