<?php
// Inicio de sesión
include 'includes/session_control.php';

require_once 'cotizaciones/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

$r = cpn_node_request('GET', $base . '/api/dashboard/home', $token, null);
$d = !empty($r['ok']) ? ($r['data'] ?? []) : [];

$cotSeguimiento = (int)($d['cotSeguimiento'] ?? ($d['cotCount'] ?? 0));
$ventasProc = (int)($d['ventasProc'] ?? 0);
$ventasSinEnvio = (int)($d['ventasSinEnvio'] ?? 0);
$pedidosProc = (int)($d['pedidosProc'] ?? 0);
$pedidosPorRecoger = (int)($d['pedidosPorRecoger'] ?? 0);
$pedidosPorCruzar = (int)($d['pedidosPorCruzar'] ?? 0);
$productosSolicit = (int)($d['productosSolicit'] ?? 0);
$impresionesProc = (int)($d['impresionesProc'] ?? 0);
$prodMalPublicados = (int)($d['prodMalPublicados'] ?? 0);
$prodPendientesPublicar = (int)($d['prodPendientesPublicar'] ?? ($d['prodChecklist'] ?? 0));
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Tablero de Control</title>
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/compranet.css" rel="stylesheet">
    <style>
        /* Tablero compacto y legible */
        .dash-title {
            font-weight: 700;
            letter-spacing: .2px;
        }

        .dashboard-card {
            display: flex;
            flex-direction: column;
            min-height: 92px;
        }

        .dashboard-card .card-body {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: .6rem .85rem;
        }

        .dashboard-card .card-left {
            display: flex;
            align-items: center;
            gap: .65rem;
            min-width: 0;
        }

        .dashboard-card .card-icon {
            font-size: 1.25rem;
            opacity: .95;
        }

        .dashboard-card .card-title {
            font-size: .9rem;
            margin: 0;
            line-height: 1.1;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .dashboard-card .card-count {
            font-size: 1.6rem;
            font-weight: 800;
            line-height: 1;
            margin: 0;
            text-align: right;
        }

        .dashboard-card .card-footer {
            background: transparent;
            border-top: 0;
            padding: .35rem .85rem .6rem;
            display: flex;
            justify-content: flex-end;
        }

        .dashboard-card .btn {
            padding: .2rem .55rem;
        }

        .section-gap {
            margin-top: .5rem;
            margin-bottom: .75rem;
        }

        .table-sm td,
        .table-sm th {
            padding: .35rem .5rem;
        }

        .table thead th {
            background: #1f2937;
            color: #fff;
            border-color: #2d3748;
        }

        .table-bordered td,
        .table-bordered th {
            border-color: #e5e7eb;
        }

        .card-header {
            background: #fff;
        }

        /* Mejora contraste de textos "muted" en el tablero */
        .text-muted {
            color: #6b7280 !important;
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include 'templates/sidebar.php'; ?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include 'templates/topbar.php'; ?>
                <div class="container-fluid">
                    <div class="d-flex align-items-center justify-content-between section-gap">
                        <h1 class="h4 mb-0 dash-title text-gray-900">Tablero de Control</h1>
                        <small class="text-muted">Vista resumida (todo en una pantalla)</small>
                    </div>

                    <!-- Indicadores (compacto) -->
                    <div class="row">
                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-info dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-file-alt card-icon"></i>
                                        <h5 class="card-title">Cotizaciones en seguimiento</h5>
                                    </div>
                                    <div class="card-count"><?= $cotSeguimiento ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/cotizaciones/historialcotizaciones.php" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-primary dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-shopping-cart card-icon"></i>
                                        <h5 class="card-title">Ventas en proceso</h5>
                                    </div>
                                    <div class="card-count"><?= $ventasProc ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ventas/ordenes.php?filter_id=&filter_refExt=&filter_cliente=&filter_estado=1&filter_tipo=0&filter_medio=0" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-warning dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-truck card-icon"></i>
                                        <h5 class="card-title">Ventas sin envío</h5>
                                    </div>
                                    <div class="card-count"><?= $ventasSinEnvio ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ventas/ordenes.php" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-secondary dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-clipboard-list card-icon"></i>
                                        <h5 class="card-title">Pedidos por enviar</h5>
                                    </div>
                                    <div class="card-count"><?= $pedidosProc ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ordenes/pedidos.php?filter_id=&filter_factura=&filter_proveedor=0&filter_estado=1" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-info dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-box card-icon"></i>
                                        <h5 class="card-title">Pedidos por recoger</h5>
                                    </div>
                                    <div class="card-count"><?= $pedidosPorRecoger ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ordenes/pedidos.php?filter_id=&filter_factura=&filter_proveedor=0&filter_estado=2" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-danger dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-file-invoice card-icon"></i>
                                        <h5 class="card-title">Pedidos por cruzar factura</h5>
                                    </div>
                                    <div class="card-count"><?= $pedidosPorCruzar ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ordenes/pedidos.php?filter_id=&filter_factura=&filter_proveedor=0&filter_estado=4" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-danger dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-box-open card-icon"></i>
                                        <h5 class="card-title">Productos por solicitar</h5>
                                    </div>
                                    <div class="card-count"><?= $productosSolicit ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/ordenes/pedidos_por_solicitar.php" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-primary dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-print card-icon"></i>
                                        <h5 class="card-title">Impresiones en proceso</h5>
                                    </div>
                                    <div class="card-count"><?= $impresionesProc ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/marcacion/trabajos.php" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-success dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-tags card-icon"></i>
                                        <h5 class="card-title">Mal publicados</h5>
                                    </div>
                                    <div class="card-count"><?= $prodMalPublicados ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/productos/items.php?filter_checklist_group=mal_publicados" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12 mb-3">
                            <div class="card text-white bg-warning dashboard-card shadow-sm">
                                <div class="card-body">
                                    <div class="card-left">
                                        <i class="fas fa-tasks card-icon"></i>
                                        <h5 class="card-title">Pendientes para publicar</h5>
                                    </div>
                                    <div class="card-count"><?= $prodPendientesPublicar ?></div>
                                </div>
                                <div class="card-footer">
                                    <a href="/productos/items.php?filter_checklist_group=pendientes" class="btn btn-outline-light btn-sm">Ver</a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Seguimiento de cotizaciones (próximas gestiones) -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">Seguimiento de cotizaciones (próxima gestión)</h6>
                                    <a href="/cotizaciones/historialcotizaciones.php" class="btn btn-primary btn-sm">Ver todas</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-sm mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 80px;" class="text-center">Id</th>
                                                    <th>Cliente</th>
                                                    <th style="width: 180px;" class="text-center">Próx. gestión</th>
                                                    <th style="width: 90px;" class="text-center">Acción</th>
                                                </tr>
                                            </thead>
                                            <tbody id="cotPendientesTbody">
                                                <tr>
                                                    <td colspan="4" class="text-center text-muted">Cargando...</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <small class="text-muted d-block mt-2">Incluye atrasadas y las programadas en los próximos 15 días.</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Modal: Notas de seguimiento -->
                    <div class="modal fade" id="cotNotasModal" tabindex="-1" role="dialog" aria-hidden="true">
                        <div class="modal-dialog modal-lg" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">Notas de seguimiento <span class="text-muted" id="cotNotasTitle"></span></h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <div class="mb-2">
                                        <strong>Cliente:</strong> <span id="cotNotasCliente">—</span>
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered mb-0">
                                            <thead>
                                                <tr>
                                                    <th style="width: 150px;">Fecha</th>
                                                    <th style="width: 160px;">Responsable</th>
                                                    <th style="width: 120px;">Resultado</th>
                                                    <th>Nota</th>
                                                    <th style="width: 150px;">Próx. gestión</th>
                                                </tr>
                                            </thead>
                                            <tbody id="cotNotasTbody">
                                                <tr>
                                                    <td colspan="5" class="text-center text-muted">Cargando...</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> <!-- /.container-fluid -->
            </div> <!-- /#content -->
            <?php include 'templates/footer.php'; ?>
        </div> <!-- /#content-wrapper -->
    </div> <!-- /#wrapper -->

    <!-- Scripts -->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>

    <script>
        (function() {
            function loadCotPendientes() {
                $.getJSON('/cotizaciones/get_cotizaciones.php', {
                    limit: 10,
                    page: 1,
                    agendaDays: 15,
                    view: 'pending_widget'
                }).done(function(r) {
                    var html = (r && r.rows) ? r.rows : '';
                    if (!html) {
                        html = '<tr><td colspan="4" class="text-center text-muted">Sin próximas gestiones</td></tr>';
                    }
                    $('#cotPendientesTbody').html(html);
                }).fail(function() {
                    $('#cotPendientesTbody').html('<tr><td colspan="4" class="text-center text-danger">Error cargando pendientes</td></tr>');
                });
            }

            $(loadCotPendientes);

            function escHtml(s) {
                return String(s || '').replace(/[&<>"']/g, function(ch) {
                    return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch];
                });
            }

            function fmtFecha(val) {
                if (!val) return '—';
                var s = String(val);
                var m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?:[ T]([0-9]{2}):([0-9]{2})(?::([0-9]{2}))?)?/.exec(s);
                if (!m) return s;
                var months = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
                var d = parseInt(m[3], 10);
                var mo = months[(parseInt(m[2], 10) - 1)] || 'Ene';
                var y = String(m[1]).slice(-2);
                var hh = parseInt(m[4] || '0', 10);
                var mm = String(m[5] || '0').padStart(2, '0');
                var hour12 = (hh % 12) || 12;
                var ampm = hh >= 12 ? 'pm' : 'am';
                return String(d).padStart(2, '0') + '-' + mo + '-' + y + ' ' + hour12 + ':' + mm + ' ' + ampm;
            }

            $(document).on('click', '.js-cot-notas', function() {
                var id = Number($(this).data('id') || 0);
                var cliente = $(this).data('cliente') || '';

                $('#cotNotasTitle').text(id ? ('#' + id) : '');
                $('#cotNotasCliente').text(cliente || '—');
                $('#cotNotasTbody').html('<tr><td colspan="5" class="text-center text-muted">Cargando...</td></tr>');
                $('#cotNotasModal').modal('show');

                if (!id) {
                    $('#cotNotasTbody').html('<tr><td colspan="5" class="text-center text-muted">Sin notas</td></tr>');
                    return;
                }

                $.getJSON('/cotizaciones/api/get_cot_seguimiento.php', { id: id })
                    .done(function(resp) {
                        if (!resp || !resp.ok) {
                            $('#cotNotasTbody').html('<tr><td colspan="5" class="text-center text-danger">Error cargando notas</td></tr>');
                            return;
                        }
                        var rows = Array.isArray(resp.data) ? resp.data : [];
                        if (!rows.length) {
                            $('#cotNotasTbody').html('<tr><td colspan="5" class="text-center text-muted">Sin notas</td></tr>');
                            return;
                        }
                        var html = '';
                        rows.forEach(function(r) {
                            var respNombre = (r.responsableNombre || '') + ' ' + (r.responsableApellido || '');
                            html += '<tr>'
                                + '<td>' + escHtml(fmtFecha(r.fecha)) + '</td>'
                                + '<td>' + escHtml(respNombre.trim() || '—') + '</td>'
                                + '<td>' + escHtml(r.resultado || '—') + '</td>'
                                + '<td>' + escHtml(r.nota || '') + '</td>'
                                + '<td>' + escHtml(fmtFecha(r.proximaGestion)) + '</td>'
                                + '</tr>';
                        });
                        $('#cotNotasTbody').html(html);
                    })
                    .fail(function() {
                        $('#cotNotasTbody').html('<tr><td colspan="5" class="text-center text-danger">Error cargando notas</td></tr>');
                    });
            });
        })();
    </script>
</body>

</html>
