<?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, ',', '.');
}

$nombre_tercero = trim($_GET['nombre_tercero'] ?? '');
$filtroActivo   = isset($_GET['filtro']);
$nombreUsuarioSesion = $_SESSION['nombre'] ?? ($_SESSION['usuario'] ?? '');

$stats = [
    'referencias'   => 0,
    'tallas'        => 0,
    'pendiente'     => 0,
    'despachado_mas'=> 0,
    'neto'          => 0,
];

$tallas = [];
$referencias = [];
$sinResultados = false;

if ($filtroActivo && $nombre_tercero !== '') {
    $nombre_tercero_sql = $conn->real_escape_string($nombre_tercero);

    $sqlTallas = "
        SELECT talla
        FROM alm_referencia_despacho
        WHERE nombre_tercero = '$nombre_tercero_sql'
        GROUP BY talla
        ORDER BY CAST(talla AS UNSIGNED) ASC, talla ASC
    ";
    $queryTallas = $conn->query($sqlTallas);
    if ($queryTallas && $queryTallas->num_rows > 0) {
        while ($rowTalla = $queryTallas->fetch_assoc()) {
            $tallas[] = (string)$rowTalla['talla'];
        }
    }

    $sqlDetalle = "
        SELECT 
            referencia_producto,
            talla,
            SUM(cantidad) AS cantidad
        FROM alm_referencia_despacho
        WHERE nombre_tercero = '$nombre_tercero_sql'
        GROUP BY referencia_producto, talla
        ORDER BY referencia_producto ASC
    ";
    $queryDetalle = $conn->query($sqlDetalle);

    $temp = [];

    if ($queryDetalle && $queryDetalle->num_rows > 0) {
        while ($row = $queryDetalle->fetch_assoc()) {
            $ref = (string)$row['referencia_producto'];
            $talla = (string)$row['talla'];
            $cantidad = (float)$row['cantidad'];

            if (!isset($temp[$ref])) {
                $temp[$ref] = [
                    'referencia' => $ref,
                    'cantidades' => array_fill_keys($tallas, 0),
                    'total'      => 0
                ];
            }

            if (!isset($temp[$ref]['cantidades'][$talla])) {
                $temp[$ref]['cantidades'][$talla] = 0;
            }

            $temp[$ref]['cantidades'][$talla] += $cantidad;
            $temp[$ref]['total'] += $cantidad;

            if ($cantidad > 0) {
                $stats['pendiente'] += $cantidad;
            } elseif ($cantidad < 0) {
                $stats['despachado_mas'] += abs($cantidad);
            }
        }
    }

    if (!empty($temp)) {
        $refsSql = array_map(function ($r) use ($conn) {
            return "'" . $conn->real_escape_string($r) . "'";
        }, array_keys($temp));

        $sqlProductos = "
            SELECT referencia, color, categoria
            FROM producto
            WHERE referencia IN (" . implode(',', $refsSql) . ")
        ";
        $queryProductos = $conn->query($sqlProductos);

        $productos = [];
        if ($queryProductos && $queryProductos->num_rows > 0) {
            while ($rowProd = $queryProductos->fetch_assoc()) {
                $productos[$rowProd['referencia']] = $rowProd;
            }
        }

        foreach ($temp as $ref => $data) {
            $prod = $productos[$ref] ?? [
                'referencia' => $ref,
                'color'      => 'No registra',
                'categoria'  => 'No registra'
            ];

            $referencias[] = [
                'producto'   => $prod,
                'cantidades' => $data['cantidades'],
                'total'      => $data['total']
            ];
        }
    }

    $stats['referencias'] = count($referencias);
    $stats['tallas'] = count($tallas);
    $stats['neto'] = $stats['pendiente'] - $stats['despachado_mas'];
    $sinResultados = $stats['referencias'] === 0;
}
?>
<!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: #4f46e5;
            --primary-soft: rgba(79, 70, 229, .10);
            --success-soft: rgba(34, 197, 94, .12);
            --danger-soft: rgba(239, 68, 68, .12);
            --warning-soft: rgba(245, 158, 11, .12);
            --info-soft: rgba(6, 182, 212, .12);
            --shadow: 0 10px 30px rgba(15, 23, 42, .06);
            --radius: 18px;
        }

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

        .page-title-card,
        .filter-card,
        .stats-card,
        .report-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body {
            padding: 1.4rem 1.5rem;
        }

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

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

        .filter-card .card-body,
        .report-card .card-body {
            padding: 1.25rem;
        }

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

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

        .stats-icon {
            width: 42px;
            height: 42px;
            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: .8rem;
            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;
            color: var(--text-main);
        }

        .stats-note {
            font-size: .8rem;
            color: var(--text-soft);
            margin-top: .35rem;
        }

        .report-head {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
            align-items: flex-start;
            flex-wrap: wrap;
            margin-bottom: 1.2rem;
            padding: 1rem 1.1rem;
            border: 1px solid var(--line);
            border-radius: 16px;
            background: linear-gradient(135deg, #ffffff 0%, #fafbff 100%);
        }

        .report-brand {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .report-brand img {
            width: 68px;
            height: 68px;
            object-fit: contain;
            border-radius: 14px;
            background: #fff;
            border: 1px solid var(--line);
            padding: .4rem;
        }

        .report-meta h4 {
            margin: 0 0 .3rem 0;
            font-size: 1.1rem;
            font-weight: 800;
        }

        .report-meta p {
            margin: 0;
            color: var(--text-soft);
            font-size: .92rem;
        }

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

        .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;
        }

        .toolbar-actions .btn {
            border-radius: 12px;
            padding: .65rem 1rem;
            font-weight: 700;
        }

        .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: .8rem .65rem;
        }

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

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

        .chip-soft {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .38rem .65rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .76rem;
            color: var(--text-main);
            font-weight: 700;
        }

        .ref-main {
            font-weight: 800;
            color: #111827;
        }

        .cell-pos {
            background: rgba(6, 182, 212, .12);
            color: #0f766e;
            font-weight: 800;
            text-align: center;
        }

        .cell-neg {
            background: rgba(239, 68, 68, .12);
            color: #b91c1c;
            font-weight: 800;
            text-align: center;
        }

        .cell-zero {
            color: #94a3b8;
            text-align: center;
            font-weight: 700;
        }

        .link-cell {
            color: inherit;
            text-decoration: underline;
            font-weight: 800;
        }

        .link-cell:hover {
            color: inherit;
            opacity: .85;
        }

        .total-pos {
            color: #0891b2;
            font-weight: 800;
        }

        .total-neg {
            color: #dc2626;
            font-weight: 800;
        }

        .total-zero {
            color: #475569;
            font-weight: 800;
        }

        .legend-wrap {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            justify-content: flex-end;
            margin-top: 1rem;
        }

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

        .legend-box {
            width: 14px;
            height: 14px;
            border-radius: 4px;
            display: inline-block;
        }

        .legend-box.pos {
            background: rgba(6, 182, 212, .75);
        }

        .legend-box.neg {
            background: rgba(239, 68, 68, .75);
        }

        .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 print {
            body {
                background: #fff !important;
            }

            .d-print-none,
            .wrapper aside,
            .top-header,
            .page-breadcrumb,
            .toolbar-actions,
            .modal {
                display: none !important;
            }

            .page-title-card,
            .filter-card,
            .stats-card,
            .report-card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }

            .page-content-wrapper,
            .page-content,
            .wrapper {
                margin: 0 !important;
                padding: 0 !important;
            }

            .report-head {
                border: 1px solid #ddd !important;
                background: #fff !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="d-print-none mb-3">
                    <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 active" aria-current="page">RPT - Mercancía por despachar</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Mercancía por despachar a cliente</div>
                        <p class="page-subtitle">
                            Consulta consolidada por referencia y talla de la mercancía pendiente por despachar o despachada de más.
                        </p>
                    </div>
                </div>

                <div class="card filter-card d-print-none mb-3">
                    <div class="card-body">
                        <form method="GET" action="rpt-mercancia-despachar-cliente.php">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-10">
                                    <label class="label-soft">Cliente</label>
                                    <select class="single-select form-control" name="nombre_tercero" required>
                                        <option value="" disabled <?= !$filtroActivo ? 'selected' : '' ?>>Seleccione</option>
                                        <?php
                                        $sqlClientes = "SELECT * FROM alm_tercero ORDER BY nombre ASC";
                                        $queryClientes = $conn->query($sqlClientes);
                                        if ($queryClientes && $queryClientes->num_rows > 0) {
                                            while ($rowCliente = $queryClientes->fetch_assoc()) {
                                                $selected = ($nombre_tercero === $rowCliente['nombre']) ? 'selected' : '';
                                        ?>
                                                <option value="<?= h($rowCliente['nombre']) ?>" <?= $selected ?>>
                                                    <?= h($rowCliente['nombre']) ?>
                                                </option>
                                        <?php
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <button class="btn btn-dark w-100" type="submit" name="filtro">
                                        <i class="fas fa-search me-1"></i> Consultar
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if ($filtroActivo): ?>
                    <div class="row g-3 mb-3 d-print-none">
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="stats-icon"><i class="fas fa-layer-group"></i></div>
                                    <div class="stats-title">Referencias</div>
                                    <div class="stats-value"><?= nf0($stats['referencias']) ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="stats-icon"><i class="fas fa-ruler-combined"></i></div>
                                    <div class="stats-title">Tallas</div>
                                    <div class="stats-value"><?= nf0($stats['tallas']) ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="stats-icon"><i class="fas fa-truck-loading"></i></div>
                                    <div class="stats-title">Pendiente</div>
                                    <div class="stats-value"><?= nf0($stats['pendiente']) ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="stats-icon"><i class="fas fa-exclamation-triangle"></i></div>
                                    <div class="stats-title">Despachado de más</div>
                                    <div class="stats-value"><?= nf0($stats['despachado_mas']) ?></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card report-card mb-3">
                        <div class="card-body">
                            <div class="report-head">
                                <div class="report-brand">
                                    <img src="../../img/logo.png" alt="Logo">
                                    <div class="report-meta">
                                        <h4>Mercancía por despachar</h4>
                                        <p><?= h($nombre_tercero) ?></p>
                                        <div class="report-badges">
                                            <span class="info-chip">
                                                <i class="fas fa-file-alt"></i>
                                                <?= nf0($stats['referencias']) ?> referencias
                                            </span>
                                            <span class="info-chip">
                                                <i class="fas fa-balance-scale"></i>
                                                Neto: <?= nf0($stats['neto']) ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="toolbar-actions d-print-none">
                                    <a href="javascript:window.print()" class="btn btn-outline-dark">
                                        <i class="fas fa-print me-1"></i> Imprimir
                                    </a>
                                </div>
                            </div>

                            <?php if ($sinResultados): ?>
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <h5>Sin registros para este cliente</h5>
                                    <p>No se encontró mercancía pendiente o excedente para el tercero seleccionado.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-modern align-middle table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th>Referencia</th>
                                                <?php foreach ($tallas as $talla): ?>
                                                    <th class="text-center"><?= h($talla) ?></th>
                                                <?php endforeach; ?>
                                                <th class="text-center">Total</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($referencias as $item): ?>
                                                <?php
                                                $totalClass = $item['total'] > 0 ? 'total-pos' : ($item['total'] < 0 ? 'total-neg' : 'total-zero');
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="ref-main"><?= h($item['producto']['referencia']) ?></div>
                                                        <div class="d-flex gap-2 flex-wrap mt-1">
                                                            <span class="chip-soft">
                                                                <i class="fas fa-tag"></i>
                                                                <?= h($item['producto']['categoria']) ?>
                                                            </span>
                                                            <span class="chip-soft">
                                                                <i class="fas fa-palette"></i>
                                                                <?= h($item['producto']['color']) ?>
                                                            </span>
                                                        </div>
                                                    </td>

                                                    <?php foreach ($tallas as $talla): ?>
                                                        <?php
                                                        $valor = (float)($item['cantidades'][$talla] ?? 0);
                                                        $cellClass = 'cell-zero';
                                                        if ($valor > 0) {
                                                            $cellClass = 'cell-pos';
                                                        } elseif ($valor < 0) {
                                                            $cellClass = 'cell-neg';
                                                        }
                                                        ?>
                                                        <td class="<?= $cellClass ?>">
                                                            <?php if ($valor > 0): ?>
                                                                <a href="#"
                                                                   class="link-cell"
                                                                   data-bs-toggle="modal"
                                                                   data-bs-target="#cierre_pedido"
                                                                   data-nombre_usuario="<?= h($nombreUsuarioSesion) ?>"
                                                                   data-nombre_tercero="<?= h($nombre_tercero) ?>"
                                                                   data-referencia_producto="<?= h($item['producto']['referencia']) ?>"
                                                                   data-talla="<?= h($talla) ?>"
                                                                   data-cantidad="<?= h($valor) ?>">
                                                                    <?= nf0($valor) ?>
                                                                </a>
                                                            <?php elseif ($valor < 0): ?>
                                                                <?= nf0($valor) ?>
                                                            <?php else: ?>
                                                                0
                                                            <?php endif; ?>
                                                        </td>
                                                    <?php endforeach; ?>

                                                    <td class="text-center <?= $totalClass ?>">
                                                        <?= nf0($item['total']) ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>

                                <div class="legend-wrap">
                                    <span class="legend-item">
                                        <span class="legend-box pos"></span>
                                        Mercancía por despachar
                                    </span>
                                    <span class="legend-item">
                                        <span class="legend-box neg"></span>
                                        Mercancía despachada de más
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

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

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

    <div class="modal fade text-start text-dark" id="cierre_pedido" tabindex="-1" aria-labelledby="cierrePedidoLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content border-0" style="border-radius:18px; overflow:hidden;">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title card-heading" id="cierrePedidoLabel">Hacer cierre</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/cierre-pedido.php">
                    <div class="modal-body row g-2">
                        <div class="col-sm-12 mt-2">
                            <label class="form-label">Usuario de registro</label>
                            <input type="text" name="nombre_usuario" id="nombre_usuario" required readonly class="form-control">
                        </div>

                        <div class="col-sm-12 mt-2">
                            <label class="form-label">Tercero</label>
                            <input type="text" name="nombre_tercero" id="nombre_tercero_modal" required readonly class="form-control">
                        </div>

                        <div class="col-sm-12 mt-2">
                            <label class="form-label">Referencia</label>
                            <input type="text" name="referencia_producto" id="referencia_producto" required readonly class="form-control">
                        </div>

                        <div class="col-sm-12 mt-2">
                            <label class="form-label">Talla</label>
                            <input type="text" name="talla" id="talla" required readonly class="form-control">
                        </div>

                        <div class="col-sm-12 mt-2">
                            <label class="form-label">Cantidad</label>
                            <input class="form-control" type="number" required name="cantidad" id="cantidad" placeholder="cant." value="">
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-warning" name="editar"
                            onclick="if (!confirm('Seguro deseas hacer cierre de este registro?')) { return false; }">
                            Guardar cambios
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $('.single-select').select2({
                theme: 'bootstrap4',
                width: '100%'
            });
        });

        $('#cierre_pedido').on('show.bs.modal', function(event) {
            var button = $(event.relatedTarget);

            $('#nombre_usuario').val(button.data('nombre_usuario'));
            $('#nombre_tercero_modal').val(button.data('nombre_tercero'));
            $('#referencia_producto').val(button.data('referencia_producto'));
            $('#talla').val(button.data('talla'));
            $('#cantidad').val(button.data('cantidad'));
        });
    </script>
</body>
</html>