<?php
session_start();
include '../../script/conexion.php';
require '../general/validacion.php';

date_default_timezone_set('America/Bogota');

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function nf0($value)
{
    return number_format((float)$value, 0, ',', '.');
}

function formatDateEs($date)
{
    if (!$date) return '';
    return date('d/m/Y', strtotime($date));
}

function tallaSort($a, $b)
{
    $aNum = is_numeric($a);
    $bNum = is_numeric($b);

    if ($aNum && $bNum) {
        return (float)$a <=> (float)$b;
    }

    if ($aNum) return -1;
    if ($bNum) return 1;

    return strcmp((string)$a, (string)$b);
}

$referencia = trim($_GET['referencia'] ?? '');
$terceroFabrica = 'INNOVASUELAS ALMACEN';

if ($referencia === '') {
    ?>
    <!doctype html>
    <html lang="es" class="light-theme">
    <head>
        <?php include '../general/libreria-css.php'; ?>
    </head>
    <body>
        <div class="wrapper">
            <?php echo include '../general/menu.php'; ?>
            <div class="page-content-wrapper">
                <div class="page-content">
                    <div class="alert alert-danger">No se recibió la referencia.</div>
                </div>
            </div>
        </div>
        <?php echo include '../general/libreria-js.php'; ?>
    </body>
    </html>
    <?php
    exit;
}

$referenciaSql = $conn->real_escape_string($referencia);

$sqlProducto = "SELECT * FROM producto WHERE referencia = '$referenciaSql' LIMIT 1";
$queryProducto = $conn->query($sqlProducto);
$rowpro = $queryProducto ? $queryProducto->fetch_assoc() : null;

if (!$rowpro) {
    ?>
    <!doctype html>
    <html lang="es" class="light-theme">
    <head>
        <?php include '../general/libreria-css.php'; ?>
    </head>
    <body>
        <div class="wrapper">
            <?php echo include '../general/menu.php'; ?>
            <div class="page-content-wrapper">
                <div class="page-content">
                    <div class="alert alert-warning">La referencia <?= h($referencia) ?> no existe en producto.</div>
                </div>
            </div>
        </div>
        <?php echo include '../general/libreria-js.php'; ?>
    </body>
    </html>
    <?php
    exit;
}

/*
|--------------------------------------------------------------------------
| Colores
|--------------------------------------------------------------------------
*/
$colorMap = [];
$coloresNecesarios = [];

if (!empty($rowpro['color']) && strtoupper($rowpro['color']) !== 'NO APLICA') {
    $coloresNecesarios[$rowpro['color']] = true;
}
if (!empty($rowpro['color2']) && strtoupper($rowpro['color2']) !== 'NO APLICA') {
    $coloresNecesarios[$rowpro['color2']] = true;
}

if (!empty($coloresNecesarios)) {
    $inColors = array_map(function ($c) use ($conn) {
        return "'" . $conn->real_escape_string($c) . "'";
    }, array_keys($coloresNecesarios));

    $sqlColors = "SELECT color, rgb FROM color WHERE color IN (" . implode(',', $inColors) . ")";
    $queryColors = $conn->query($sqlColors);
    if ($queryColors && $queryColors->num_rows > 0) {
        while ($row = $queryColors->fetch_assoc()) {
            $colorMap[$row['color']] = $row['rgb'];
        }
    }
}

/*
|--------------------------------------------------------------------------
| Agregados por talla
|--------------------------------------------------------------------------
*/
$compraDirecta = [];
$despachoRecibido = [];
$ventas = [];
$salidas = [];
$entradas = [];
$stockReal = [];

/* Compra directa */
$sqlCompra = "
    SELECT talla, SUM(cantidad) AS cantidad
    FROM alm_compra_detalle
    WHERE referencia_producto = '$referenciaSql'
    GROUP BY talla
";
$queryCompra = $conn->query($sqlCompra);
if ($queryCompra && $queryCompra->num_rows > 0) {
    while ($row = $queryCompra->fetch_assoc()) {
        $compraDirecta[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/* Despacho recibido desde fábrica/tercero */
$sqlDespachoRec = "
    SELECT dd.talla, SUM(dd.cantidad) AS cantidad
    FROM despacho d
    INNER JOIN despacho_detalle dd ON d.id = dd.id_despacho
    WHERE d.nombre_tercero = '$terceroFabrica'
      AND dd.referencia_producto = '$referenciaSql'
      AND dd.estado = 'Recibido'
    GROUP BY dd.talla
";
$queryDespachoRec = $conn->query($sqlDespachoRec);
if ($queryDespachoRec && $queryDespachoRec->num_rows > 0) {
    while ($row = $queryDespachoRec->fetch_assoc()) {
        $despachoRecibido[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/* Ventas */
$sqlVentas = "
    SELECT talla, SUM(cantidad) AS cantidad
    FROM alm_venta_detalle
    WHERE referencia_producto = '$referenciaSql'
      AND (estado = 'Proceso' OR estado = 'Finalizado')
    GROUP BY talla
";
$queryVentas = $conn->query($sqlVentas);
if ($queryVentas && $queryVentas->num_rows > 0) {
    while ($row = $queryVentas->fetch_assoc()) {
        $ventas[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/* Novedades salida */
$sqlSalidas = "
    SELECT talla, SUM(cantidad) AS cantidad
    FROM alm_novedad
    WHERE referencia_producto = '$referenciaSql'
      AND movimiento = 'Salida'
    GROUP BY talla
";
$querySalidas = $conn->query($sqlSalidas);
if ($querySalidas && $querySalidas->num_rows > 0) {
    while ($row = $querySalidas->fetch_assoc()) {
        $salidas[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/* Novedades entrada */
$sqlEntradas = "
    SELECT talla, SUM(cantidad) AS cantidad
    FROM alm_novedad
    WHERE referencia_producto = '$referenciaSql'
      AND movimiento = 'Entrada'
    GROUP BY talla
";
$queryEntradas = $conn->query($sqlEntradas);
if ($queryEntradas && $queryEntradas->num_rows > 0) {
    while ($row = $queryEntradas->fetch_assoc()) {
        $entradas[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/* Stock real */
$sqlStockReal = "
    SELECT talla, SUM(cantidad) AS cantidad
    FROM alm_referencia_disponible
    WHERE referencia_producto = '$referenciaSql'
    GROUP BY talla
";
$queryStockReal = $conn->query($sqlStockReal);
if ($queryStockReal && $queryStockReal->num_rows > 0) {
    while ($row = $queryStockReal->fetch_assoc()) {
        $stockReal[(string)$row['talla']] = (float)$row['cantidad'];
    }
}

/*
|--------------------------------------------------------------------------
| Unión de tallas
|--------------------------------------------------------------------------
*/
$tallas = array_unique(array_merge(
    array_keys($compraDirecta),
    array_keys($despachoRecibido),
    array_keys($ventas),
    array_keys($salidas),
    array_keys($entradas),
    array_keys($stockReal)
));

usort($tallas, 'tallaSort');

/*
|--------------------------------------------------------------------------
| Totales y filas
|--------------------------------------------------------------------------
*/
$rows = [];
$totals = [
    'compra_directa'    => 0,
    'despacho_recibido' => 0,
    'compras_total'     => 0,
    'ventas'            => 0,
    'salidas'           => 0,
    'entradas'          => 0,
    'calculado'         => 0,
    'real'              => 0,
    'diferencia'        => 0,
];

foreach ($tallas as $talla) {
    $compra = (float)($compraDirecta[$talla] ?? 0);
    $recibido = (float)($despachoRecibido[$talla] ?? 0);
    $ventasT = (float)($ventas[$talla] ?? 0);
    $salida = (float)($salidas[$talla] ?? 0);
    $entrada = (float)($entradas[$talla] ?? 0);
    $stock = (float)($stockReal[$talla] ?? 0);

    $comprasFusionadas = $compra + $recibido;
    $calculado = ($comprasFusionadas + $entrada) - ($ventasT + $salida);
    $diferencia = $stock - $calculado;

    $rows[] = [
        'talla'             => $talla,
        'compra_directa'    => $compra,
        'despacho_recibido' => $recibido,
        'compras_total'     => $comprasFusionadas,
        'ventas'            => $ventasT,
        'salidas'           => $salida,
        'entradas'          => $entrada,
        'calculado'         => $calculado,
        'real'              => $stock,
        'diferencia'        => $diferencia,
    ];

    $totals['compra_directa'] += $compra;
    $totals['despacho_recibido'] += $recibido;
    $totals['compras_total'] += $comprasFusionadas;
    $totals['ventas'] += $ventasT;
    $totals['salidas'] += $salida;
    $totals['entradas'] += $entrada;
    $totals['calculado'] += $calculado;
    $totals['real'] += $stock;
    $totals['diferencia'] += $diferencia;
}

$stockClassGeneral = 'text-secondary';
if ($totals['real'] > 0) {
    $stockClassGeneral = 'text-success';
} elseif ($totals['real'] < 0) {
    $stockClassGeneral = 'text-danger';
}

$diferenciaClassGeneral = 'text-secondary';
if ($totals['diferencia'] > 0) {
    $diferenciaClassGeneral = 'text-primary';
} elseif ($totals['diferencia'] < 0) {
    $diferenciaClassGeneral = 'text-danger';
}
?>
<!doctype html>
<html lang="es" class="light-theme">
<head>
    <?php include '../general/libreria-css.php'; ?>

    <style>
        :root {
            --page-bg: #f6f8fb;
            --card-bg: #ffffff;
            --text-main: #1f2937;
            --text-soft: #6b7280;
            --line: #e5e7eb;
            --primary: #111827;
            --primary-soft: rgba(17, 24, 39, .06);
            --success-soft: rgba(34, 197, 94, .12);
            --warning-soft: rgba(245, 158, 11, .12);
            --danger-soft: rgba(239, 68, 68, .12);
            --info-soft: rgba(59, 130, 246, .12);
            --shadow: 0 10px 30px rgba(15, 23, 42, .06);
            --radius: 18px;
        }

        body {
            background: var(--page-bg);
            color: var(--text-main);
        }

        .page-title-card,
        .nav-card,
        .info-card,
        .stats-card,
        .gallery-card,
        .table-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body,
        .nav-card .card-body,
        .info-card .card-body,
        .gallery-card .card-body,
        .table-card .card-body {
            padding: 1.25rem 1.35rem;
        }

        .page-title-main {
            font-size: 1.55rem;
            font-weight: 800;
            margin-bottom: .2rem;
            letter-spacing: .2px;
        }

        .page-subtitle {
            color: var(--text-soft);
            margin: 0;
            font-size: .95rem;
        }

        .page-badges,
        .report-badges {
            display: flex;
            gap: .5rem;
            flex-wrap: wrap;
            margin-top: .8rem;
        }

        .info-chip {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .45rem .75rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .82rem;
            color: var(--text-main);
            font-weight: 600;
        }

        .section-title {
            font-size: 1rem;
            font-weight: 800;
            margin-bottom: .15rem;
        }

        .section-subtitle {
            color: var(--text-soft);
            font-size: .88rem;
            margin-bottom: 1rem;
        }

        .btn-modern {
            border-radius: 12px;
            padding: .72rem 1rem;
            font-weight: 800;
        }

        .nav-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: .8rem;
        }

        .nav-link-card {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: .65rem;
            text-decoration: none;
            border-radius: 16px;
            padding: .95rem 1rem;
            font-weight: 800;
            border: 1px solid #e5e7eb;
            color: #111827;
            background: #fff;
            transition: all .18s ease;
        }

        .nav-link-card:hover {
            transform: translateY(-1px);
            background: #fafcff;
            border-color: #cfd8e3;
            color: #111827;
        }

        .nav-link-card.active {
            background: #111827;
            color: #fff;
            border-color: #111827;
        }

        .detail-table {
            margin-bottom: 0;
        }

        .detail-table th {
            width: 42%;
            color: #475569;
            font-weight: 700;
        }

        .detail-table td {
            font-weight: 700;
            color: #111827;
        }

        .color-dot {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: inline-block;
            border: 1px solid rgba(15, 23, 42, .12);
            margin-left: .45rem;
            vertical-align: middle;
        }

        .stats-card .card-body {
            padding: 1rem 1.1rem;
        }

        .stats-icon {
            width: 44px;
            height: 44px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-soft);
            color: var(--primary);
            font-size: 1.05rem;
            margin-bottom: .85rem;
        }

        .stats-title {
            font-size: .78rem;
            color: var(--text-soft);
            text-transform: uppercase;
            letter-spacing: .08em;
            margin-bottom: .35rem;
            font-weight: 700;
        }

        .stats-value {
            font-size: 1.35rem;
            font-weight: 800;
            line-height: 1.1;
        }

        .photo-box {
            border: 1px solid #e5e7eb;
            border-radius: 18px;
            overflow: hidden;
            background: #fff;
            height: 100%;
        }

        .photo-preview {
            height: 190px;
            width: 100%;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            border-bottom: 1px solid #eef2f7;
        }

        .photo-preview img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .photo-footer {
            padding: 1rem;
        }

        .photo-title {
            font-weight: 800;
            margin-bottom: .65rem;
        }

        .upload-box {
            border: 1px dashed #cbd5e1;
            border-radius: 18px;
            padding: 1rem;
            background: #fbfcfe;
            height: 100%;
        }

        .upload-box .form-control {
            border-radius: 12px;
        }

        .table-modern {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table-modern thead th {
            background: #f8fafc;
            color: #334155;
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            font-weight: 800;
            border-bottom: 1px solid var(--line);
            border-top: 0;
            white-space: nowrap;
            padding: .78rem .62rem;
        }

        .table-modern tbody td,
        .table-modern tfoot th,
        .table-modern tfoot td {
            padding: .8rem .62rem;
            vertical-align: middle;
            border-color: #eef2f7;
            white-space: nowrap;
        }

        .table-modern tbody tr:hover {
            background: #fafcff;
        }

        .qty-positive {
            color: #15803d;
            font-weight: 800;
            background: rgba(34, 197, 94, .08);
            text-align: center;
        }

        .qty-negative {
            color: #b91c1c;
            font-weight: 800;
            background: rgba(239, 68, 68, .08);
            text-align: center;
        }

        .qty-neutral {
            color: #64748b;
            font-weight: 700;
            text-align: center;
        }

        .link-talla {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: .35rem;
            text-decoration: none;
            padding: .35rem .75rem;
            border-radius: 999px;
            background: #111827;
            color: #fff;
            font-weight: 800;
        }

        .link-talla:hover {
            color: #fff;
            background: #000;
        }

        .empty-state {
            border: 1px dashed #cbd5e1;
            border-radius: 18px;
            padding: 2rem 1rem;
            text-align: center;
            background: #fff;
        }

        .empty-state i {
            font-size: 2rem;
            color: #94a3b8;
            margin-bottom: .75rem;
        }

        .empty-state h5 {
            font-weight: 800;
            margin-bottom: .35rem;
        }

        .empty-state p {
            color: var(--text-soft);
            margin-bottom: 0;
        }

        @media (max-width: 991.98px) {
            .nav-grid {
                grid-template-columns: 1fr;
            }
        }

        @media print {
            .d-print-none,
            .wrapper aside,
            .top-header,
            .modal {
                display: none !important;
            }

            body {
                background: #fff !important;
            }

            .page-title-card,
            .nav-card,
            .info-card,
            .stats-card,
            .gallery-card,
            .table-card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php echo include '../general/menu.php'; ?>

        <div class="page-content-wrapper">
            <div class="page-content">

                <nav aria-label="breadcrumb" class="mb-3 d-print-none">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item">
                            <a href="../inicio/inicio.php">
                                <ion-icon name="home-outline"></ion-icon>
                            </a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="producto.php">Productos</a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page"><?= h($referencia) ?></li>
                        <li class="breadcrumb-item active" aria-current="page">Kardex</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Kardex de referencia</div>
                        <p class="page-subtitle">
                            Resumen detallado de movimientos, stock calculado y stock real para la referencia seleccionada.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-tag"></i>
                                <?= h($referencia) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-barcode"></i>
                                Código: <?= h($rowpro['codigo']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-layer-group"></i>
                                Tallas: <?= nf0(count($rows)) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-warehouse"></i>
                                Stock real: <?= nf0($totals['real']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="card nav-card mb-3 d-print-none">
                    <div class="card-body">
                        <div class="nav-grid">
                            <a class="nav-link-card active" href="kardex.php?referencia=<?= urlencode($referencia) ?>">
                                <i class="far fa-chart-bar"></i> Kardex
                            </a>
                            <a class="nav-link-card" href="movimiento.php?referencia=<?= urlencode($referencia) ?>">
                                <i class="fas fa-file-signature"></i> Movimientos
                            </a>
                            <a class="nav-link-card" href="devolucion.php?referencia=<?= urlencode($referencia) ?>">
                                <i class="fa-solid fa-rotate-left"></i> Devoluciones
                            </a>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-lg-4">
                        <div class="card info-card h-100">
                            <div class="card-body">
                                <div class="section-title">Información de la referencia</div>
                                <div class="section-subtitle">Datos principales del producto y edición rápida de costos.</div>

                                <table class="table table-sm detail-table">
                                    <tbody>
                                        <tr>
                                            <th>Habilitado</th>
                                            <td>
                                                <?php if ($rowpro['habilitado'] === 'Si'): ?>
                                                    <span class="badge bg-success">Si</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger"><?= h($rowpro['habilitado']) ?></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Segmento</th>
                                            <td><?= h($rowpro['referencia_segmento']) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Código</th>
                                            <td><?= h($rowpro['codigo']) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Color 1</th>
                                            <td>
                                                <?= h($rowpro['color']) ?>
                                                <?php if (!empty($colorMap[$rowpro['color']])): ?>
                                                    <span class="color-dot" style="background: <?= h($colorMap[$rowpro['color']]) ?>;"></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Color 2</th>
                                            <td>
                                                <?= h($rowpro['color2']) ?>
                                                <?php if (!empty($colorMap[$rowpro['color2']])): ?>
                                                    <span class="color-dot" style="background: <?= h($colorMap[$rowpro['color2']]) ?>;"></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Categoría</th>
                                            <td><?= h($rowpro['categoria']) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Clase</th>
                                            <td><?= h($rowpro['clase']) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Peso</th>
                                            <td><?= h($rowpro['peso']) ?> g</td>
                                        </tr>
                                        <tr>
                                            <th>Costo unidad</th>
                                            <td>$ <?= nf0($rowpro['alm_costo_unidad']) ?></td>
                                        </tr>
                                        <tr>
                                            <th>Precio unidad</th>
                                            <td>$ <?= nf0($rowpro['alm_precio_unidad']) ?></td>
                                        </tr>
                                    </tbody>
                                </table>

                                <button class="btn btn-dark btn-modern w-100 mt-2" data-bs-toggle="modal" data-bs-target="#editarproducto">
                                    <i class="far fa-edit me-1"></i> Editar referencia
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-8">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-cart-plus"></i></div>
                                        <div class="stats-title">Compras + recibidos</div>
                                        <div class="stats-value"><?= nf0($totals['compras_total']) ?></div>
                                        <div class="stats-note">
                                            Directa: <?= nf0($totals['compra_directa']) ?> · Recibido: <?= nf0($totals['despacho_recibido']) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-cash-register"></i></div>
                                        <div class="stats-title">Ventas</div>
                                        <div class="stats-value"><?= nf0($totals['ventas']) ?></div>
                                        <div class="stats-note">Proceso + Finalizado</div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-right-left"></i></div>
                                        <div class="stats-title">Entradas / Salidas</div>
                                        <div class="stats-value"><?= nf0($totals['entradas']) ?> / <?= nf0($totals['salidas']) ?></div>
                                        <div class="stats-note">Movimientos de novedad</div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-calculator"></i></div>
                                        <div class="stats-title">Disponible calculado</div>
                                        <div class="stats-value <?= $totals['calculado'] > 0 ? 'text-success' : ($totals['calculado'] < 0 ? 'text-danger' : 'text-secondary') ?>">
                                            <?= nf0($totals['calculado']) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-warehouse"></i></div>
                                        <div class="stats-title">Stock real</div>
                                        <div class="stats-value <?= $stockClassGeneral ?>">
                                            <?= nf0($totals['real']) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="card stats-card h-100">
                                    <div class="card-body">
                                        <div class="stats-icon"><i class="fas fa-scale-balanced"></i></div>
                                        <div class="stats-title">Diferencia</div>
                                        <div class="stats-value <?= $diferenciaClassGeneral ?>">
                                            <?= nf0($totals['diferencia']) ?>
                                        </div>
                                        <div class="stats-note">Real - Calculado</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card gallery-card mb-3">
                    <div class="card-body">
                        <div class="section-title">Galería del producto</div>
                        <div class="section-subtitle">Carga, visualización y eliminación de las fotos de la referencia.</div>

                        <div class="row g-3">
                            <?php for ($i = 1; $i <= 4; $i++): ?>
                                <?php
                                $campoFoto = 'foto' . $i;
                                $foto = $rowpro[$campoFoto] ?? 'NO APLICA';
                                $modalId = 'fotoModal' . $i;
                                ?>
                                <div class="col-12 col-sm-6 col-xl-3">
                                    <?php if ($foto === 'NO APLICA' || $foto === ''): ?>
                                        <div class="upload-box">
                                            <div class="photo-title">Foto <?= $i ?></div>
                                            <form method="POST" action="script/foto<?= $i ?>.php" enctype="multipart/form-data">
                                                <input type="hidden" name="referencia_producto" value="<?= h($referencia) ?>">
                                                <input type="file" name="file" class="form-control mb-3" required>
                                                <button type="submit" name="editar" class="btn btn-dark btn-modern w-100">
                                                    Guardar foto <?= $i ?>
                                                </button>
                                            </form>
                                        </div>
                                    <?php else: ?>
                                        <div class="photo-box">
                                            <a href="#!" data-bs-toggle="modal" data-bs-target="#<?= h($modalId) ?>" class="photo-preview">
                                                <img src="../../../../innovasuelas/img-producto/<?= h($foto) ?>" alt="Foto <?= $i ?>" loading="lazy">
                                            </a>
                                            <div class="photo-footer">
                                                <div class="photo-title">Foto <?= $i ?></div>
                                                <a
                                                    class="btn btn-outline-danger btn-modern w-100"
                                                    href="script/foto<?= $i ?>-eliminar.php?referencia=<?= urlencode($referencia) ?>&archivo=<?= urlencode($foto) ?>"
                                                    onclick="return confirm('Seguro deseas eliminar esta foto?');"
                                                >
                                                    <i class="fas fa-trash-alt me-1"></i> Eliminar
                                                </a>
                                            </div>
                                        </div>

                                        <div class="modal fade" id="<?= h($modalId) ?>" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Foto <?= $i ?> - <?= h($referencia) ?></h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <img class="img-fluid w-100" src="../../../../innovasuelas/img-producto/<?= h($foto) ?>" alt="Foto <?= $i ?>">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>

                <div class="card table-card mb-3">
                    <div class="card-body">
                        <div class="section-title">Kardex por talla</div>
                        <div class="section-subtitle">
                            Comparación entre disponible calculado y stock real. La columna diferencia te ayuda a detectar ajustes o descuadres.
                        </div>

                        <?php if (empty($rows)): ?>
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <h5>Sin movimientos</h5>
                                <p>No se encontraron tallas con información para esta referencia.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-modern align-middle table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th class="text-center">Talla</th>
                                            <th class="text-center">Compra directa</th>
                                            <th class="text-center">Despacho recibido</th>
                                            <th class="text-center">Compras total</th>
                                            <th class="text-center">Ventas</th>
                                            <th class="text-center">Salidas</th>
                                            <th class="text-center">Entradas</th>
                                            <th class="text-center">Disponible calculado</th>
                                            <th class="text-center">Stock real</th>
                                            <th class="text-center">Diferencia</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($rows as $item): ?>
                                            <?php
                                            $calcClass = 'qty-neutral';
                                            if ($item['calculado'] > 0) {
                                                $calcClass = 'qty-positive';
                                            } elseif ($item['calculado'] < 0) {
                                                $calcClass = 'qty-negative';
                                            }

                                            $realClass = 'qty-neutral';
                                            if ($item['real'] > 0) {
                                                $realClass = 'qty-positive';
                                            } elseif ($item['real'] < 0) {
                                                $realClass = 'qty-negative';
                                            }

                                            $diffClass = 'qty-neutral';
                                            if ($item['diferencia'] > 0) {
                                                $diffClass = 'qty-positive';
                                            } elseif ($item['diferencia'] < 0) {
                                                $diffClass = 'qty-negative';
                                            }
                                            ?>
                                            <tr>
                                                <td class="text-center">
                                                    <a
                                                        href="historial.php?referencia=<?= urlencode($referencia) ?>&talla=<?= urlencode($item['talla']) ?>&filtro="
                                                        class="link-talla"
                                                        target="_blank"
                                                    >
                                                        T - <?= h($item['talla']) ?>
                                                    </a>
                                                </td>
                                                <td class="text-center"><?= nf0($item['compra_directa']) ?></td>
                                                <td class="text-center"><?= nf0($item['despacho_recibido']) ?></td>
                                                <td class="text-center"><?= nf0($item['compras_total']) ?></td>
                                                <td class="text-center"><?= nf0($item['ventas']) ?></td>
                                                <td class="text-center"><?= nf0($item['salidas']) ?></td>
                                                <td class="text-center"><?= nf0($item['entradas']) ?></td>
                                                <td class="<?= $calcClass ?>"><?= nf0($item['calculado']) ?></td>
                                                <td class="<?= $realClass ?>"><?= nf0($item['real']) ?></td>
                                                <td class="<?= $diffClass ?>"><?= nf0($item['diferencia']) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th class="text-center">Total</th>
                                            <th class="text-center"><?= nf0($totals['compra_directa']) ?></th>
                                            <th class="text-center"><?= nf0($totals['despacho_recibido']) ?></th>
                                            <th class="text-center"><?= nf0($totals['compras_total']) ?></th>
                                            <th class="text-center"><?= nf0($totals['ventas']) ?></th>
                                            <th class="text-center"><?= nf0($totals['salidas']) ?></th>
                                            <th class="text-center"><?= nf0($totals['entradas']) ?></th>
                                            <th class="<?= $totals['calculado'] > 0 ? 'qty-positive' : ($totals['calculado'] < 0 ? 'qty-negative' : 'qty-neutral') ?>">
                                                <?= nf0($totals['calculado']) ?>
                                            </th>
                                            <th class="<?= $totals['real'] > 0 ? 'qty-positive' : ($totals['real'] < 0 ? 'qty-negative' : 'qty-neutral') ?>">
                                                <?= nf0($totals['real']) ?>
                                            </th>
                                            <th class="<?= $totals['diferencia'] > 0 ? 'qty-positive' : ($totals['diferencia'] < 0 ? 'qty-negative' : 'qty-neutral') ?>">
                                                <?= nf0($totals['diferencia']) ?>
                                            </th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <?php echo include '../general/footer.php'; ?>
        </div>
    </div>

    <div class="modal fade" id="editarproducto" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Editar producto</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/producto-editar.php">
                    <input type="hidden" name="nombre_usuario" value="<?= h($rowusu['nombre']) ?>">
                    <input type="hidden" name="id" value="<?= h($rowpro['id']) ?>">
                    <input type="hidden" name="referencia" value="<?= h($referencia) ?>">

                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Costo unidad</label>
                            <input class="form-control" type="text" required name="alm_costo_unidad" value="<?= h($rowpro['alm_costo_unidad']) ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Precio unidad</label>
                            <input class="form-control" type="text" required name="alm_precio_unidad" value="<?= h($rowpro['alm_precio_unidad']) ?>">
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-dark btn-modern w-100" name="editar">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php echo include '../general/libreria-js.php'; ?>
</body>
</html>