<?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 = 'INNOVASUELAS ALMACEN';

$tallas = [];
$referencias = [];
$totalesPorTalla = [];

$stats = [
    'referencias'          => 0,
    'tallas'               => 0,
    'pendiente'            => 0,
    'exceso'               => 0,
    'balance_neto'         => 0,
    'refs_pendiente'       => 0,
    'refs_exceso'          => 0,
    'refs_balanceadas'     => 0,
];

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

$sqlDetalle = "
    SELECT 
        referencia_producto,
        talla,
        SUM(cantidad) AS cantidad
    FROM referencia_despacho
    WHERE nombre_tercero = '$nombre_tercero'
    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,
                'pendiente'  => 0,
                'exceso'     => 0,
                'estado'     => 'Balanceado',
            ];
        }

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

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

        $totalesPorTalla[$talla] += $cantidad;
        $stats['balance_neto'] += $cantidad;
    }
}

$productos = [];

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);

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

    foreach ($temp as $ref => $data) {
        if ($data['total'] > 0) {
            $data['estado'] = 'Pendiente';
            $stats['refs_pendiente']++;
        } elseif ($data['total'] < 0) {
            $data['estado'] = 'Despachado de más';
            $stats['refs_exceso']++;
        } else {
            $data['estado'] = ($data['pendiente'] > 0 && $data['exceso'] > 0) ? 'Compensado' : 'Balanceado';
            $stats['refs_balanceadas']++;
        }

        $referencias[] = [
            'producto'   => $productos[$ref] ?? [
                'referencia' => $ref,
                'color'      => 'No registra',
                'categoria'  => 'No registra',
            ],
            'cantidades' => $data['cantidades'],
            'total'      => $data['total'],
            'pendiente'  => $data['pendiente'],
            'exceso'     => $data['exceso'],
            'estado'     => $data['estado'],
        ];
    }
}

$stats['referencias'] = count($referencias);
$stats['tallas'] = count($tallas);

function badgeEstadoClase($estado)
{
    switch ($estado) {
        case 'Pendiente':
            return 'badge-pendiente';
        case 'Despachado de más':
            return 'badge-exceso';
        case 'Compensado':
            return 'badge-compensado';
        default:
            return 'badge-balanceado';
    }
}
?>
<!doctype html>
<html lang="es" class="light-theme">
<head>
    <?php include '../general/libreria-css.php'; ?>

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

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

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

        .page-title-card .card-body,
        .report-card .card-body,
        .legend-card .card-body {
            padding: 1.25rem 1.35rem;
        }

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

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

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

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

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

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

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

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

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

        .qty-positive {
            text-align: center;
            font-weight: 800;
            color: #0369a1;
            background: rgba(59, 130, 246, .08);
        }

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

        .qty-total-positive {
            text-align: center;
            font-weight: 800;
            color: #0369a1;
        }

        .qty-total-negative {
            text-align: center;
            font-weight: 800;
            color: #b91c1c;
        }

        .qty-total-neutral {
            text-align: center;
            font-weight: 800;
            color: #475569;
        }

        .badge-soft {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 999px;
            padding: .42rem .78rem;
            font-size: .78rem;
            font-weight: 800;
            border: 1px solid transparent;
            white-space: nowrap;
        }

        .badge-pendiente {
            background: rgba(59, 130, 246, .12);
            color: #1d4ed8;
            border-color: rgba(59, 130, 246, .18);
        }

        .badge-exceso {
            background: rgba(239, 68, 68, .12);
            color: #b91c1c;
            border-color: rgba(239, 68, 68, .18);
        }

        .badge-balanceado {
            background: rgba(34, 197, 94, .12);
            color: #15803d;
            border-color: rgba(34, 197, 94, .18);
        }

        .badge-compensado {
            background: rgba(245, 158, 11, .12);
            color: #b45309;
            border-color: rgba(245, 158, 11, .18);
        }

        .legend-item {
            display: inline-flex;
            align-items: center;
            gap: .45rem;
            margin-right: 1rem;
            margin-bottom: .5rem;
            font-weight: 600;
            color: var(--text-main);
        }

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

        .legend-pos {
            background: rgba(59, 130, 246, .75);
        }

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

        .legend-zero {
            background: rgba(148, 163, 184, .75);
        }

        @media print {
            body {
                background: #fff !important;
            }

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

            .page-title-card,
            .stats-card,
            .report-card,
            .legend-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">
                            <a href="empresa.php">Fábrica</a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Pendiente</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Pendiente</div>
                        <p class="page-subtitle">
                            Consolidado por referencia y talla para revisar mercancía pendiente, exceso de despacho y balance del tercero.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-building"></i>
                                <?= h($nombre_tercero) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-layer-group"></i>
                                Referencias: <?= nf0($stats['referencias']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-ruler-combined"></i>
                                Tallas: <?= nf0($stats['tallas']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <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 text-primary"><?= nf0($stats['pendiente']) ?></div>
                                <div class="stats-note">Pares aún por despachar</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-triangle-exclamation"></i></div>
                                <div class="stats-title">Despachado de más</div>
                                <div class="stats-value text-danger"><?= nf0($stats['exceso']) ?></div>
                                <div class="stats-note">Pares con exceso</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-3">
                        <div class="card stats-card">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-circle-info"></i></div>
                                <div class="stats-title">Refs. pendientes</div>
                                <div class="stats-value"><?= nf0($stats['refs_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-circle-xmark"></i></div>
                                <div class="stats-title">Refs. con exceso</div>
                                <div class="stats-value"><?= nf0($stats['refs_exceso']) ?></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-scale-balanced"></i></div>
                                <div class="stats-title">Refs. balanceadas</div>
                                <div class="stats-value"><?= nf0($stats['refs_balanceadas']) ?></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-chart-line"></i></div>
                                <div class="stats-title">Balance neto</div>
                                <div class="stats-value <?= $stats['balance_neto'] < 0 ? 'text-danger' : ($stats['balance_neto'] > 0 ? 'text-primary' : '') ?>">
                                    <?= nf0($stats['balance_neto']) ?>
                                </div>
                                <div class="stats-note">Pendiente menos exceso</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card legend-card mb-3">
                    <div class="card-body">
                        <div class="legend-item">
                            <span class="legend-dot legend-pos"></span>
                            Mercancía por despachar
                        </div>
                        <div class="legend-item">
                            <span class="legend-dot legend-neg"></span>
                            Mercancía despachada de más
                        </div>
                        <div class="legend-item">
                            <span class="legend-dot legend-zero"></span>
                            Sin diferencia
                        </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>Consolidado pendiente por tercero</h4>
                                    <p><?= h($nombre_tercero) ?></p>

                                    <div class="report-badges">
                                        <span class="info-chip">
                                            <i class="fas fa-truck-loading"></i>
                                            Pendiente: <?= nf0($stats['pendiente']) ?>
                                        </span>
                                        <span class="info-chip">
                                            <i class="fas fa-triangle-exclamation"></i>
                                            Exceso: <?= nf0($stats['exceso']) ?>
                                        </span>
                                        <span class="info-chip">
                                            <i class="fas fa-scale-balanced"></i>
                                            Balance: <?= nf0($stats['balance_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>

                        <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>
                                        <th class="text-center">Pendiente</th>
                                        <th class="text-center">Exceso</th>
                                        <th class="text-center">Estado</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($referencias)): ?>
                                        <tr>
                                            <td colspan="<?= count($tallas) + 4 ?>" class="text-center text-muted py-4">
                                                No hay registros para mostrar.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($referencias as $item): ?>
                                            <?php
                                            $claseTotal = 'qty-total-neutral';
                                            if ($item['total'] > 0) {
                                                $claseTotal = 'qty-total-positive';
                                            } elseif ($item['total'] < 0) {
                                                $claseTotal = 'qty-total-negative';
                                            }
                                            ?>
                                            <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);
                                                    $clase = 'qty-neutral';
                                                    if ($valor > 0) {
                                                        $clase = 'qty-positive';
                                                    } elseif ($valor < 0) {
                                                        $clase = 'qty-negative';
                                                    }
                                                    ?>
                                                    <td class="<?= $clase ?>">
                                                        <?= $valor != 0 ? nf0($valor) : '' ?>
                                                    </td>
                                                <?php endforeach; ?>

                                                <td class="<?= $claseTotal ?>"><?= nf0($item['total']) ?></td>
                                                <td class="text-center text-primary fw-bold"><?= $item['pendiente'] > 0 ? nf0($item['pendiente']) : '' ?></td>
                                                <td class="text-center text-danger fw-bold"><?= $item['exceso'] > 0 ? nf0($item['exceso']) : '' ?></td>
                                                <td class="text-center">
                                                    <span class="badge-soft <?= badgeEstadoClase($item['estado']) ?>">
                                                        <?= h($item['estado']) ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>

                                <?php if (!empty($referencias)): ?>
                                    <tfoot>
                                        <tr>
                                            <th class="text-end">Total por talla</th>
                                            <?php foreach ($tallas as $talla): ?>
                                                <?php
                                                $valor = (float)($totalesPorTalla[$talla] ?? 0);
                                                $clase = 'qty-total-neutral';
                                                if ($valor > 0) {
                                                    $clase = 'qty-total-positive';
                                                } elseif ($valor < 0) {
                                                    $clase = 'qty-total-negative';
                                                }
                                                ?>
                                                <th class="<?= $clase ?>"><?= $valor != 0 ? nf0($valor) : '' ?></th>
                                            <?php endforeach; ?>
                                            <th class="<?= $stats['balance_neto'] > 0 ? 'qty-total-positive' : ($stats['balance_neto'] < 0 ? 'qty-total-negative' : 'qty-total-neutral') ?>">
                                                <?= nf0($stats['balance_neto']) ?>
                                            </th>
                                            <th class="text-center text-primary"><?= nf0($stats['pendiente']) ?></th>
                                            <th class="text-center text-danger"><?= nf0($stats['exceso']) ?></th>
                                            <th></th>
                                        </tr>
                                    </tfoot>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                </div>

            </div>

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

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