<?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 db_rows(mysqli $conn, string $sql): array
{
    $rows = [];
    $query = $conn->query($sql);
    if ($query) {
        while ($row = $query->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function ref_key(string $referencia, string $talla): string
{
    return $referencia . '||' . $talla;
}

function badge_estado(string $estado): string
{
    return match ($estado) {
        'Proceso'    => 'badge alert-info',
        'Confirmado' => 'badge bg-pink',
        'Recibido'   => 'badge alert-success',
        'Cancelado'  => 'badge alert-secondary',
        default      => 'badge bg-light text-dark',
    };
}

function badge_origen(string $tipo): string
{
    return match ($tipo) {
        'CRUCE_INVENTARIO' => 'badge bg-info text-dark',
        'PEDIDO_CLIENTE'   => 'badge bg-warning text-dark',
        'PEDIDO_EXTRA'     => 'badge bg-success',
        default            => 'badge bg-secondary',
    };
}

$id_pedido = (int)($_GET['id_pedido'] ?? 0);
if ($id_pedido <= 0) {
    die('ID inválido');
}

$pedido = $conn->query("SELECT * FROM pedido WHERE id='$id_pedido' LIMIT 1")->fetch_assoc();
if (!$pedido) {
    die('Pedido no encontrado');
}

$tercero = $conn->query("SELECT * FROM tercero WHERE nombre='" . $conn->real_escape_string($pedido['nombre_tercero']) . "' LIMIT 1")->fetch_assoc();
$tieneTablaOrigen = $conn->query("SHOW TABLES LIKE 'pedido_detalle_origen'")->num_rows > 0;

if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf'];

$detalleTallas = db_rows($conn, "
    SELECT talla, SUM(CAST(cantidad AS SIGNED)) AS suma
    FROM pedido_detalle
    WHERE id_pedido = '$id_pedido'
    GROUP BY talla
    ORDER BY CAST(talla AS UNSIGNED) ASC, talla ASC
");

$tallas = [];
foreach ($detalleTallas as $item) {
    $tallas[] = (string)$item['talla'];
}

$detallePlano = db_rows($conn, "
    SELECT referencia_producto, talla, SUM(CAST(cantidad AS SIGNED)) AS cantidad
    FROM pedido_detalle
    WHERE id_pedido = '$id_pedido'
    GROUP BY referencia_producto, talla
    ORDER BY referencia_producto ASC, CAST(talla AS UNSIGNED) ASC, talla ASC
");

$matrizDetalle = [];
$totalesRef = [];
$refs = [];
$totalCant = 0;
foreach ($detallePlano as $row) {
    $ref = (string)$row['referencia_producto'];
    $talla = (string)$row['talla'];
    $cant = (float)$row['cantidad'];

    if (!in_array($ref, $refs, true)) {
        $refs[] = $ref;
    }
    if (!isset($matrizDetalle[$ref])) {
        $matrizDetalle[$ref] = [];
        $totalesRef[$ref] = 0;
    }
    $matrizDetalle[$ref][$talla] = $cant;
    $totalesRef[$ref] += $cant;
    $totalCant += $cant;
}

$productos = [];
if (!empty($refs)) {
    $in = [];
    foreach ($refs as $ref) {
        $in[] = "'" . $conn->real_escape_string($ref) . "'";
    }
    $productosRows = db_rows($conn, "SELECT referencia, categoria, color, foto1 FROM producto WHERE referencia IN (" . implode(',', $in) . ")");
    foreach ($productosRows as $row) {
        $productos[$row['referencia']] = $row;
    }
}

$origenRows = [];
$origenResumen = [
    'CRUCE_INVENTARIO' => 0,
    'PEDIDO_CLIENTE'   => 0,
    'PEDIDO_EXTRA'     => 0,
];
$origenPorCelda = [];

if ($tieneTablaOrigen) {
    $origenRows = db_rows($conn, "
        SELECT referencia_producto, talla, nombre_tercero, tipo_origen, SUM(CAST(cantidad AS SIGNED)) AS cantidad, MAX(fecha) AS fecha
        FROM pedido_detalle_origen
        WHERE id_pedido = '$id_pedido'
        GROUP BY referencia_producto, talla, nombre_tercero, tipo_origen
        ORDER BY referencia_producto ASC, CAST(talla AS UNSIGNED) ASC, talla ASC, tipo_origen ASC, nombre_tercero ASC
    ");

    foreach ($origenRows as $row) {
        $tipo = $row['tipo_origen'];
        $cantidad = (float)$row['cantidad'];
        if (isset($origenResumen[$tipo])) {
            $origenResumen[$tipo] += $cantidad;
        }
        $key = ref_key((string)$row['referencia_producto'], (string)$row['talla']);
        $origenPorCelda[$key][] = $row;
    }
}

$filasPreparacion = [];
$productosPrep = [];
if ($pedido['estado'] === 'Proceso' && $tieneTablaOrigen) {
    $filasPreparacion = db_rows($conn, "
        SELECT
            d.referencia_producto,
            d.talla,
            d.nombre_tercero,
            SUM(CAST(d.cantidad AS SIGNED)) AS saldo_base,
            COALESCE(ad.cantidad, 0) AS disponible_base
        FROM alm_referencia_despacho d
        LEFT JOIN alm_referencia_disponible ad
               ON ad.referencia_producto = d.referencia_producto
              AND ad.talla = d.talla
        GROUP BY
            d.referencia_producto,
            d.talla,
            d.nombre_tercero,
            ad.cantidad
        HAVING SUM(CAST(d.cantidad AS SIGNED)) > 0
        ORDER BY d.nombre_tercero ASC, d.referencia_producto ASC, CAST(d.talla AS UNSIGNED) ASC, d.talla ASC
    ");

    $refsPrep = [];
    foreach ($filasPreparacion as $row) {
        $refsPrep[] = $row['referencia_producto'];
    }
    $refsPrep = array_values(array_unique($refsPrep));

    if (!empty($refsPrep)) {
        $in = [];
        foreach ($refsPrep as $ref) {
            $in[] = "'" . $conn->real_escape_string($ref) . "'";
        }
        $prodRows = db_rows($conn, "SELECT referencia, categoria, color FROM producto WHERE referencia IN (" . implode(',', $in) . ")");
        foreach ($prodRows as $row) {
            $productosPrep[$row['referencia']] = $row;
        }
    }

    foreach ($filasPreparacion as &$fila) {
        $fila['saldo_pendiente'] = max((float)$fila['saldo_base'], 0);
        $fila['inventario_libre'] = max((float)$fila['disponible_base'], 0);
    }
    unset($fila);
}
?>
<!doctype html>
<html lang="es" class="light-theme">

<head>
    <?php include '../general/libreria-css.php'; ?>
    <style>
        /* =========================
        TABLA PRINCIPAL DEL PEDIDO
        ========================== */
        .tabla-tallas thead th.sticky-top {
            top: 0;
            z-index: 5;
            background: #fff;
        }

        .tabla-tallas td:first-child,
        .tabla-tallas th:first-child {
            position: sticky;
            left: 0;
            z-index: 4;
            background: #fff;
        }

        .tabla-tallas td:nth-child(2),
        .tabla-tallas th:nth-child(2) {
            position: sticky;
            left: 58px;
            z-index: 4;
            background: #fff;
        }

        #hover_enlace:hover {
            color: #fd7e14;
            border: 1px solid #fd7e14;
            padding: 1px;
            box-shadow: 0 0 .5rem rgba(255, 193, 7, 0.5);
        }

        /* =========================
       CHIPS Y RESUMEN
    ========================= */
        .origen-chip {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .25rem .55rem;
            border-radius: 999px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            font-size: .78rem;
            font-weight: 600;
            margin-right: .35rem;
            margin-bottom: .35rem;
        }

        .sticky-summary {
            position: sticky;
            bottom: 0;
            z-index: 5;
            background: #fff;
            border-top: 1px solid #e9ecef;
        }

        .resumen-linea td,
        .resumen-linea th {
            font-size: .85rem;
            white-space: nowrap;
        }

      
        /* =========================
       INPUTS Y TABLA PREPARACIÓN
    ========================== */
        .input-mini {
            min-width: 90px;
        }

        .tabla-preparacion td,
        .tabla-preparacion th {
            white-space: nowrap;
            vertical-align: middle;
        }

        /* =========================
       MODAL PREPARAR PEDIDO
    ========================== */
        #modalPrepararPedido .modal-dialog {
            max-width: 98vw;
        }

        #modalPrepararPedido .modal-body {
            max-height: calc(100vh - 180px);
            overflow-y: auto;
            padding: 1rem;
        }

        #modalPrepararPedido .table-responsive {
            overflow: auto;
        }

        #modalPrepararPedido .sticky-top {
            top: 0;
            z-index: 10;
            background: #fff;
        }

        /* =========================
       PANEL IZQUIERDO CLIENTES
    ========================== */
        .panel-clientes-prep {
            border: 1px solid #e9ecef;
            border-radius: .75rem;
            background: #fff;
            position: sticky;
            top: 0;
        }

        .lista-clientes-prep {
            max-height: 58vh;
            overflow-y: auto;
        }

        .btn-cliente-prep {
            width: 100%;
            text-align: left;
            white-space: normal;
            border-radius: .7rem;
            padding: .7rem .85rem;
            transition: all .2s ease;
        }

        .btn-cliente-prep.activo {
            background: #212529;
            border-color: #212529;
            color: #fff;
        }

        .btn-cliente-prep.inactivo {
            background: #fff;
            border-color: #dee2e6;
            color: #212529;
            opacity: .75;
        }

        .btn-cliente-prep:hover {
            transform: translateY(-1px);
        }

        .prep-meta {
            font-size: .78rem;
            color: #6c757d;
            display: block;
            margin-top: .15rem;
        }

        /* =========================
       BOTÓN OMITIR FILA
    ========================== */
        .btn-omitir-fila {
            min-width: 88px;
        }

        .btn-omitir-fila.omitida {
            background: #6c757d;
            border-color: #6c757d;
            color: #fff;
        }

        /* =========================
       FILAS OCULTAS
    ========================== */
        .fila-preparacion.omitida-fila,
        .fila-preparacion.omitida-cliente {
            display: none;
        }

        /* =========================
       FILTRO ANTIGUO
       (solo si aún lo usas)
    ========================== */
        #filtroClientePreparacion {
            min-width: 260px;
        }
    </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">
                    <ol class="breadcrumb small">
                        <li class="breadcrumb-item"><a href="../inicio/inicio.php"><ion-icon name="home-outline"></ion-icon></a></li>
                        <li class="breadcrumb-item"><a href="empresa.php">Fábrica</a></li>
                        <li class="breadcrumb-item"><a href="pedido.php">Pedidos</a></li>
                        <li class="breadcrumb-item active">ODP-<?= $id_pedido ?> <?= h($pedido['nombre_tercero']) ?></li>
                    </ol>
                </nav>

                <?php if (isset($_GET['ok_preparado'])): ?>
                    <div class="alert alert-success border-0 shadow-sm">
                        Se guardó la preparación del pedido y quedó registrada la trazabilidad del armado.
                    </div>
                <?php endif; ?>

                <div class="card shadow-sm mb-4 border-0">
                    <div class="card-body bg-gradient-warning bg-opacity-75 rounded-3">
                        <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3">
                            <div>
                                <h1 class="h4 mb-1 text-dark fw-bold">ODP-<?= $id_pedido ?></h1>
                                <div class="small text-dark">
                                    <?= h($pedido['nombre_tercero']) ?> · <?= h($pedido['fecha']) ?>
                                </div>
                            </div>

                            <div class="d-flex flex-wrap gap-2 justify-content-lg-end">
                                <?php if ($pedido['estado'] === 'Proceso' && $tieneTablaOrigen): ?>
                                    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#modalPrepararPedido">
                                        <i class="fas fa-wand-magic-sparkles me-1"></i> Preparar desde saldos
                                    </button>
                                <?php endif; ?>

                                <?php if ($pedido['estado'] === 'Proceso'): ?>
                                    <a class="btn btn-warning" href="#!" data-bs-toggle="modal" data-bs-target="#editar_venta">
                                        <i class="far fa-edit me-1"></i> Actualizar datos
                                    </a>
                                <?php endif; ?>

                                <span class="btn <?= badge_estado($pedido['estado']) ?> text-uppercase py-2 px-3">
                                    <?= h($pedido['estado']) ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm" id="areaImprimir">
                    <div class="card-body">
                        <div class="row align-items-center mb-4 gx-4">
                            <div class="col-md-8">
                                <h2 class="h6 text-uppercase mb-0">Cliente: <span class="text-dark fw-bold"><?= h($pedido['nombre_tercero']) ?></span></h2>
                                <small class="text-muted">Tel: <?= h($tercero['telefono'] ?? 'No registra') ?></small>
                            </div>
                            <div class="col-md-4 text-md-end">
                                <span class="badge bg-light text-dark fs-6"><?= h($pedido['fecha']) ?></span>
                            </div>
                        </div>

                        <div class="table-responsive mb-4">
                            <table class="table table-bordered table-sm">
                                <thead class="bg-gradient-warning text-dark">
                                    <tr>
                                        <th style="width:5%" class="text-center">Logo</th>
                                        <th style="width:30%" class="text-center">Datos</th>
                                        <th style="width:40%" class="text-center">Observación</th>
                                        <th style="width:10%" class="text-center">N° Pedido</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="align-middle">
                                        <td class="text-center"><img src="../../img/logo.png" width="60" loading="lazy" alt="logo"></td>
                                        <td>
                                            <span class="fw-semibold">Cliente:</span> <mark><?= h($pedido['nombre_tercero']) ?></mark><br>
                                            <span class="fw-semibold">Tel:</span> <mark><?= h($tercero['telefono'] ?? 'No registra') ?></mark>
                                        </td>
                                        <td><mark><?= h($pedido['observacion']) ?></mark></td>
                                        <td class="text-center fs-4 fw-bold"><?= h($pedido['numero_pedido']) ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="table-responsive table-responsive-lg">
                            <table class="table table-hover table-bordered table-sm tabla-tallas">
                                <thead class="text-dark bg-warning bg-opacity-75 small sticky-top">
                                    <tr>
                                        <th>Foto</th>
                                        <th>Referencia</th>
                                        <th class="text-center">Categoría</th>
                                        <th class="text-center">Color</th>
                                        <?php foreach ($tallas as $talla): ?>
                                            <th class="text-center"><?= h($talla) ?></th>
                                        <?php endforeach; ?>
                                        <th class="text-center">Pares</th>
                                    </tr>
                                </thead>
                                <tbody class="align-middle">
                                    <?php if (empty($refs)): ?>
                                        <tr>
                                            <td colspan="<?= count($tallas) + 5 ?>" class="text-center text-muted py-4">Este pedido todavía no tiene referencias agregadas.</td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php foreach ($refs as $ref):
                                        $prod = $productos[$ref] ?? ['referencia' => $ref, 'categoria' => 'No registra', 'color' => 'No registra', 'foto1' => 'NO APLICA'];
                                    ?>
                                        <tr>
                                            <td class="text-center">
                                                <img src="<?= ($prod['foto1'] ?? 'NO APLICA') === 'NO APLICA' ? '../../img/camara.jpg' : '../../img-producto/' . $prod['foto1'] ?>" width="40" height="40" loading="lazy" alt="foto">
                                            </td>
                                            <td>
                                                <span class="fw-semibold"><?= h($prod['referencia']) ?></span>
                                                <?php if ($pedido['estado'] === 'Proceso'): ?>
                                                    <a class="btn btn-warning btn-sm float-end" data-bs-toggle="modal"
                                                        data-bs-target="#editar_referencia"
                                                        data-id_pedido="<?= $id_pedido ?>"
                                                        data-referencia_producto="<?= h($ref) ?>">
                                                        Editar
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center text-muted small"><?= h($prod['categoria'] ?? 'No registra') ?></td>
                                            <td class="text-center text-muted small"><?= h($prod['color'] ?? 'No registra') ?></td>

                                            <?php foreach ($tallas as $talla):
                                                $cantTalla = (float)($matrizDetalle[$ref][$talla] ?? 0);
                                            ?>
                                                <td class="text-center">
                                                    <?php if ($pedido['estado'] !== 'Proceso'): ?>
                                                        <?= nf0($cantTalla) ?>
                                                    <?php else: ?>
                                                        <form action="script/pedido-talla-eliminar.php" method="post" class="d-inline" onsubmit="return confirm('¿Eliminar esta talla del pedido?');">
                                                            <input type="hidden" name="id_pedido" value="<?= $id_pedido ?>">
                                                            <input type="hidden" name="referencia_producto" value="<?= h($ref) ?>">
                                                            <input type="hidden" name="talla" value="<?= h($talla) ?>">
                                                            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                                                            <button class="btn btn-link p-0 text-dark fw-semibold" type="submit">
                                                                <span id="hover_enlace"><?= nf0($cantTalla) ?></span>
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                </td>
                                            <?php endforeach; ?>

                                            <td class="text-center fw-bold"><?= nf0($totalesRef[$ref] ?? 0) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="bg-light">
                                        <th colspan="<?= count($tallas) + 4 ?>" class="text-end">TOTAL</th>
                                        <th class="text-center"><?= nf0($totalCant) ?></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <?php if ($pedido['estado'] === 'Proceso'): ?>
                            <form class="g-3 needs-validation d-print-none mt-4" method="POST" action="script/pedido-referencia-guardar.php">
                                <input type="hidden" name="id_pedido" value="<?= $id_pedido ?>">
                                <input type="hidden" name="estado" value="<?= h($pedido['estado']) ?>">
                                <div class="row">
                                    <div class="col-md-6">
                                        <select class="" id="single-select1" required name="referencia_producto" autofocus>
                                            <?php if (isset($_GET['referencia_producto'])): ?>
                                                <option selected value="<?= h($_GET['referencia_producto']) ?>"><?= h($_GET['referencia_producto']) ?></option>
                                                <option value="">Referencias</option>
                                            <?php else: ?>
                                                <option selected value="">Referencias</option>
                                            <?php endif; ?>
                                            <?php
                                            $query4 = $conn->query("SELECT * FROM producto WHERE Habilitado='Si' ORDER BY referencia ASC");
                                            if ($query4) {
                                                while ($row4 = $query4->fetch_assoc()) {
                                                    echo '<option value="' . h($row4['referencia']) . '">' . h($row4['referencia']) . ' - ' . h($row4['color']) . ' ' . h($row4['categoria']) . '</option>';
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <select class="single-select" required name="talla">
                                            <option selected disabled value="">Tallas</option>
                                            <?php for ($i = 10; $i < 50; $i++): ?>
                                                <option value="<?= $i ?>">Talla <?= $i ?></option>
                                            <?php endfor; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <input class="form-control" type="number" required name="cantidad" placeholder="cant." value="0">
                                    </div>
                                    <div class="col-md-2">
                                        <button class="btn btn-success px-2 radius-30 w-100" type="submit"><i class="fas fa-plus text-white"></i> Agregar item</button>
                                    </div>
                                </div>
                            </form>
                        <?php endif; ?>

                        <?php if ($tieneTablaOrigen): ?>
                            <hr class="my-4">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
                                <div>
                                    <h5 class="mb-1">Trazabilidad del armado</h5>
                                    <div class="text-muted small">Aquí queda amarrado qué parte del pedido corresponde a clientes específicos, cruces con inventario o cantidades extra.</div>
                                </div>
                                <div class="text-end">
                                    <span class="origen-chip"><span class="badge bg-info text-dark">Cruce</span> <?= nf0($origenResumen['CRUCE_INVENTARIO'] ?? 0) ?></span>
                                    <span class="origen-chip"><span class="badge bg-warning text-dark">Cliente</span> <?= nf0($origenResumen['PEDIDO_CLIENTE'] ?? 0) ?></span>
                                    <span class="origen-chip"><span class="badge bg-success">Extra</span> <?= nf0($origenResumen['PEDIDO_EXTRA'] ?? 0) ?></span>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-sm table-bordered align-middle mb-0">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>Referencia</th>
                                            <th class="text-center">Talla</th>
                                            <th>Tipo</th>
                                            <th>Cliente / Origen</th>
                                            <th class="text-center">Cantidad</th>
                                            <th class="text-center">Fecha</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($origenRows)): ?>
                                            <tr>
                                                <td colspan="6" class="text-center text-muted py-4">Aún no has usado el asistente de preparación en este pedido.</td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($origenRows as $origen): ?>
                                                <tr>
                                                    <td><?= h($origen['referencia_producto']) ?></td>
                                                    <td class="text-center"><?= h($origen['talla']) ?></td>
                                                    <td><span class="<?= badge_origen($origen['tipo_origen']) ?>"><?= h(str_replace('_', ' ', $origen['tipo_origen'])) ?></span></td>
                                                    <td><?= h($origen['nombre_tercero'] ?: 'Mercancía extra / inventario') ?></td>
                                                    <td class="text-center fw-bold"><?= nf0($origen['cantidad']) ?></td>
                                                    <td class="text-center"><?= h($origen['fecha']) ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>



                        <?php
                        $manualRows = [];
                        $totalManual = 0;

                        $sqlManual = "
    SELECT 
        pd.id,
        pd.referencia_producto,
        pd.talla,
        SUM(CAST(pd.cantidad AS SIGNED)) AS cantidad
    FROM pedido_detalle pd
    LEFT JOIN pedido_detalle_origen pdo 
        ON pdo.id_pedido_detalle = pd.id
    WHERE pd.id_pedido = '$id_pedido'
      AND pd.estado <> 'Cancelado'
      AND pdo.id IS NULL
    GROUP BY pd.id, pd.referencia_producto, pd.talla
    ORDER BY pd.referencia_producto ASC, CAST(pd.talla AS UNSIGNED) ASC
";
                        $queryManual = $conn->query($sqlManual);

                        if ($queryManual && $queryManual->num_rows > 0) {
                            while ($rowManual = $queryManual->fetch_assoc()) {
                                $manualRows[] = $rowManual;
                                $totalManual += (float)$rowManual['cantidad'];
                            }
                        }
                        ?>

                        <?php if (!empty($manualRows)): ?>
                            <div class="card border-0 shadow-sm mt-3">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                                        <div>
                                            <h5 class="mb-1 fw-bold">Pedido agregado manualmente</h5>
                                            <p class="text-muted mb-0">Items cargados desde el formulario normal, fuera del asistente de trazabilidad.</p>
                                        </div>
                                        <div class="text-end">
                                            <span class="badge bg-dark fs-6">Total manual: <?= number_format($totalManual, 0, ',', '.') ?></span>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table class="table table-sm table-striped align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Referencia</th>
                                                    <th class="text-center">Talla</th>
                                                    <th class="text-center">Cantidad</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($manualRows as $itemManual): ?>
                                                    <tr>
                                                        <td><?= h($itemManual['referencia_producto']) ?></td>
                                                        <td class="text-center"><?= h($itemManual['talla']) ?></td>
                                                        <td class="text-center fw-bold text-success">
                                                            <?= number_format((float)$itemManual['cantidad'], 0, ',', '.') ?>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <th colspan="2" class="text-end">Total manual</th>
                                                    <th class="text-center text-success"><?= number_format($totalManual, 0, ',', '.') ?></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>





                        <div class="text-center my-4 d-print-none">
                            <button class="btn btn-info btn-lg radius-30" onclick="printDiv('areaImprimir')">
                                <i class="fas fa-print"></i> Imprimir
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <?php include '../general/footer.php'; ?>
        </div>
    </div>

    <?php include '../general/libreria-js.php'; ?>
    <script>
        $(document).ready(function() {
            $('#single-select1').select2({
                theme: 'bootstrap4',
                width: '100%'
            });
            $('.single-select').select2({
                theme: 'bootstrap4',
                width: '100%'
            });
        });
    </script>

    <?php if ($pedido['estado'] === 'Proceso' && $tieneTablaOrigen): ?>
        <div class="modal fade" id="modalPrepararPedido" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-fullscreen-xl-down modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header bg-dark text-white">
                        <h5 class="modal-title">Preparar pedido desde saldos del almacén</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form method="POST" action="script/pedido-preparar-guardar.php" id="formPrepararPedido">
                        <input type="hidden" name="id_pedido" value="<?= $id_pedido ?>">
                        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
                        <div class="modal-body">

                            <?php
                            $clientesPreparacion = [];
                            foreach ($filasPreparacion as $filaPrep) {
                                $cli = (string)$filaPrep['nombre_tercero'];

                                if (!isset($clientesPreparacion[$cli])) {
                                    $clientesPreparacion[$cli] = [
                                        'nombre' => $cli,
                                        'registros' => 0,
                                        'saldo' => 0,
                                    ];
                                }

                                $clientesPreparacion[$cli]['registros']++;
                                $clientesPreparacion[$cli]['saldo'] += (float)$filaPrep['saldo_pendiente'];
                            }
                            ksort($clientesPreparacion);
                            ?>

                            <div class="row g-3">
                                <div class="col-lg-3">
                                    <div class="panel-clientes-prep p-3">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <div>
                                                <h6 class="mb-1">Clientes</h6>
                                                <small class="text-muted">Oculta o vuelve a mostrar clientes completos.</small>
                                            </div>
                                        </div>

                                        <div class="d-grid gap-2 mb-3">
                                            <button type="button" class="btn btn-outline-secondary btn-sm" id="btnMostrarTodosClientes">
                                                Mostrar todos
                                            </button>
                                        </div>

                                        <div class="lista-clientes-prep d-grid gap-2" id="listaClientesPreparacion">
                                            <?php foreach ($clientesPreparacion as $clientePrep): ?>
                                                <button
                                                    type="button"
                                                    class="btn btn-cliente-prep activo"
                                                    data-cliente="<?= h($clientePrep['nombre']) ?>">
                                                    <span class="fw-semibold d-block"><?= h($clientePrep['nombre']) ?></span>
                                                    <span class="prep-meta">
                                                        <?= nf0($clientePrep['registros']) ?> registros · saldo <?= nf0($clientePrep['saldo']) ?>
                                                    </span>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-9">
                                    <div class="table-responsive mb-4 tabla-preparacion-wrap">
                                        <table class="table table-bordered table-sm tabla-preparacion align-middle">
                                            <thead class="bg-light sticky-top">
                                                <tr>
                                                    <th class="text-center">Acción</th>
                                                    <th>Referencia</th>
                                                    <th class="text-center">Talla</th>
                                                    <th>Cliente</th>
                                                    <th class="text-center">Saldo</th>
                                                    <th class="text-center">Inventario</th>
                                                    <th class="text-center">Cruzar inventario</th>
                                                    <th class="text-center">Se pide por cliente</th>
                                                    <th class="text-center">Pedido extra</th>
                                                    <th class="text-center">Total a generar</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($filasPreparacion)): ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center text-muted py-4">No hay saldos disponibles para preparar en este momento.</td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($filasPreparacion as $i => $fila):
                                                        $ref = (string)$fila['referencia_producto'];
                                                        $talla = (string)$fila['talla'];
                                                        $cliente = (string)$fila['nombre_tercero'];
                                                        $saldoPendiente = (float)$fila['saldo_pendiente'];
                                                        $inventarioLibre = (float)$fila['inventario_libre'];
                                                        $grupo = md5(ref_key($ref, $talla));
                                                        $prodPrep = $productosPrep[$ref] ?? ['categoria' => 'No registra', 'color' => 'No registra'];
                                                    ?>
                                                        <tr class="fila-preparacion"
                                                            data-group="<?= $grupo ?>"
                                                            data-ref="<?= h($ref) ?>"
                                                            data-talla="<?= h($talla) ?>"
                                                            data-cliente="<?= h($cliente) ?>"
                                                            data-saldo="<?= (int)$saldoPendiente ?>"
                                                            data-available="<?= (int)$inventarioLibre ?>"
                                                            data-omit-manual="0">

                                                            <td class="text-center">
                                                                <button type="button" class="btn btn-outline-secondary btn-sm btn-omitir-fila">
                                                                    Omitir
                                                                </button>
                                                                <input type="hidden" name="rows[<?= $i ?>][omitido]" class="input-omitido" value="0">
                                                            </td>

                                                            <td>
                                                                <div class="fw-semibold"><?= h($ref) ?></div>
                                                                <div class="text-muted small"><?= h($prodPrep['color']) ?> · <?= h($prodPrep['categoria']) ?></div>
                                                                <input type="hidden" name="rows[<?= $i ?>][referencia_producto]" value="<?= h($ref) ?>">
                                                                <input type="hidden" name="rows[<?= $i ?>][talla]" value="<?= h($talla) ?>">
                                                                <input type="hidden" name="rows[<?= $i ?>][nombre_tercero]" value="<?= h($cliente) ?>">
                                                                <input type="hidden" name="rows[<?= $i ?>][saldo_cliente]" value="<?= (int)$saldoPendiente ?>">
                                                            </td>

                                                            <td class="text-center fw-bold"><?= h($talla) ?></td>
                                                            <td><?= h($cliente) ?></td>
                                                            <td class="text-center fw-bold text-warning-emphasis"><?= nf0($saldoPendiente) ?></td>

                                                            <td class="text-center">
                                                                <span class="badge bg-info text-dark cantidad-inventario"><?= nf0($inventarioLibre) ?></span>
                                                                <div class="small text-muted mt-1 disponible-restante">Restante: <?= nf0($inventarioLibre) ?></div>
                                                            </td>

                                                            <td class="text-center">
                                                                <input type="number" min="0" step="1" class="form-control form-control-sm input-mini input-cruce mx-auto" name="rows[<?= $i ?>][cruce_inventario]" value="0">
                                                            </td>

                                                            <td class="text-center fw-bold text-primary pedido-cliente"><?= nf0($saldoPendiente) ?></td>

                                                            <td class="text-center">
                                                                <input type="number" min="0" step="1" class="form-control form-control-sm input-mini input-extra mx-auto" name="rows[<?= $i ?>][pedido_extra]" value="0">
                                                            </td>

                                                            <td class="text-center fw-bold text-success total-generar"><?= nf0($saldoPendiente) ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>




                                    <div class="card border-0 shadow-sm resumen-bloque-prep">
                                        <div class="card-body p-0">
                                            <div class="p-3 border-bottom bg-light d-flex justify-content-between align-items-center flex-wrap gap-2">
                                                <div>
                                                    <h6 class="mb-0">Resumen del armado</h6>
                                                    <small class="text-muted">Solo toma en cuenta lo que esté visible y no omitido.</small>
                                                </div>
                                                <div class="d-flex flex-wrap gap-2 text-end">
                                                    <span class="origen-chip">Cruce inventario: <strong id="sumCruce">0</strong></span>
                                                    <span class="origen-chip">Pedido cliente: <strong id="sumCliente">0</strong></span>
                                                    <span class="origen-chip">Extra: <strong id="sumExtra">0</strong></span>
                                                    <span class="origen-chip">Total a generar: <strong id="sumGenerar">0</strong></span>
                                                </div>
                                            </div>
                                            <div class="table-responsive">
                                                <table class="table table-sm table-bordered resumen-linea mb-0">
                                                    <thead class="bg-white sticky-summary">
                                                        <tr>
                                                            <th>Referencia</th>
                                                            <th class="text-center">Talla</th>
                                                            <th class="text-center">Cruce</th>
                                                            <th class="text-center">Pedido cliente</th>
                                                            <th class="text-center">Extra</th>
                                                            <th class="text-center">Total generar</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="tbodyResumenPreparacion">
                                                        <tr>
                                                            <td colspan="6" class="text-center text-muted py-3">Sin cantidades cargadas aún.</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>


                                </div>
                            </div>


                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                            <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i> Guardar preparación</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>



        <script>
            (function() {
                function nf(v) {
                    return new Intl.NumberFormat('es-CO').format(Number(v || 0));
                }

                function normalizarCliente(v) {
                    return String(v || '').trim().toLowerCase();
                }

                function allRows() {
                    return Array.from(document.querySelectorAll('.fila-preparacion'));
                }

                function rowsByGroup(group) {
                    return allRows().filter(function(row) {
                        return row.dataset.group === group;
                    });
                }

                function rowIsVisible(row) {
                    return row.style.display !== 'none';
                }

                const clientesOmitidos = {};

                function actualizarEstadoBotonesCliente() {
                    document.querySelectorAll('.btn-cliente-prep').forEach(function(btn) {
                        const key = normalizarCliente(btn.dataset.cliente);
                        const omitido = !!clientesOmitidos[key];

                        btn.classList.toggle('activo', !omitido);
                        btn.classList.toggle('inactivo', omitido);
                    });
                }

                function aplicarVisibilidad() {
                    allRows().forEach(function(row) {
                        const clienteKey = normalizarCliente(row.dataset.cliente);
                        const omitidoCliente = !!clientesOmitidos[clienteKey];
                        const omitidoFila = row.dataset.omitManual === '1';
                        const ocultar = omitidoCliente || omitidoFila;

                        row.classList.toggle('omitida-cliente', omitidoCliente);
                        row.classList.toggle('omitida-fila', omitidoFila);
                        row.style.display = ocultar ? 'none' : '';

                        const inputOmitido = row.querySelector('.input-omitido');
                        if (inputOmitido) {
                            inputOmitido.value = ocultar ? '1' : '0';
                        }
                    });

                    actualizarEstadoBotonesCliente();
                }

                function clampRowCruce(row) {
                    const saldo = parseInt(row.dataset.saldo || '0', 10) || 0;
                    const available = parseInt(row.dataset.available || '0', 10) || 0;
                    const group = row.dataset.group;
                    const input = row.querySelector('.input-cruce');

                    let current = parseInt(input.value || '0', 10);
                    if (isNaN(current) || current < 0) current = 0;

                    let usedOther = 0;
                    rowsByGroup(group).forEach(function(other) {
                        if (other === row) return;
                        if (!rowIsVisible(other)) return;

                        const v = parseInt(other.querySelector('.input-cruce').value || '0', 10);
                        usedOther += isNaN(v) ? 0 : v;
                    });

                    const allowed = Math.max(0, Math.min(saldo, available - usedOther));

                    if (current > allowed) current = allowed;
                    input.value = current;

                    return current;
                }

                function recalc() {
                    aplicarVisibilidad();

                    const rows = allRows();
                    let sumCruce = 0;
                    let sumCliente = 0;
                    let sumExtra = 0;
                    let sumGenerar = 0;
                    const resumen = {};

                    rows.forEach(function(row) {
                        const saldo = parseInt(row.dataset.saldo || '0', 10) || 0;
                        const available = parseInt(row.dataset.available || '0', 10) || 0;
                        const visible = rowIsVisible(row);

                        const cruce = clampRowCruce(row);

                        const inputExtra = row.querySelector('.input-extra');
                        let extra = parseInt(inputExtra.value || '0', 10);
                        if (isNaN(extra) || extra < 0) extra = 0;
                        inputExtra.value = extra;

                        const pedidoCliente = Math.max(0, saldo - cruce);
                        const totalGenerar = pedidoCliente + extra;

                        row.querySelector('.pedido-cliente').textContent = nf(pedidoCliente);
                        row.querySelector('.total-generar').textContent = nf(totalGenerar);

                        const group = row.dataset.group;
                        const usedGroup = rowsByGroup(group).reduce(function(acc, r) {
                            if (!rowIsVisible(r)) return acc;
                            const v = parseInt(r.querySelector('.input-cruce').value || '0', 10);
                            return acc + (isNaN(v) ? 0 : v);
                        }, 0);

                        const restante = Math.max(0, available - usedGroup);
                        rowsByGroup(group).forEach(function(r) {
                            const box = r.querySelector('.disponible-restante');
                            if (box) {
                                box.textContent = 'Restante: ' + nf(restante);
                            }
                        });

                        if (!visible) return;

                        sumCruce += cruce;
                        sumCliente += pedidoCliente;
                        sumExtra += extra;
                        sumGenerar += totalGenerar;

                        const key = row.dataset.ref + '||' + row.dataset.talla;
                        if (!resumen[key]) {
                            resumen[key] = {
                                referencia: row.dataset.ref,
                                talla: row.dataset.talla,
                                cruce: 0,
                                cliente: 0,
                                extra: 0,
                                total: 0
                            };
                        }

                        resumen[key].cruce += cruce;
                        resumen[key].cliente += pedidoCliente;
                        resumen[key].extra += extra;
                        resumen[key].total += totalGenerar;
                    });

                    document.getElementById('sumCruce').textContent = nf(sumCruce);
                    document.getElementById('sumCliente').textContent = nf(sumCliente);
                    document.getElementById('sumExtra').textContent = nf(sumExtra);
                    document.getElementById('sumGenerar').textContent = nf(sumGenerar);

                    const tbody = document.getElementById('tbodyResumenPreparacion');
                    const keys = Object.keys(resumen).filter(function(key) {
                        return resumen[key].cruce > 0 || resumen[key].cliente > 0 || resumen[key].extra > 0;
                    });

                    if (keys.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted py-3">Sin cantidades cargadas aún.</td></tr>';
                        return;
                    }

                    let html = '';
                    keys.forEach(function(key) {
                        const item = resumen[key];
                        html += '<tr>' +
                            '<td>' + item.referencia + '</td>' +
                            '<td class="text-center">' + item.talla + '</td>' +
                            '<td class="text-center fw-bold text-info">' + nf(item.cruce) + '</td>' +
                            '<td class="text-center fw-bold text-primary">' + nf(item.cliente) + '</td>' +
                            '<td class="text-center fw-bold text-success">' + nf(item.extra) + '</td>' +
                            '<td class="text-center fw-bold">' + nf(item.total) + '</td>' +
                            '</tr>';
                    });

                    tbody.innerHTML = html;
                }

                document.addEventListener('click', function(e) {
                    const btnCliente = e.target.closest('.btn-cliente-prep');
                    if (btnCliente) {
                        const key = normalizarCliente(btnCliente.dataset.cliente);
                        clientesOmitidos[key] = !clientesOmitidos[key];
                        recalc();
                        return;
                    }

                    if (e.target.id === 'btnMostrarTodosClientes') {
                        Object.keys(clientesOmitidos).forEach(function(key) {
                            clientesOmitidos[key] = false;
                        });

                        allRows().forEach(function(row) {
                            row.dataset.omitManual = '0';
                            const btn = row.querySelector('.btn-omitir-fila');
                            if (btn) {
                                btn.classList.remove('omitida');
                                btn.textContent = 'Omitir';
                            }
                        });

                        recalc();
                        return;
                    }

                    const btnFila = e.target.closest('.btn-omitir-fila');
                    if (btnFila) {
                        const row = btnFila.closest('.fila-preparacion');
                        const omitida = row.dataset.omitManual === '1';

                        row.dataset.omitManual = omitida ? '0' : '1';
                        btnFila.classList.toggle('omitida', !omitida);
                        btnFila.textContent = omitida ? 'Omitir' : 'Mostrar';

                        recalc();
                    }
                });

                document.addEventListener('input', function(e) {
                    if (e.target.classList.contains('input-cruce') || e.target.classList.contains('input-extra')) {
                        recalc();
                    }
                });

                const modal = document.getElementById('modalPrepararPedido');
                if (modal) {
                    modal.addEventListener('shown.bs.modal', function() {
                        recalc();
                    });
                }

                recalc();
            })();
        </script>

    <?php endif; ?>

    <div class="modal fade" id="editar_venta" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xs">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Formulario | Editar pedido</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form class="text-start" method="POST" action="script/pedido-editar.php">
                    <input type="hidden" name="id_pedido" value="<?= $id_pedido ?>">
                    <input type="hidden" name="nombre_usuario" value="<?= h($rowusu['nombre'] ?? ($_SESSION['nombre'] ?? '')) ?>">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">Fecha</label>
                                <input class="form-control" type="date" name="fecha" value="<?= h($pedido['fecha']) ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">No pedido</label>
                                <input class="form-control" type="text" name="numero_pedido" value="<?= h($pedido['numero_pedido']) ?>" required>
                            </div>
                            <div class="col-md-12 mt-3">
                                <label class="form-label">Nombre tercero</label>
                                <select class="form-select" name="nombre_tercero" required>
                                    <option value="<?= h($pedido['nombre_tercero']) ?>"><?= h($pedido['nombre_tercero']) ?></option>
                                </select>
                            </div>
                            <div class="col-md-12 mt-3">
                                <label class="form-label">Observación</label>
                                <textarea class="form-control" name="observacion" required><?= h($pedido['observacion']) ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-warning px-5 radius-30">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="editar_referencia" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-warning text-dark">
                    <h5 class="modal-title">Editar referencia</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="script/referencia-editar.php">
                    <input type="hidden" name="edit_id_pedido" id="edit_id_pedido">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Referencia actual</label>
                                <input class="form-control" type="text" name="edit_referencia_producto" id="edit_referencia_producto" readonly>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">Referencia nueva</label>
                                <select class="form-control" name="edit_referencia_producto_new">
                                    <option selected value="">Referencias</option>
                                    <?php
                                    $query4 = $conn->query("SELECT * FROM producto WHERE Habilitado='Si' ORDER BY referencia ASC");
                                    if ($query4) {
                                        while ($row4 = $query4->fetch_assoc()) {
                                            echo '<option value="' . h($row4['referencia']) . '">' . h($row4['referencia']) . ' - ' . h($row4['color']) . ' ' . h($row4['categoria']) . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" name="eliminar" class="btn btn-danger radius-10">Eliminar</button>
                        <button type="submit" name="editar" class="btn btn-warning radius-10">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        $('#editar_referencia').on('show.bs.modal', function(event) {
            var button = $(event.relatedTarget);
            $('#edit_id_pedido').val(button.data('id_pedido'));
            $('#edit_referencia_producto').val(button.data('referencia_producto'));
        });
    </script>
</body>

</html>