<?php
date_default_timezone_set('America/Bogota');
set_time_limit(0);

// Parámetros de conexión
$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");

// (Opcional) prepara 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 de diferencias
$sql = "
SELECT 
    v.referenciaCPN,
    v.referenciaProveedor,
    t.wp_id             AS wp_id_padre,
    v.wp_id             AS 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
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);
if (!$res) {
    die("Error en la consulta: " . $conn->error);
}
$rows = $res->fetch_all(MYSQLI_ASSOC);

// --- HTML de salida ---
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Diferencias de Inventario - Proveedor #<?= $id_proveedor ?></title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 1em;
        }

        th,
        td {
            border: 1px solid #999;
            padding: 6px;
            text-align: center;
        }

        .diff-positive {
            color: green;
        }

        .diff-negative {
            color: red;
        }

        .total-foot {
            font-weight: bold;
        }
    </style>
</head>

<body>

    <h2>Proveedor #<?= $id_proveedor ?> — Diferencias Encontradas</h2>

    <table>
        <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 Vendido</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $sumTotal = 0;
            foreach ($rows as $r) {
                // Cálculo de variación y vendido
                $varStock = $r['new_stock'] - $r['old_stock'];
                $soldQty  = $varStock < 0 ? -$varStock : 0;

                // Formato de 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 de 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 de 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 vendido
                $netFmt   = '$ ' . number_format($r['precioNeto'], 0, ',', '.');
                $totalRow = $soldQty * $r['precioNeto'];
                $sumTotal += $totalRow;
                $totFmt   = '$ ' . number_format($totalRow, 0, ',', '.');

                // (Opcional) inserción en la tabla de movimientos
                if ($insertStmt) {
                    $insertStmt->bind_param(
                        'ssiiid',
                        $r['referenciaCPN'],
                        $r['referenciaProveedor'],
                        $varStock,
                        $id_proveedor,
                        $r['precioNeto'],
                        $totalRow
                    );
                    $insertStmt->execute();
                }

                echo "<tr>
                <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>
              </tr>";
            }
            ?>
        </tbody>
        <tfoot>
            <tr class="total-foot">
                <td colspan="8" style="text-align:right">Gran Total Vendido:</td>
                <td><?php echo '$ ' . number_format($sumTotal, 0, ',', '.'); ?></td>
            </tr>
        </tfoot>
    </table>

</body>

</html>
<?php
// Cierre de conexiones
if ($insertStmt) {
    $insertStmt->close();
}
$conn->close();
