<div class="content-wrapper">
    <section class="content-header">
        <h1>
            Dashboard
            <small><?php echo date('d/m/Y'); ?> — <?php echo !empty($empresa->nombre) ? $empresa->nombre : 'AteneaVD'; ?></small>
        </h1>
    </section>

    <section class="content">

        <!-- FILA 1 — CARDS RESUMEN DEL DÍA -->
        <div class="row" style="margin-bottom:15px;">

            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-green">
                    <span class="info-box-icon"><i class="fa fa-money"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ventas de hoy</span>
                        <span class="info-box-number">
                            S/ <?php echo number_format((float)($ventas_hoy->total_ventas ?? 0), 2); ?>
                        </span>
                        <div class="progress"><div class="progress-bar" style="width:100%"></div></div>
                        <span class="progress-description">
                            <?php echo (int)($ventas_hoy->total_comprobantes ?? 0); ?> comprobante(s)
                        </span>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-blue">
                    <span class="info-box-icon"><i class="fa fa-arrow-down"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ingresos al almacén hoy</span>
                        <span class="info-box-number"><?php echo (int)($pi_hoy->total ?? 0); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:100%"></div></div>
                        <span class="progress-description">
                            <a href="<?php echo base_url('index.php/logistica/parte_ingreso'); ?>" style="color:#fff;">
                                Ver partes de ingreso
                            </a>
                        </span>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-sm-6">
                <div class="info-box bg-yellow">
                    <span class="info-box-icon"><i class="fa fa-arrow-up"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Salidas del almacén hoy</span>
                        <span class="info-box-number"><?php echo (int)($ps_hoy->total ?? 0); ?></span>
                        <div class="progress"><div class="progress-bar" style="width:100%"></div></div>
                        <span class="progress-description">
                            <a href="<?php echo base_url('index.php/logistica/parte_salida'); ?>" style="color:#fff;">
                                Ver partes de salida
                            </a>
                        </span>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-sm-6">
                <div class="info-box <?php echo ($oc_pendientes->total > 0) ? 'bg-red' : 'bg-gray'; ?>">
                    <span class="info-box-icon"><i class="fa fa-shopping-cart"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">OC por autorizar</span>
                        <span class="info-box-number"><?php echo (int)$oc_pendientes->total; ?></span>
                        <div class="progress"><div class="progress-bar" style="width:100%"></div></div>
                        <span class="progress-description">
                            <a href="<?php echo base_url('index.php/logistica/orden_compra/bandeja'); ?>" style="color:#fff;">
                                Ver bandeja
                            </a>
                        </span>
                    </div>
                </div>
            </div>

        </div>

        <!-- ============================================================ -->
        <!-- FILA 2 — ACCESOS RÁPIDOS (antes estaban en fila 4) -->
        <!-- ============================================================ -->
        <div class="row" style="margin-bottom:15px;">
            <div class="col-md-12">
                <div class="box box-default">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-bolt"></i> Accesos rápidos</h3>
                    </div>
                    <div class="box-body" style="padding:10px 15px;">
                        <div class="row text-center">

                            <?php if(tiene_permiso('cotizaciones_crear')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/ventas/cotizaciones/create'); ?>"
                                   class="btn btn-info btn-block acceso-rapido">
                                    <i class="fa fa-file-text-o fa-lg"></i><br>
                                    <small>Nueva Cotización</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('comprobante_crear')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/ventas/comprobante/create'); ?>"
                                   class="btn btn-success btn-block acceso-rapido">
                                    <i class="fa fa-file-text fa-lg"></i><br>
                                    <small>Nueva Venta</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('orden_compra_crear')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/logistica/orden_compra/create'); ?>"
                                   class="btn btn-primary btn-block acceso-rapido">
                                    <i class="fa fa-shopping-cart fa-lg"></i><br>
                                    <small>Nueva OC</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('parte_ingreso_crear')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/logistica/parte_ingreso/create'); ?>"
                                   class="btn btn-info btn-block acceso-rapido">
                                    <i class="fa fa-arrow-down fa-lg"></i><br>
                                    <small>Parte Ingreso</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('kardex_ver')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/almacen/kardex'); ?>"
                                   class="btn btn-warning btn-block acceso-rapido">
                                    <i class="fa fa-list-alt fa-lg"></i><br>
                                    <small>Kardex</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('stock_ver')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/almacen/stock'); ?>"
                                   class="btn btn-default btn-block acceso-rapido">
                                    <i class="fa fa-cubes fa-lg"></i><br>
                                    <small>Reporte Stock</small>
                                </a>
                            </div>
                            <?php endif; ?>

                            <?php if(tiene_permiso('cuentas_cobrar_ver')): ?>
                            <div class="col-md-1-7 col-sm-4 col-xs-6" style="margin-bottom:10px; width:14.28%;">
                                <a href="<?php echo base_url('index.php/cobranzas/cuentas_cobrar'); ?>"
                                   class="btn btn-danger btn-block acceso-rapido">
                                    <i class="fa fa-dollar fa-lg"></i><br>
                                    <small>Ctas. por Cobrar</small>
                                </a>
                            </div>
                            <?php endif; ?>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ============================================================ -->
        <!-- FILA 3 — GRÁFICO + TOP PRODUCTOS -->
        <!-- ============================================================ -->
        <div class="row" style="margin-bottom:15px;">

            <div class="col-md-8">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-bar-chart"></i> Ventas últimos 30 días</h3>
                    </div>
                    <div class="box-body">
                        <canvas id="graficoVentas" height="100"></canvas>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="box box-success">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-star"></i> Top productos del mes</h3>
                    </div>
                    <div class="box-body" style="padding:0;">
                        <?php if(!empty($top_productos)): ?>
                            <table class="table table-condensed" style="margin:0;">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Producto</th>
                                        <th class="text-right">Cant.</th>
                                        <th class="text-right">S/</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $n = 1; foreach($top_productos as $item): ?>
                                        <tr>
                                            <td><?php echo $n++; ?></td>
                                            <td style="max-width:120px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="<?php echo $item->producto; ?>">
                                                <?php echo $item->producto; ?>
                                            </td>
                                            <td class="text-right"><?php echo number_format((float)$item->cantidad_total, 0); ?></td>
                                            <td class="text-right"><?php echo number_format((float)$item->monto_total, 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <p class="text-muted text-center" style="padding:20px;">Sin ventas este mes</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>

        <!-- ============================================================ -->
        <!-- FILA 4 — ALERTAS (antes estaban en fila 2) -->
        <!-- ============================================================ -->
        <div class="row" style="margin-bottom:15px;">

            <div class="col-md-3">
                <a href="<?php echo base_url('index.php/cobranzas/vencimientos_cobro'); ?>" style="text-decoration:none;">
                    <div class="small-box <?php echo ($cobrar_vencidos->total > 0) ? 'bg-red' : 'bg-gray'; ?>">
                        <div class="inner">
                            <h3><?php echo (int)($cobrar_vencidos->total ?? 0); ?></h3>
                            <p>Cobros vencidos</p>
                            <small>S/ <?php echo number_format((float)($cobrar_vencidos->monto ?? 0), 2); ?></small>
                        </div>
                        <div class="icon"><i class="fa fa-exclamation-circle"></i></div>
                    </div>
                </a>
            </div>

            <div class="col-md-3">
                <a href="<?php echo base_url('index.php/cobranzas/vencimientos_cobro?dias=7'); ?>" style="text-decoration:none;">
                    <div class="small-box <?php echo ($cobrar_por_vencer->total > 0) ? 'bg-yellow' : 'bg-gray'; ?>">
                        <div class="inner">
                            <h3><?php echo (int)($cobrar_por_vencer->total ?? 0); ?></h3>
                            <p>Por cobrar — próx. 7 días</p>
                            <small>S/ <?php echo number_format((float)($cobrar_por_vencer->monto ?? 0), 2); ?></small>
                        </div>
                        <div class="icon"><i class="fa fa-clock-o"></i></div>
                    </div>
                </a>
            </div>

            <div class="col-md-3">
                <a href="<?php echo base_url('index.php/logistica/vencimientos'); ?>" style="text-decoration:none;">
                    <div class="small-box <?php echo ($pagar_vencidos->total > 0) ? 'bg-red' : 'bg-gray'; ?>">
                        <div class="inner">
                            <h3><?php echo (int)($pagar_vencidos->total ?? 0); ?></h3>
                            <p>Pagos a proveedores vencidos</p>
                            <small>S/ <?php echo number_format((float)($pagar_vencidos->monto ?? 0), 2); ?></small>
                        </div>
                        <div class="icon"><i class="fa fa-credit-card"></i></div>
                    </div>
                </a>
            </div>

            <div class="col-md-3">
                <a href="<?php echo base_url('index.php/almacen/stock'); ?>" style="text-decoration:none;">
                    <div class="small-box <?php echo ($stock_bajo->total > 0) ? 'bg-orange' : 'bg-gray'; ?>">
                        <div class="inner">
                            <h3><?php echo (int)$stock_bajo->total; ?></h3>
                            <p>Productos bajo stock mínimo</p>
                            <small>Requieren reposición</small>
                        </div>
                        <div class="icon"><i class="fa fa-cubes"></i></div>
                    </div>
                </a>
            </div>

        </div>

    </section>
</div>

<style>
.acceso-rapido {
    padding: 10px 4px;
    font-size: 12px;
}
.acceso-rapido i {
    display: block;
    margin-bottom: 4px;
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script>
window.addEventListener('load', function () {

    var labels = <?php
        $labels = array();
        $valores = array();
        $fecha_inicio = date('Y-m-d', strtotime('-29 days'));
        $ventas_map   = array();
        foreach ($ventas_30dias as $v) {
            $ventas_map[$v->fecha_raw] = (float)$v->total;
        }
        for ($i = 29; $i >= 0; $i--) {
            $dia   = date('Y-m-d', strtotime('-' . $i . ' days'));
            $label = date('d/m', strtotime('-' . $i . ' days'));
            $labels[] = $label;
            $valores[] = isset($ventas_map[$dia]) ? $ventas_map[$dia] : 0;
        }
        echo json_encode($labels);
    ?>;

    var valores = <?php echo json_encode($valores); ?>;

    var ctx = document.getElementById('graficoVentas').getContext('2d');
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Ventas (S/)',
                data: valores,
                backgroundColor: 'rgba(60, 141, 188, 0.7)',
                borderColor: 'rgba(60, 141, 188, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return 'S/ ' + parseFloat(context.raw).toFixed(2);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'S/ ' + value.toLocaleString();
                        }
                    }
                },
                x: {
                    ticks: { maxRotation: 45, minRotation: 45 }
                }
            }
        }
    });

});
</script>