<?php
require __DIR__ . '/vendor/autoload.php';

date_default_timezone_set('America/Bogota');

use Automattic\WooCommerce\Client;

set_time_limit(0);

// Parámetros
$servername     = "localhost";
$username       = "ndconsulta";
$password       = "Nitro2021";
$dbname         = "db_compranet";
$id_proveedor   = isset($_GET['id_proveedor']) ? (int)$_GET['id_proveedor'] : 0;
if ($id_proveedor === 0) {
    die("Por favor proporciona un id_proveedor válido.");
}

// Conexión MySQL
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Conexión fallida: " . $conn->connect_error);
}
$conn->set_charset("utf8");

// Cliente WooCommerce
$woocommerce = new Client(
    'https://compranet.com.co',
    'ck_910af40e780677e03593d388885a2e58b7c4fa43',
    'cs_2983cea05dbc631dc6236c61c79feb35a61666cf',
    ['version' => 'wc/v3']
);

// Preparar inserción en movimiento_inventarios
$insertStmt = $conn->prepare(
    "INSERT INTO db_inventarios_compranet.movimiento_inventarios
        (ref_cpn, ref_proveedor, var_stock, idProveedor, precioNeto, total)
     VALUES (?, ?, ?, ?, ?, ?)"
);

// Consulta con los campos solicitados (asegúrate de incluir wp_id y wp_id_padre)
$sql = "
SELECT 
    v.referenciaCPN,
    v.referenciaProveedor,
      t.wp_id             AS wp_id_padre,
    v.wp_id,
    t.nombre                    AS nombre,
    v.txtColor                  AS color,
    wpv.stock                   AS old_stock,
    v.inventario                AS new_stock,
    wpv.precio                  AS old_price,
    v.PVP                       AS new_price,
    wpv.precioreducido          AS old_reduced,
    v.PVPReducido               AS new_reduced,
    v.precioNetoProveedor       AS precioNeto,
    v.wp_id                     AS wp_id,
    t.wp_id                     AS wp_id_padre
FROM tb_productos_variantes v
JOIN tb_productos t    ON v.idProducto = t.id
JOIN wp_productos_variacion wpv ON v.wp_id = wpv.idVariacion
WHERE t.idProveedor = $id_proveedor
  AND (
    COALESCE(v.PVP,0)           <> COALESCE(wpv.precio,0)
    OR COALESCE(v.PVPReducido,0) <> COALESCE(wpv.precioreducido,0)
    OR COALESCE(v.inventario,0)  <> COALESCE(wpv.stock,0)
)
ORDER BY v.referenciaCPN;
";
$res   = $conn->query($sql);
$rows  = $res->fetch_all(MYSQLI_ASSOC);
$total = count($rows);

// Prepara mapeo y lote para WooCommerce
$rowIndexMap = [];
$variations   = [];

// --- HTML de encabezado ---
echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Movimiento Inventarios</title>
<style>
  #progress-container { width:100%; background:#f3f3f3; border:1px solid #ccc; margin-bottom:1em; }
  #progress-bar { width:0; height:25px; background:#4caf50; text-align:center; line-height:25px; color:white; }
  table { border-collapse:collapse; width:100%; margin-bottom:1em; }
  th,td { border:1px solid #999; padding:4px; text-align:center; }
  .diff-positive { color: green; }
  .diff-negative { color: red; }
  .total-foot { font-weight:bold; }
  .log { white-space:pre-wrap; font-family:monospace; height:200px; overflow:auto; background:#f9f9f9; padding:5px; }
</style>
</head><body>';

echo "<h2>Movimiento de Inventarios - Proveedor #{$id_proveedor}</h2>";

// Barra de progreso
echo '<div id="progress-container"><div id="progress-bar">0%</div></div>';

// Tabla HTML con columna Estado al final
echo '<table>';
echo '<thead><tr>
        <th>Ref CPN</th>
        <th>Ref Proveedor</th>
        <th>Nombre</th>
        <th>Color</th>
        <th>Stock</th>
        <th>Precio</th>
        <th>Precio Reducido</th>
        <th>Precio Neto</th>
        <th>Total</th>
        <th>Estado</th>
      </tr></thead><tbody>';

$sumTotal = 0;
foreach ($rows as $i => $r) {
    // Variación de stock
    $varStock = $r['new_stock'] - $r['old_stock'];
    $soldQty  = $varStock < 0 ? -$varStock : 0;

    // Formato stock
    $stockCh = "{$r['old_stock']} → {$r['new_stock']}";
    if ($varStock !== 0) {
        $cls    = $varStock > 0 ? 'diff-positive' : 'diff-negative';
        $sign   = $varStock > 0 ? '+' : '';
        $stockCh .= " <span class=\"{$cls}\">({$sign}{$varStock})</span>";
    }

    // Formato precio
    $fmtOldP = '$ ' . number_format($r['old_price'], 0, ',', '.');
    $fmtNewP = '$ ' . number_format($r['new_price'], 0, ',', '.');
    if ($r['old_price'] == $r['new_price']) {
        $priceCh = "{$fmtNewP} (=)";
    } else {
        $diffP   = $r['new_price'] - $r['old_price'];
        $clsP    = $diffP > 0 ? 'diff-positive' : 'diff-negative';
        $signP   = $diffP > 0 ? '+' : '';
        $fmtDiff = number_format(abs($diffP), 0, ',', '.');
        $priceCh = "{$fmtOldP} → {$fmtNewP} <span class=\"{$clsP}\">({$signP}{$fmtDiff})</span>";
    }

    // Formato precio reducido
    $fmtOldR = '$ ' . number_format($r['old_reduced'], 0, ',', '.');
    $fmtNewR = '$ ' . number_format($r['new_reduced'], 0, ',', '.');
    if ($r['old_reduced'] == $r['new_reduced']) {
        $redCh = "{$fmtNewR} (=)";
    } else {
        $diffR   = $r['new_reduced'] - $r['old_reduced'];
        $clsR    = $diffR > 0 ? 'diff-positive' : 'diff-negative';
        $signR   = $diffR > 0 ? '+' : '';
        $fmtDiffR = number_format(abs($diffR), 0, ',', '.');
        $redCh   = "{$fmtOldR} → {$fmtNewR} <span class=\"{$clsR}\">({$signR}{$fmtDiffR})</span>";
    }

    // Precio neto y total
    $netFmt    = '$ ' . number_format($r['precioNeto'], 0, ',', '.');
    $totalRow  = $soldQty * $r['precioNeto'];
    $sumTotal += $totalRow;
    $totFmt    = '$ ' . number_format($totalRow, 0, ',', '.');

    // Insertar movimiento
    $insertStmt->bind_param(
        'ssiiid',
        $r['referenciaCPN'],
        $r['referenciaProveedor'],
        $varStock,
        $id_proveedor,
        $r['precioNeto'],
        $totalRow
    );
    $insertStmt->execute();

    // Preparar batch WooCommerce
    $parent = $r['wp_id_padre'];
    $rowIndexMap[$parent][] = $i;
    $variations[$parent][] = [
        'id'             => $r['wp_id'],
        'stock_quantity' => $r['new_stock'],
        'regular_price'  => (string)$r['new_price'],
        'sale_price'     => (string)$r['new_reduced']
    ];

    // Fila HTML
    echo "<tr id=\"row-{$i}\">"
        . "<td>{$r['referenciaCPN']}</td>"
        . "<td>{$r['referenciaProveedor']}</td>"
        . "<td>{$r['nombre']}</td>"
        . "<td>{$r['color']}</td>"
        . "<td>{$stockCh}</td>"
        . "<td>{$priceCh}</td>"
        . "<td>{$redCh}</td>"
        . "<td>{$netFmt}</td>"
        . "<td>{$totFmt}</td>"
        . "<td class=\"status\" id=\"status-{$i}\"></td>"
        . "</tr>";
}

echo '</tbody>';
echo '<tfoot><tr class="total-foot">'
    . '<td colspan="8" style="text-align:right">Gran Total:</td>'
    . '<td>$ ' . number_format($sumTotal, 0, ',', '.') . '</td>'
    . '<td></td>'
    . '</tr></tfoot>';
echo '</table>';

// Panel de log
echo '<h3>Log de procesamiento</h3>';
echo '<div id="log" class="log"></div>';

// Abrir archivo de log
$logFile   = __DIR__ . "/{$id_proveedor}_inv_update_" . date('Ymd_His') . ".log";
$logHandle = fopen($logFile, 'a');
fwrite($logHandle, "=== Inicia actualización " . date('Y-m-d H:i:s') . " ===\n");

// Procesar en lotes
$batchSize = 100;
$counter   = 0;

foreach ($variations as $parent => $batch) {
    try {
        $woocommerce->post("products/{$parent}/variations/batch", ['update' => $batch]);
        $msg = "Producto #{$parent} actualizado en WP.\n";
        echo "<script>document.getElementById('log').innerText += " . json_encode($msg) . ";</script>";
        fwrite($logHandle, $msg);

        // Marcar estado sin borrar el total
        foreach ($rowIndexMap[$parent] as $idx) {
            echo "<script>document.getElementById('row-{$idx}').style.opacity = 0.5;</script>";
            echo "<script>document.getElementById('status-{$idx}').innerText = '✓';</script>";
        }
    } catch (Exception $e) {
        $err = "ERROR WP #{$parent}: " . $e->getMessage() . "\n";
        echo "<script>document.getElementById('log').innerText += " . json_encode($err) . ";</script>";
        fwrite($logHandle, $err);
    }

    // Avanzar barra
    $counter += count($batch);
    $p = round(($counter / $total) * 100);
    echo "<script>
            document.getElementById('progress-bar').style.width='{$p}%';
            document.getElementById('progress-bar').innerText='{$p}%';
          </script>";
    echo str_repeat(' ', 1024);
    flush();
}

fwrite($logHandle, "=== Fin " . date('Y-m-d H:i:s') . " ===\n\n");
fclose($logHandle);
$insertStmt->close();
$conn->close();

echo '</body></html>';
