<div class="content-wrapper">
    <section class="content-header">
        <h1>Antigüedad de Saldos por Cobrar</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;">Antigüedad de Saldos por Cobrar</div>
                        <div style="font-size:11px; color:#555;">Emitido: <?php echo $fecha_reporte; ?></div>
                        <div style="font-size:11px; color:#555;">
                            Fecha de corte: <?php echo date('d/m/Y', strtotime($fecha_corte)); ?>
                            <?php if($cliente_id): ?>
                                &nbsp;|&nbsp; Cliente:
                                <?php
                                    foreach($clientes as $c) {
                                        if ($c->id == $cliente_id) { echo $c->razon_social; break; }
                                    }
                                ?>
                            <?php endif; ?>
                        </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/cobranzas/antiguedad_saldos'); ?>">
                            <div class="row">
                                <div class="col-md-4 form-group">
                                    <label>Cliente</label>
                                    <select name="cliente_id" class="form-control">
                                        <option value="">Todos los clientes</option>
                                        <?php foreach($clientes as $item): ?>
                                            <option value="<?php echo $item->id; ?>"
                                                <?php echo ($cliente_id == $item->id) ? 'selected' : ''; ?>>
                                                <?php echo $item->razon_social; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group">
                                    <label>Fecha de corte</label>
                                    <input type="date" name="fecha_corte" class="form-control"
                                           value="<?php echo $fecha_corte; ?>">
                                </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> Filtrar
                                    </button>
                                    <a href="<?php echo base_url('index.php/cobranzas/antiguedad_saldos'); ?>" class="btn btn-default">
                                        <i class="fa fa-refresh"></i>
                                    </a>
                                </div>
                                <div class="col-md-4 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 POR BUCKET -->
        <div class="row no-print" id="cardsResumen" style="margin-bottom:5px !important; height: 45px;">
            <?php
                $colores = array(
                    'corriente' => 'success',
                    'b1_30'     => 'info',
                    'b31_60'    => 'warning',
                    'b61_90'    => 'warning',
                    'b90_mas'   => 'danger',
                );
            ?>
            <?php foreach($buckets_def as $key => $label): ?>
                <div class="col-md-2" style="width:20%;">
                    <div class="panel panel-<?php echo $colores[$key]; ?>">
                        <div class="panel-body text-center" style="padding:10px 5px;">
                            <h5 class="text-muted" style="margin:0 0 5px; font-size:11px;"><?php echo $label; ?></h5>
                            <h4 style="margin:0;">S/ <?php echo number_format($totales_buckets[$key], 2); ?></h4>
                            <small class="text-muted">
                                <?php echo $total_general > 0 ? number_format($totales_buckets[$key] / $total_general * 100, 1) : 0; ?>%
                            </small>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- RESUMEN PARA IMPRESIÓN -->
        <table class="print-only tabla-resumen-print">
            <tr>
                <?php foreach($buckets_def as $key => $label): ?>
                    <td>
                        <strong><?php echo $label; ?>:</strong><br>
                        S/ <?php echo number_format($totales_buckets[$key], 2); ?>
                        (<?php echo $total_general > 0 ? number_format($totales_buckets[$key] / $total_general * 100, 1) : 0; ?>%)
                    </td>
                <?php endforeach; ?>
            </tr>
        </table>

        <!-- TABLA PRINCIPAL: CLIENTES x BUCKETS -->
        <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>Saldos por cliente</strong>
                        <span class="badge pull-right"><?php echo count($agrupado); ?> clientes</span>
                    </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>Cliente</th>
                                    <?php foreach($buckets_def as $key => $label): ?>
                                        <th class="text-right"><?php echo $label; ?></th>
                                    <?php endforeach; ?>
                                    <th class="text-right">Total</th>
                                    <th class="text-center">% del total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($agrupado)): ?>
                                    <tr>
                                        <td colspan="<?php echo count($buckets_def) + 3; ?>" class="text-center text-muted">
                                            No hay saldos pendientes a la fecha de corte seleccionada.
                                        </td>
                                    </tr>
                                <?php endif; ?>
                                <?php foreach($agrupado as $cli): ?>
                                    <tr>
                                        <td>
                                            <?php echo $cli['cliente']; ?>
                                            <br><small class="text-muted"><?php echo $cli['cliente_ruc']; ?></small>
                                        </td>
                                        <?php foreach($buckets_def as $key => $label): ?>
                                            <td class="text-right <?php echo ($cli['buckets'][$key] > 0 && $key != 'corriente') ? ($key=='b90_mas' ? 'text-danger' : 'text-warning') : ''; ?>">
                                                <?php echo $cli['buckets'][$key] > 0 ? number_format($cli['buckets'][$key], 2) : '-'; ?>
                                            </td>
                                        <?php endforeach; ?>
                                        <td class="text-right"><strong><?php echo number_format($cli['total'], 2); ?></strong></td>
                                        <td class="text-center">
                                            <?php echo $total_general > 0 ? number_format($cli['total'] / $total_general * 100, 1) : 0; ?>%
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <?php if(!empty($agrupado)): ?>
                            <tfoot>
                                <tr style="background:#f9f9f9; font-weight:bold;">
                                    <td class="text-right">TOTAL GENERAL:</td>
                                    <?php foreach($buckets_def as $key => $label): ?>
                                        <td class="text-right"><?php echo number_format($totales_buckets[$key], 2); ?></td>
                                    <?php endforeach; ?>
                                    <td class="text-right">S/ <?php echo number_format($total_general, 2); ?></td>
                                    <td class="text-center">100%</td>
                                </tr>
                            </tfoot>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- DETALLE POR CLIENTE (solo si filtró un cliente específico) -->
        <?php if($cliente_id && !empty($agrupado)): ?>
            <?php $cli = reset($agrupado); ?>
            <div class="row" style="margin-bottom:5px !important;">
                <div class="col-md-12">
                    <div class="panel panel-info reporte-panel">
                        <div class="panel-heading no-print"><strong>Detalle de comprobantes — <?php echo $cli['cliente']; ?></strong></div>
                        <div class="panel-body" style="padding:0;">
                            <table class="table table-bordered table-hover tabla-reporte" style="margin:0;">
                                <thead>
                                    <tr style="background:#d9edf7;">
                                        <th>Comprobante</th>
                                        <th>F. Emisión</th>
                                        <th>F. Vencimiento</th>
                                        <th class="text-center">Días vencido</th>
                                        <th>Rango</th>
                                        <th>Moneda</th>
                                        <th class="text-right">Saldo</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($cli['items'] as $it): ?>
                                        <tr>
                                            <td>
                                                <?php echo $it['tipo_comprobante']; ?>
                                                <strong><?php echo ' ' . $it['serie'] . '-' . $it['numero']; ?></strong>
                                            </td>
                                            <td><?php echo date('d/m/Y', strtotime($it['fecha'])); ?></td>
                                            <td><?php echo !empty($it['fecvencimiento']) ? date('d/m/Y', strtotime($it['fecvencimiento'])) : '-'; ?></td>
                                            <td class="text-center"><?php echo $it['dias_vencido'] !== null ? $it['dias_vencido'] : '-'; ?></td>
                                            <td><?php echo $buckets_def[$it['bucket']]; ?></td>
                                            <td><?php echo $it['moneda']; ?></td>
                                            <td class="text-right"><strong><?php echo number_format($it['saldo'], 2); ?></strong></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,
    .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: 9px;
    }
    .tabla-reporte th, .tabla-reporte td {
        padding: 3px 4px !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: 10px;
        padding: 4px 8px;
        text-align: center;
        width: 20%;
    }
}
</style>
