<div class="content-wrapper">
    <section class="content-header">
        <h1>Ventas por Período</h1>
    </section>

    <section class="content">

        <!-- ============================================================ -->
        <!-- CABECERA SOLO PARA IMPRESIÓN -->
        <!-- ============================================================ -->
        <div id="cabeceraImpresion" class="print-only">
            <table style="width:100%; border:none; margin-bottom:10px;">
                <tr>
                    <td style="width:90px; vertical-align:top; border:none;">
                        <?php if(!empty($empresa->logo)): ?>
                            <img src="<?php echo base_url('uploads/empresa/'.$empresa->logo); ?>" style="max-width:80px; max-height:80px;">
                        <?php endif; ?>
                    </td>
                    <td style="vertical-align:top; border:none;">
                        <div style="font-size:15px; font-weight:bold;"><?php echo !empty($empresa->nombre) ? $empresa->nombre : ''; ?></div>
                        <div style="font-size:11px; color:#555;">RUC: <?php echo !empty($empresa->ruc) ? $empresa->ruc : ''; ?></div>
                        <div style="font-size:11px; color:#555;"><?php echo !empty($empresa->direccion_fiscal) ? $empresa->direccion_fiscal : ''; ?></div>
                    </td>
                    <td style="text-align:right; vertical-align:top; border:none;">
                        <div style="font-size:16px; font-weight:bold; text-transform:uppercase;">Reporte de Ventas por Período</div>
                        <div style="font-size:11px; color:#555;">Emitido: <?php echo $fecha_reporte; ?></div>
                        <div style="font-size:11px; color:#555;">
                            Año <?php echo $anio_actual; ?> vs Año <?php echo $anio_actual - 1; ?>
                        </div>
                    </td>
                </tr>
            </table>
            <hr style="margin:6px 0 12px; border-top:2px solid #333;">
        </div>

        <!-- FILTROS -->
        <div class="row no-print" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-12">
                <div class="panel panel-primary" id="panelFiltros">
                    <div class="panel-heading"><strong><i class="fa fa-filter"></i> Filtros</strong></div>
                    <div class="panel-body">
                        <form method="get" action="<?php echo base_url('index.php/ventas/ventas_periodo'); ?>">
                            <div class="row">
                                <div class="col-md-2 form-group">
                                    <label>Año</label>
                                    <select name="anio" class="form-control">
                                        <?php foreach($anios_disponibles as $a): ?>
                                            <option value="<?php echo $a; ?>" <?php echo ($a == $anio_actual) ? 'selected' : ''; ?>>
                                                <?php echo $a; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group" style="padding-top:25px;">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fa fa-search"></i> Consultar
                                    </button>
                                </div>
                                <div class="col-md-8 form-group" style="padding-top:25px;">
                                    <button type="button" onclick="window.print()" class="btn btn-default pull-right">
                                        <i class="fa fa-print"></i> Imprimir
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- CARDS RESUMEN -->
        <div class="row no-print" id="cardsResumen" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-3">
                <div class="panel panel-default">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Total <?php echo $anio_actual; ?></h4>
                        <h3>S/ <?php echo number_format($total_actual, 2); ?></h3>
                        <small><?php echo $total_comp_act; ?> comprobantes</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="panel panel-default">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Total <?php echo $anio_actual - 1; ?></h4>
                        <h3>S/ <?php echo number_format($total_anterior, 2); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="panel panel-<?php echo ($variacion_total === null) ? 'default' : ($variacion_total >= 0 ? 'success' : 'danger'); ?>">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Variación anual</h4>
                        <h3 class="<?php echo ($variacion_total === null) ? '' : ($variacion_total >= 0 ? 'text-success' : 'text-danger'); ?>">
                            <?php if($variacion_total === null): ?>
                                -
                            <?php else: ?>
                                <i class="fa fa-<?php echo $variacion_total >= 0 ? 'arrow-up' : 'arrow-down'; ?>"></i>
                                <?php echo number_format(abs($variacion_total), 1); ?>%
                            <?php endif; ?>
                        </h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="panel panel-default">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Promedio mensual</h4>
                        <h3>S/ <?php echo number_format($total_actual / 12, 2); ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- RESUMEN PARA IMPRESIÓN -->
        <table class="print-only tabla-resumen-print">
            <tr>
                <td><strong>Total <?php echo $anio_actual; ?>:</strong> S/ <?php echo number_format($total_actual, 2); ?> (<?php echo $total_comp_act; ?> comp.)</td>
                <td><strong>Total <?php echo $anio_actual - 1; ?>:</strong> S/ <?php echo number_format($total_anterior, 2); ?></td>
                <td>
                    <strong>Variación:</strong>
                    <?php echo $variacion_total === null ? '-' : number_format($variacion_total, 1) . '%'; ?>
                </td>
                <td><strong>Promedio mensual:</strong> S/ <?php echo number_format($total_actual / 12, 2); ?></td>
            </tr>
        </table>

        <!-- GRÁFICO COMPARATIVO -->
        <div class="row no-print">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-bar-chart"></i> Ventas mensuales — <?php echo $anio_actual; ?> vs <?php echo $anio_actual - 1; ?></h3>
                    </div>
                    <div class="box-body">
                        <canvas id="graficoVentasPeriodo" height="90"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- TABLA MENSUAL -->
        <div class="row" style="margin-bottom:5px !important;">
            <div class="col-md-12">
                <div class="panel panel-default reporte-panel">
                    <div class="panel-heading no-print"><strong>Detalle mensual</strong></div>
                    <div class="panel-body" style="padding:0;">
                        <table class="table table-bordered table-hover table-striped tabla-reporte" style="margin:0;">
                            <thead>
                                <tr style="background:#ecf0f1;">
                                    <th>Mes</th>
                                    <th class="text-center">N° Comprobantes</th>
                                    <th class="text-right">Ventas <?php echo $anio_actual; ?></th>
                                    <th class="text-right">Ventas <?php echo $anio_actual - 1; ?></th>
                                    <th class="text-center">Variación</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($filas as $f): ?>
                                    <tr>
                                        <td><?php echo $f['mes']; ?></td>
                                        <td class="text-center"><?php echo $f['comprobantes']; ?></td>
                                        <td class="text-right"><strong><?php echo number_format($f['total_actual'], 2); ?></strong></td>
                                        <td class="text-right"><?php echo number_format($f['total_anterior'], 2); ?></td>
                                        <td class="text-center">
                                            <?php if($f['variacion'] === null): ?>
                                                <span class="text-muted">-</span>
                                            <?php else: ?>
                                                <span class="<?php echo $f['variacion'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                    <i class="fa fa-<?php echo $f['variacion'] >= 0 ? 'arrow-up' : 'arrow-down'; ?>"></i>
                                                    <?php echo number_format(abs($f['variacion']), 1); ?>%
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr style="background:#f9f9f9; font-weight:bold;">
                                    <td>TOTAL</td>
                                    <td class="text-center"><?php echo $total_comp_act; ?></td>
                                    <td class="text-right">S/ <?php echo number_format($total_actual, 2); ?></td>
                                    <td class="text-right">S/ <?php echo number_format($total_anterior, 2); ?></td>
                                    <td class="text-center">
                                        <?php if($variacion_total === null): ?>
                                            -
                                        <?php else: ?>
                                            <span class="<?php echo $variacion_total >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                <?php echo number_format($variacion_total, 1); ?>%
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- TOP 5 CLIENTES -->
        <?php if(!empty($top_clientes)): ?>
        <div class="row" style="margin-bottom:5px !important;">
            <div class="col-md-12">
                <div class="panel panel-success reporte-panel">
                    <div class="panel-heading no-print"><strong><i class="fa fa-star"></i> Top 5 clientes — <?php echo $anio_actual; ?></strong></div>
                    <div class="panel-body" style="padding:0;">
                        <table class="table table-bordered table-striped tabla-reporte" style="margin:0;">
                            <thead>
                                <tr style="background:#dff0d8;">
                                    <th>#</th>
                                    <th>Cliente</th>
                                    <th class="text-center">N° Comprobantes</th>
                                    <th class="text-right">Total comprado</th>
                                    <th class="text-center">% del total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $n = 1; foreach($top_clientes as $tc): ?>
                                    <tr>
                                        <td><?php echo $n++; ?></td>
                                        <td><?php echo $tc->cliente; ?></td>
                                        <td class="text-center"><?php echo $tc->total_comprobantes; ?></td>
                                        <td class="text-right"><strong>S/ <?php echo number_format((float)$tc->total, 2); ?></strong></td>
                                        <td class="text-center">
                                            <?php echo $total_actual > 0 ? number_format(((float)$tc->total / $total_actual) * 100, 1) : 0; ?>%
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- PIE DE PÁGINA SOLO IMPRESIÓN -->
        <div class="print-only" style="margin-top:15px; font-size:10px; color:#888; text-align:center; border-top:1px solid #ccc; padding-top:6px;">
            Reporte generado el <?php echo $fecha_reporte; ?> — <?php echo !empty($empresa->nombre) ? $empresa->nombre : ''; ?>
        </div>

    </section>
</div>

<style>
/* ============================================================ */
/* ESTILOS DE PANTALLA */
/* ============================================================ */
.print-only { display: none; }

/* ============================================================ */
/* ESTILOS DE IMPRESIÓN — REPORTE APAISADO */
/* ============================================================ */
@media print {

    @page {
        size: A4 landscape;
        margin: 10mm;
    }

    .main-header, .sidebar, .content-header, .main-footer,
    .no-print, #panelFiltros, #cardsResumen,
    .box.box-primary,
    .control-sidebar, .navbar { display: none !important; }

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

    .print-only { display: block !important; }

    .reporte-panel {
        border: 1px solid #999 !important;
        box-shadow: none !important;
        margin-bottom: 8px !important;
    }

    .tabla-reporte {
        font-size: 10px;
    }
    .tabla-reporte th, .tabla-reporte td {
        padding: 4px 6px !important;
    }
    .tabla-reporte thead tr,
    .tabla-reporte tfoot tr {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }

    .tabla-resumen-print {
        width: 100%;
        border: none;
        margin-bottom: 10px;
    }
    .tabla-resumen-print td {
        border: none;
        font-size: 11px;
        padding: 4px 10px;
        text-align: center;
        width: 25%;
    }
}
</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 echo json_encode(array_column($filas, 'mes')); ?>;
    var actual   = <?php echo json_encode(array_map(function($f){ return round($f['total_actual'], 2); }, $filas)); ?>;
    var anterior = <?php echo json_encode(array_map(function($f){ return round($f['total_anterior'], 2); }, $filas)); ?>;

    var ctx = document.getElementById('graficoVentasPeriodo').getContext('2d');
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Ventas <?php echo $anio_actual; ?>',
                    data: actual,
                    backgroundColor: 'rgba(60, 141, 188, 0.8)',
                },
                {
                    label: 'Ventas <?php echo $anio_actual - 1; ?>',
                    data: anterior,
                    backgroundColor: 'rgba(210, 214, 222, 0.8)',
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': S/ ' + parseFloat(context.raw).toFixed(2);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) { return 'S/ ' + value.toLocaleString(); }
                    }
                }
            }
        }
    });

});
</script>
