<?php
// actualizarvariaciones.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);

function js_log(string $msg)
{
    echo "<script>log('" . addslashes($msg) . "');</script>";
}
function js_prog(int $c, int $t)
{
    echo "<script>prog({$c}, {$t});</script>";
}

function slugify(string $text): string
{
    $text = preg_replace('/[^A-Za-z0-9]+/', '-', $text);
    $text = trim($text, '-');
    return strtolower($text);
}
/* --------------------------------------------------------------------------
 * 2. SALIDA HTML INICIAL (LOG + PROGRESO)
 * -------------------------------------------------------------------------- */
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Actualizar Variaciones WP</title></head><body>';
echo '<h1>Actualización de Variaciones</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. 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'           => 300,
        'connect_timeout'   => 30,
        'verify_ssl'        => false,
    ]
);

/* --------------------------------------------------------------------------
 * 6. PREPARAR QUERY
 * -------------------------------------------------------------------------- */
$sql = "
SELECT
    p.id,
    v.referenciaCPN,
    t.alto_cm,
    t.ancho_cm,
    t.largo_cm,
    t.peso_kg,
    v.PVP,
    v.minVenta,
    v.multiploVenta,
    iv.linkImagen,
    v.txtColor,
    p.wp_id      AS wpIDProducto,
    v.wp_id      AS wpIDVariante,
    v.idEstado,
    v.inventario AS stock,
    p.idEstado   AS estadoProducto
FROM tb_productos       p
INNER JOIN tb_productos_variantes v ON p.id = v.idProducto
INNER JOIN tb_tipo_envio           t ON p.idTipoEnvio = t.id
INNER JOIN tb_imagenes_variantes   iv ON v.id = iv.idVariante
WHERE
    v.PVP > 0
    AND p.wp_id > 0
    AND v.idEstado = 1
    
    AND p.idEstado = 1
";

if ($idFilter) {
    $sql .= " AND p.id = {$idFilter}";
}

$sql .= " ORDER BY v.wp_id";

$res = $mysqli->query($sql);
if (!$res) {
    die('Error en la consulta: ' . $mysqli->error);
}

$total   = $res->num_rows;
$curr    = 0;
$deleted = [];

/* --------------------------------------------------------------------------
 * 7. BUCLE PRINCIPAL
 * -------------------------------------------------------------------------- */
while ($row = $res->fetch_assoc()) {
    $curr++;
    echo "<script>js_prog({$curr}, {$total});</script>";
    echo "<script>js_log('Procesando producto {$row['wpIDProducto']} variante referencia {$row['referenciaCPN']} ({$curr}/{$total})');</script>";


    $prod_id     = (int)$row['wpIDProducto'];
    $var_id      = $row['wpIDVariante'] ? (int)$row['wpIDVariante'] : null;
    $sku         = $row['referenciaCPN'];
    $price       = (string)$row['PVP'];
    $stock       = (int)$row['stock'];
    $color       = trim($row['txtColor']);
    $dims        = [
        'length' => (string)$row['largo_cm'],
        'width'  => (string)$row['ancho_cm'],
        'height' => (string)$row['alto_cm'],
    ];
    $weight      = (string)$row['peso_kg'];

    // ➊ — FORCE: eliminar variaciones existentes una sola vez por producto
    if ($force && empty($deleted[$prod_id])) {
        js_log("  → force=1: borrando variaciones existentes para producto {$prod_id}");
        try {
            $vars = $wc->get("products/{$prod_id}/variations");
            foreach ($vars as $v) {
                $wc->delete("products/{$prod_id}/variations/{$v->id}", ['force' => true]);
            }
            js_log("  → variaciones eliminadas");
        } catch (HttpClientException $e) {
            js_log("  → ERROR borrando variaciones: {$e->getMessage()}");
        }
        $deleted[$prod_id] = true;
    }

    // ➋ — DETERMINAR CREAR o ACTUALIZAR
    $is_new = !$var_id || $force;

    // ──── ➊ bis ────
    //  – 1) Localizar ID del atributo global en Woo
    $attr_slug = 'pa_color-tipo';
    $all_attrs = $wc->get("products/attributes", ['search' => $attr_slug]);
    $attr_id   = null;
    foreach ($all_attrs as $A) {
        if ($A->slug === $attr_slug) {
            $attr_id = $A->id;
            break;
        }
    }
    if (!$attr_id) {
        // si no existe el atributo global, créalo
        $newA = $wc->post("products/attributes", [
            'name' => 'Color/Tipo',
            'slug' => $attr_slug,
            'type' => 'select'
        ]);
        $attr_id = $newA->id;
    }

    // ──── ➊ bis ────
    //  – 1) Localizar o crear atributo global (igual que antes)…
    //  – 2) Localizar o crear término ($term_id)…
    // ───────────────────────────────────────────────────────────────

    //  – 3) TRAER ATRIBUTOS ACTUALES DEL PADRE Y RECONSTRUIR EL ARRAY
    $prod          = $wc->get("products/{$prod_id}");
    $updatedAttrs  = [];
    $has_attr      = false;
    foreach ($prod->attributes as $PA) {
        $options = (array)$PA->options;
        // Si ya es nuestro atributo, marcamos flag y nos aseguramos de incluir este término
        if ((int)$PA->id === $attr_id) {
            $has_attr = true;
            if (!in_array($color, $options, true)) {
                $options[] = $color;
            }
        }
        $updatedAttrs[] = [
            'id'        => (int)$PA->id,
            'name'      => $PA->name,
            'position'  => (int)$PA->position,
            'visible'   => (bool)$PA->visible,
            'variation' => (bool)$PA->variation,
            'options'   => $options,
        ];
    }

    //  – 4) Si no existía, lo agregamos al final
    if (!$has_attr) {
        $updatedAttrs[] = [
            'id'        => $attr_id,
            'name'      => 'Color/Tipo',       // debe coincidir con el label del atributo global
            'position'  => count($updatedAttrs),
            'visible'   => true,
            'variation' => true,
            'options'   => [$color],
        ];
    }

    //  – 5) ACTUALIZAR PRODUCTO PADRE
    try {
        $wc->put("products/{$prod_id}", [
            'attributes' => $updatedAttrs
        ]);
        js_log("  → atributo Color/Tipo actualizado en padre {$prod_id}");
    } catch (HttpClientException $e) {
        js_log("  → ERROR actualizando atributos padre: {$e->getMessage()}");
    }



    // ➌ — PREPARAR DATA BÁSICA
    $data = [
        'sku'            => $sku,
        'regular_price'  => $price,
        'manage_stock'   => true,
        'stock_quantity' => $stock,
        'meta_data'      => [
            ['key' => 'min_quantity', 'value' => (int) $row['minVenta']],
            ['key' => 'product_step',  'value' => (int) $row['multiploVenta']],
        ],
        'status'         => 'publish',
        'weight'         => $weight,
        'dimensions'     => $dims,
        'description'    => $color,
        'attributes'     => [
            ['id' => $attr_id, 'option' => $color],
        ],
    ];


    // ➍ — ASIGNAR IMAGEN EXISTENTE
    // 1) obtener nombre con y sin extensión
    $fileWithExt = basename(parse_url(trim($row['linkImagen']), PHP_URL_PATH));
    $fileBase    = pathinfo($fileWithExt, PATHINFO_FILENAME);

    // 2) buscar sólo entre attachments del producto
    $sqlImg = "
    SELECT p.ID
      FROM db_compranet_wp.wp_posts p
      JOIN db_compranet_wp.wp_postmeta pm 
        ON pm.post_id = p.ID
     WHERE p.post_type = 'attachment'
       AND p.post_parent = ?
       AND pm.meta_key   = '_wp_attached_file'
       AND pm.meta_value LIKE CONCAT('%', ?, '%')
     LIMIT 1
";
    $stmt = $mysqli->prepare($sqlImg);
    $stmt->bind_param('is', $prod_id, $fileBase);
    $stmt->execute();
    $stmt->bind_result($attachmentID);
    $exists = (bool)$stmt->fetch();
    $stmt->close();

    if ($exists) {
        $data['image'] = ['id' => (int)$attachmentID];
    } else {
        js_log("  → La imagen aún no se ha subido al servidor (archivo: {$file})");
        continue;
    }


    // ➎ — EJECUTAR LLAMADA
    try {
        if ($is_new) {
            $resp = $wc->post("products/{$prod_id}/variations", $data);
            js_log("  → variante creada ID {$resp->id}");
        } else {
            $wc->put("products/{$prod_id}/variations/{$var_id}", $data);
            js_log("  → variante actualizada ID {$var_id}");
        }
    } catch (HttpClientException $e) {
        js_log("  → ERROR al " . ($is_new ? 'crear' : 'actualizar') . ": {$e->getMessage()}");
        continue;
    }
}

/* --------------------------------------------------------------------------
 * 8. ACTUALIZAR ID WP EN BASE DE DATOS
 * -------------------------------------------------------------------------- */
js_log("Llamando a procedimiento almacenado actualizar_id_wp()");
if ($mysqli->query("CALL actualizar_id_wp()")) {
    js_log("  → SP ejecutado correctamente.");
} else {
    js_log("  → ERROR SP: " . $mysqli->error);
}

// 👉 Llamar a checklist(NULL) justo después
js_log("Llamando a procedimiento almacenado checklist(NULL)");
if ($mysqli->query("CALL checklist(NULL)")) {
    js_log("  → SP checklist ejecutado correctamente.");
} else {
    js_log("  → ERROR SP checklist: " . $mysqli->error);
}
/* --------------------------------------------------------------------------
 * 9. CIERRE
 * -------------------------------------------------------------------------- */
js_log("Proceso finalizado.");
echo '</body></html>';
$mysqli->close();
