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

date_default_timezone_set('America/Bogota');

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

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

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

function badgeEstadoDespacho($estado)
{
    switch (trim((string)$estado)) {
        case 'Proceso':
            return 'badge-proceso';
        case 'Enviado':
            return 'badge-enviado';
        case 'Recibido':
            return 'badge-recibido';
        case 'Cancelado':
            return 'badge-cancelado';
        default:
            return 'badge-default';
    }
}

$nombre_tercero = 'INNOVASUELAS ALMACEN';

$stats = [
    'despachos'        => 0,
    'pares'            => 0,
    'paquetes'         => 0,
    'proceso'          => 0,
    'enviado'          => 0,
    'recibido'         => 0,
    'cancelado'        => 0,
    'promedio_pares'   => 0,
    'promedio_paquetes'=> 0,
];

$despachos = [];

$sqlDespachos = "
    SELECT 
        d.*,
        COALESCE(dd.cantidad_total, 0) AS cantidad_total,
        COALESCE(dp.paquetes_total, 0) AS paquetes_total
    FROM despacho d
    LEFT JOIN (
        SELECT id_despacho, SUM(cantidad) AS cantidad_total
        FROM despacho_detalle
        GROUP BY id_despacho
    ) dd ON dd.id_despacho = d.id
    LEFT JOIN (
        SELECT id_despacho, SUM(cantidad) AS paquetes_total
        FROM despacho_paquete
        GROUP BY id_despacho
    ) dp ON dp.id_despacho = d.id
    WHERE d.nombre_tercero = '$nombre_tercero'
    ORDER BY d.fecha DESC, d.id DESC
";
$queryDespachos = $conn->query($sqlDespachos);

if ($queryDespachos && $queryDespachos->num_rows > 0) {
    while ($row = $queryDespachos->fetch_assoc()) {
        $despachos[] = $row;

        $stats['despachos']++;
        $stats['pares'] += (float)$row['cantidad_total'];
        $stats['paquetes'] += (float)$row['paquetes_total'];

        switch (trim((string)$row['estado'])) {
            case 'Proceso':
                $stats['proceso']++;
                break;
            case 'Enviado':
                $stats['enviado']++;
                break;
            case 'Recibido':
                $stats['recibido']++;
                break;
            case 'Cancelado':
                $stats['cancelado']++;
                break;
        }
    }
}

if ($stats['despachos'] > 0) {
    $stats['promedio_pares'] = $stats['pares'] / $stats['despachos'];
    $stats['promedio_paquetes'] = $stats['paquetes'] / $stats['despachos'];
}
?>
<!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,
        .list-card,
        .action-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body,
        .list-card .card-body,
        .action-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.1rem;
        }

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

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

        .stats-value {
            font-size: 1.35rem;
            font-weight: 800;
            line-height: 1.1;
            color: var(--text-main);
        }

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

        .section-head {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }

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

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

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

        .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 {
            padding: .82rem .65rem;
            vertical-align: middle;
            border-color: #eef2f7;
            white-space: nowrap;
        }

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

        .dispatch-number {
            font-weight: 800;
            color: #111827;
        }

        .dispatch-obs {
            max-width: 280px;
            white-space: normal;
            color: #475569;
        }

        .dispatch-dest {
            font-weight: 700;
            color: #0f172a;
        }

        .qty-cell {
            font-weight: 800;
            color: #0f172a;
        }

        .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-proceso {
            background: rgba(59, 130, 246, .12);
            color: #1d4ed8;
            border-color: rgba(59, 130, 246, .18);
        }

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

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

        .badge-cancelado {
            background: rgba(100, 116, 139, .12);
            color: #475569;
            border-color: rgba(100, 116, 139, .18);
        }

        .badge-default {
            background: #f8fafc;
            color: #334155;
            border-color: #e2e8f0;
        }

        .btn-detail {
            width: 38px;
            height: 38px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #e5e7eb;
            color: #111827;
            background: #fff;
            text-decoration: none;
            transition: all .18s ease;
        }

        .btn-detail:hover {
            background: #111827;
            color: #fff;
            border-color: #111827;
        }

        .modal-content {
            border: 0;
            border-radius: 18px;
            overflow: hidden;
        }

        .modal-header-modern {
            background: linear-gradient(135deg, #0ea5e9 0%, #2563eb 100%);
            color: #fff;
            border-bottom: 0;
        }

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

        @media print {
            .d-print-none,
            .wrapper aside,
            .top-header,
            .dataTables_filter,
            .dataTables_length,
            .dt-buttons,
            .dataTables_paginate,
            .dataTables_info {
                display: none !important;
            }

            body {
                background: #fff !important;
            }

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

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

                <nav aria-label="breadcrumb" class="mb-3 d-print-none">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item">
                            <a href="../inicio/inicio.php">
                                <ion-icon name="home-outline"></ion-icon>
                            </a>
                        </li>
                        <li class="breadcrumb-item">
                            <a href="empresa.php">Fábrica</a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Despachos</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Despachos</div>
                        <p class="page-subtitle">
                            Control de despachos enviados al almacén, con resumen de volumen, paquetes y estados del proceso.
                        </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-truck-fast"></i>
                                Despachos: <?= nf0($stats['despachos']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-boxes-stacked"></i>
                                Pares: <?= nf0($stats['pares']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-box-open"></i>
                                Paquetes: <?= nf0($stats['paquetes']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-truck-fast"></i></div>
                                <div class="stats-title">Despachos</div>
                                <div class="stats-value"><?= nf0($stats['despachos']) ?></div>
                                <div class="stats-note">Total de registros generados</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-boxes-stacked"></i></div>
                                <div class="stats-title">Pares</div>
                                <div class="stats-value"><?= nf0($stats['pares']) ?></div>
                                <div class="stats-note">Cantidad total despachada</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-box-open"></i></div>
                                <div class="stats-title">Paquetes</div>
                                <div class="stats-value"><?= nf0($stats['paquetes']) ?></div>
                                <div class="stats-note">Total de paquetes registrados</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-chart-line"></i></div>
                                <div class="stats-title">Promedio por despacho</div>
                                <div class="stats-value"><?= nf0($stats['promedio_pares']) ?></div>
                                <div class="stats-note"><?= nf0($stats['promedio_paquetes']) ?> paquetes promedio</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-hourglass-half"></i></div>
                                <div class="stats-title">En proceso</div>
                                <div class="stats-value text-primary"><?= nf0($stats['proceso']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-paper-plane"></i></div>
                                <div class="stats-title">Enviados</div>
                                <div class="stats-value text-warning"><?= nf0($stats['enviado']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-circle-check"></i></div>
                                <div class="stats-title">Recibidos</div>
                                <div class="stats-value text-success"><?= nf0($stats['recibido']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-ban"></i></div>
                                <div class="stats-title">Cancelados</div>
                                <div class="stats-value text-secondary"><?= nf0($stats['cancelado']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card list-card">
                    <div class="card-body">
                        <div class="section-head">
                            <div>
                                <div class="section-title">Lista de despachos</div>
                                <p class="section-subtitle">
                                    Consulta rápida del historial de despachos del módulo.
                                </p>
                            </div>

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

                                <button type="button" class="btn btn-dark btn-modern d-print-none" data-bs-toggle="modal" data-bs-target="#agregarDespachoModal">
                                    <i class="fas fa-plus me-1"></i> Nuevo despacho
                                </button>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-modern align-middle table-striped table-bordered" id="tablaDespachos">
                                <thead>
                                    <tr>
                                        <th class="text-center">Fecha</th>
                                        <th class="text-center">ID</th>
                                        <th class="text-center">No despacho</th>
                                        <th>Tercero</th>
                                        <th class="text-center">Destino</th>
                                        <th>Dirección</th>
                                        <th>Observación</th>
                                        <th class="text-center">Cant.</th>
                                        <th class="text-center">Paquetes</th>
                                        <th class="text-center">Estado</th>
                                        <th class="text-center">Detalle</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($despachos as $row): ?>
                                        <tr>
                                            <td class="text-center"><?= h(formatDateEs($row['fecha'])) ?></td>
                                            <td class="text-center"><?= h($row['id']) ?></td>
                                            <td class="text-center">
                                                <span class="dispatch-number"><?= h($row['numero_despacho']) ?></span>
                                            </td>
                                            <td><?= h($row['nombre_tercero']) ?></td>
                                            <td class="text-center">
                                                <span class="dispatch-dest"><?= h($row['destino']) ?></span>
                                            </td>
                                            <td><?= h($row['direccion']) ?></td>
                                            <td class="dispatch-obs"><?= h($row['observacion']) ?></td>
                                            <td class="text-center qty-cell"><?= nf0($row['cantidad_total']) ?></td>
                                            <td class="text-center qty-cell"><?= nf0($row['paquetes_total']) ?></td>
                                            <td class="text-center">
                                                <span class="badge-soft <?= badgeEstadoDespacho($row['estado']) ?>">
                                                    <?= h($row['estado']) ?>
                                                </span>
                                            </td>
                                            <td class="text-center">
                                                <a class="btn-detail" href="despacho-detalle.php?id_despacho=<?= h($row['id']) ?>">
                                                    <i class="fa-solid fa-arrow-right-to-bracket"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>

            </div>

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

    <div class="modal fade" id="agregarDespachoModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header modal-header-modern">
                    <h5 class="modal-title mb-0">Nuevo despacho</h5>
                    <button type="button" class="btn-close btn-close-white shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/despacho-guardar.php">
                    <div class="modal-body p-4">
                        <div class="row g-3">
                            <input type="hidden" name="nombre_usuario" value="<?= h($rowusu['nombre']) ?>">
                            <input type="hidden" name="nombre_tercero" value="<?= h($nombre_tercero) ?>">

                            <div class="col-md-6">
                                <label class="form-label-soft">Fecha</label>
                                <input class="form-control" type="date" required name="fecha" value="<?= date('Y-m-d') ?>">
                            </div>

                            <div class="col-md-6">
                                <label class="form-label-soft">Número despacho</label>
                                <input class="form-control" type="text" required name="numero_despacho" value="No aplica">
                            </div>

                            <div class="col-md-12">
                                <label class="form-label-soft">Tercero</label>
                                <input class="form-control" type="text" value="<?= h($nombre_tercero) ?>" readonly>
                            </div>

                            <div class="col-md-12">
                                <label class="form-label-soft">Observación</label>
                                <textarea class="form-control" rows="4" required name="observacion">No aplica</textarea>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer px-4 pb-4 border-0">
                        <button type="button" class="btn btn-outline-secondary btn-modern" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-dark btn-modern">Guardar despacho</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

    <script>
        $(document).ready(function () {
            var table = $('#tablaDespachos').DataTable({
                lengthChange: false,
                pageLength: 25,
                order: [],
                buttons: ['copy', 'excel', 'pdf', 'print'],
                language: {
                    search: 'Buscar',
                    zeroRecords: 'No hay registros para mostrar.',
                    emptyTable: 'La tabla está vacía.',
                    info: "Mostrando _START_ a _END_ de _TOTAL_ registros",
                    infoEmpty: "Mostrando 0 a 0 de 0 registros",
                    infoFiltered: "(filtrados de _MAX_ registros)",
                    paginate: {
                        first: 'Primero',
                        previous: 'Anterior',
                        next: 'Siguiente',
                        last: 'Último'
                    }
                }
            });

            table.buttons().container().appendTo('#tablaDespachos_wrapper .col-md-6:eq(0)');
        });
    </script>

</body>
</html>