<?php
session_start();
include '../includes/session_control.php';
include '../db/db.php';

// Helper para contraste de texto sobre color de fondo
function getTextColor(string $hex): string
{
    $h = ltrim($hex, '#');
    $r = hexdec(substr($h, 0, 2));
    $g = hexdec(substr($h, 2, 2));
    $b = hexdec(substr($h, 4, 2));
    $lum = ($r * 0.299 + $g * 0.587 + $b * 0.114) / 255;
    return $lum > 0.5 ? '#000000' : '#ffffff';
}

// Parámetro
$idVariante = intval($_GET['id']);
if (!$idVariante) {
    die('ID de variante inválido');
}

// 1) Cabecera del producto
$sqlHeader = "
    SELECT
      pv.id,
      pv.referenciaCPN,
      pv.referenciaProveedor,
      po.nombre            AS Producto,
      pv.txtColor          AS Color,
      pv.inventario        AS Inventario,
      pv.precioNetoProveedor AS Precio,
      MIN(img.linkImagen)  AS linkImagen,
      prov.nombre          AS Proveedor
    FROM tb_productos_variantes pv
    JOIN tb_productos po ON pv.idProducto = po.id
    LEFT JOIN tb_imagenes_variantes img ON pv.id = img.idVariante
    JOIN tb_proveedores prov ON po.idProveedor = prov.id
    WHERE pv.id = $idVariante
    GROUP BY
      pv.id, pv.referenciaCPN, pv.referenciaProveedor,
      po.nombre, pv.txtColor, pv.inventario,
      pv.precioNetoProveedor, prov.nombre
";
$resHeader = $conn->query($sqlHeader);
$product   = $resHeader->fetch_assoc();

// 2) Movimientos (entradas + salidas)
$sqlMov = "
    (SELECT
       od.idOrden          AS id_odc,
       NULL                AS id_venta,
       oc.fechaSolicitud   AS Fecha,
       tp.nombre           AS ClienteProveedor,
       od.cantidad         AS Entrada,
       0                   AS Salida,
       'Entrada'           AS Mov,
       'Orden de Compra'   AS MedioCompra,
       lv.estado           AS Estado,
       lv.colorHexa        AS colorHexa,
       od.precioCompra     AS Precio,
       od.porcentajeImpuesto AS porcentaje
     FROM tb_ordenes_de_compra_detalle od
     JOIN tb_ordenes_de_compra oc ON od.idOrden = oc.id
     JOIN tb_proveedores_areas pa ON oc.idProveedorArea = pa.id
     JOIN tb_proveedores tp ON pa.idProveedor = tp.id
     LEFT JOIN tb_lista_estado_ventas lv ON oc.idEstadoOrden = lv.id
     WHERE od.idProductoVariante = $idVariante)
    UNION ALL
    (SELECT
       NULL                AS id_odc,
       v.id                AS id_venta,
       v.fechaOrden        AS Fecha,
       CONCAT(u.nombre,' ',u.apellido) AS ClienteProveedor,
       0                   AS Entrada,
       vd.cantidad         AS Salida,
       'Salida'            AS Mov,
       vm.nombre           AS MedioCompra,
       lv2.estado          AS Estado,
       lv2.colorHexa       AS colorHexa,
       vd.precioVentaAntesImpuestos AS Precio,
       vd.porcentajeImpuesto AS porcentaje
     FROM tb_ventas_detalle vd
     JOIN tb_ventas v ON vd.idVenta = v.id
     JOIN tb_usuarios u ON v.idUsuario = u.id
     JOIN tb_ventas_medios vm ON v.idMedioVenta = vm.id
     LEFT JOIN tb_lista_estado_ventas lv2 ON v.idEstado = lv2.id
     WHERE vd.idProductoVariante = $idVariante)
    ORDER BY Fecha, Mov ASC
";
$resMov = $conn->query($sqlMov);

// 3) Procesar filas y cálculos acumulados
$movs            = [];
$saldo           = 0;
$utilidadAcum    = 0;
$fila            = 1;
while ($r = $resMov->fetch_assoc()) {
    $e = (int)$r['Entrada'];
    $s = (int)$r['Salida'];
    // actualiza saldo
    $saldo += $e - $s;
    // subtotal según tipo
    $sub = ($e > 0 ? $e : $s) * $r['Precio'];
    $iva = $sub * $r['porcentaje'];
    $tot = $sub + $iva;
    // utilidad acumulada
    if ($r['Mov'] === 'Salida') {
        $utilidadAcum += $tot;
    } else {
        $utilidadAcum -= $tot;
    }
    // asignar al registro
    $r['fila']             = $fila++;
    $r['Saldo']            = $saldo;
    $r['Subtotal']         = $sub;
    $r['IVA']              = $iva;
    $r['Total']            = $tot;
    $r['UtilidadAcumulada'] = $utilidadAcum;
    $movs[] = $r;
}
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="utf-8">
    <title>Kardex: <?= htmlspecialchars($product['referenciaCPN']) ?></title>
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/compranet.css" rel="stylesheet">
</head>

<body>

    <div id="wrapper">

        <div class="container-fluid productos-kardex">
            <h1 class="h3 mb-4 text-gray-800">Kardex: <?= htmlspecialchars($product['referenciaCPN']) ?></h1>

            <!-- Cabecera del producto -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="row align-items-start">
                        <div class="col-auto">
                            <?php if ($product['linkImagen']): ?>
                                <img src="<?= str_replace(['J:/', 'j:/'], 'https://sistema.compranet.com.co/', $product['linkImagen']) ?>"
                                    style="height:100px" class="me-4">
                            <?php endif; ?>
                        </div>
                        <div class="col">
                            <div class="row">
                                <div class="col-md-8">
                                    <p><strong>Proveedor:</strong> <?= htmlspecialchars($product['Proveedor']) ?></p>
                                    <p><strong>Ref Prov:</strong> <?= htmlspecialchars($product['referenciaProveedor']) ?></p>
                                    <p><strong>Nombre:</strong> <?= htmlspecialchars($product['Producto']) ?></p>
                                    <p><strong>Color:</strong> <?= htmlspecialchars($product['Color']) ?></p>
                                    <p><strong>Stock Bodega Proveedor:</strong> <?= number_format($product['Inventario'], 0, ',', '.') ?></p>
                                </div>
                                <div class="col-md-4">
                                    <p><strong>Saldo:</strong> <?= number_format($saldo, 0, ',', '.') ?></p>
                                    <p><strong>Utilidad Acumulada:</strong> $ <?= number_format($utilidadAcum, 0, ',', '.') ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tabla de movimientos -->
            <table class="table table-sm table-bordered kardex-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Fecha</th>
                        <th>Cliente proveedor</th>
                        <th>Mov</th>
                        <th>Medio de Compra</th>
                        <th>Estado</th>
                        <th>Entrada</th>
                        <th>Salida</th>
                        <th>Saldo</th>
                        <th>Precio</th>
                        <th>Subtotal</th>
                        <th>IVA</th>
                        <th>Total</th>
                        <th>Utilidad Acum.</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($movs as $m): ?>
                        <tr class="<?= strtolower($m['Mov']) ?>">
                            <td class="text-center"><?= $m['fila'] ?></td>
                            <td class="text-center"><?= date('d-M-y', strtotime($m['Fecha'])) ?></td>
                            <td class="text-start"><?= htmlspecialchars($m['ClienteProveedor']) ?></td>
                            <td class="text-center"><?= htmlspecialchars($m['Mov']) ?></td>
                            <td class="text-center"><?= htmlspecialchars($m['MedioCompra']) ?></td>
                            <td class="text-center"
                                style="background-color: <?= $m['colorHexa'] ?>;
                                   color: <?= getTextColor($m['colorHexa']) ?>;">
                                <?= htmlspecialchars($m['Estado']) ?>
                            </td>
                            <td class="text-center"><?= $m['Entrada'] ? number_format($m['Entrada'], 0, ',', '.') : '-' ?></td>
                            <td class="text-center"><?= $m['Salida']  ? number_format($m['Salida'], 0, ',', '.')  : '-' ?></td>
                            <td class="text-center saldo-cell"><?= number_format($m['Saldo'], 0, ',', '.') ?></td>
                            <td class="text-end">$ <?= number_format($m['Precio'], 0, ',', '.') ?></td>
                            <td class="text-end">$ <?= number_format($m['Subtotal'], 0, ',', '.') ?></td>
                            <td class="text-end">$ <?= number_format($m['IVA'], 0, ',', '.') ?></td>
                            <td class="text-end">$ <?= number_format($m['Total'], 0, ',', '.') ?></td>
                            <td class="text-end">$ <?= number_format($m['UtilidadAcumulada'], 0, ',', '.') ?></td>
                            <td class="text-center">
                                <?php if ($m['Mov'] === 'Entrada'): ?>
                                    <a href="/ordenes/pedido.php?id=<?= $m['id_odc'] ?>" class="btn btn-sm btn-primary" target="_blank">Ver</a>
                                <?php else: ?>
                                    <a href="/ventas/venta.php?id=<?= $m['id_venta'] ?>" class="btn btn-sm btn-primary" target="_blank">Ver</a>
                                <?php endif; ?>
                            </td>

                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>

</html>