<div class="content-wrapper">
    <section class="content-header">
        <h1>Cobranzas</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 Cobranzas</div>
                        <div style="font-size:11px; color:#555;">Emitido: <?php echo $fecha_reporte; ?></div>
                        <div style="font-size:11px; color:#555;">
                            <?php if($cliente_id): ?>
                                Cliente:
                                <?php
                                    foreach($clientes as $c) {
                                        if ($c->id == $cliente_id) { echo $c->razon_social; break; }
                                    }
                                ?>
                                &nbsp;|&nbsp;
                            <?php endif; ?>
                            <?php
                                $estados_label = array('0' => 'Pendiente', '1' => 'Cobrado', '2' => 'Parcial');
                                if ($estado_cobro !== null && $estado_cobro !== '') {
                                    echo 'Estado: ' . ($estados_label[$estado_cobro] ?? '') . ' &nbsp;|&nbsp; ';
                                }
                            ?>
                            Periodo: <?php echo date('d/m/Y', strtotime($fecha_desde ?? date('Y-m-01'))); ?>
                            al <?php echo date('d/m/Y', strtotime($fecha_hasta ?? date('Y-m-d'))); ?>
                        </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">
                    <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/cobranzas'); ?>">
                            <div class="row">
                                <div class="col-md-3 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>Estado cobro</label>
                                    <select name="estado_cobro" class="form-control">
                                        <option value="">Todos</option>
                                        <option value="0" <?php echo ($estado_cobro === '0') ? 'selected' : ''; ?>>Pendiente</option>
                                        <option value="2" <?php echo ($estado_cobro === '2') ? 'selected' : ''; ?>>Parcial</option>
                                        <option value="1" <?php echo ($estado_cobro === '1') ? 'selected' : ''; ?>>Cobrado</option>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group">
                                    <label>Fecha desde</label>
                                    <input type="date" name="fecha_desde" class="form-control"
                                           value="<?php echo $fecha_desde ?? date('Y-m-01'); ?>">
                                </div>
                                <div class="col-md-2 form-group">
                                    <label>Fecha hasta</label>
                                    <input type="date" name="fecha_hasta" class="form-control"
                                           value="<?php echo $fecha_hasta ?? date('Y-m-d'); ?>">
                                </div>
                                <div class="col-md-1 form-group" style="padding-top:25px;">
                                    <button type="submit" class="btn btn-primary btn-block">
                                        <i class="fa fa-search"></i>
                                    </button>
                                </div>
                                <div class="col-md-2 form-group" style="padding-top:25px;">
                                    <a href="<?php echo base_url('index.php/cobranzas/cobranzas'); ?>" class="btn btn-default">
                                        <i class="fa fa-refresh"></i>
                                    </a>
                                    <button type="button" onclick="window.print()" class="btn btn-default">
                                        <i class="fa fa-print"></i> Imprimir
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- CARDS RESUMEN -->
        <div class="row no-print" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-4">
                <div class="panel panel-danger">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Por cobrar</h4>
                        <h3 class="text-danger">S/ <?php echo number_format($total_saldo, 2); ?></h3>
                        <small><?php echo count($comprobantes); ?> comprobantes</small>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="panel panel-success">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Cobrado</h4>
                        <h3 class="text-success">S/ <?php echo number_format($total_cobrado, 2); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="panel panel-default">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Total facturado</h4>
                        <h3>S/ <?php echo number_format($total_saldo + $total_cobrado, 2); ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- RESUMEN PARA IMPRESIÓN -->
        <table class="print-only tabla-resumen-print">
            <tr>
                <td>
                    <strong>Por cobrar:</strong> S/ <?php echo number_format($total_saldo, 2); ?>
                    (<?php echo count($comprobantes); ?> comprobantes)
                </td>
                <td>
                    <strong>Cobrado:</strong> S/ <?php echo number_format($total_cobrado, 2); ?>
                </td>
                <td>
                    <strong>Total facturado:</strong> S/ <?php echo number_format($total_saldo + $total_cobrado, 2); ?>
                </td>
            </tr>
        </table>

        <!-- TABLA -->
        <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>Listado de comprobantes</strong></div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table id="tablaCobranzas" class="table table-bordered table-hover table-striped tabla-reporte">
                                <thead>
                                    <tr>
                                        <th>N°</th>
                                        <th>Tipo</th>
                                        <th>Serie-Número</th>
                                        <th>Cliente</th>
                                        <th>F. Emisión</th>
                                        <th>F. Vencimiento</th>
                                        <th>Moneda</th>
                                        <th class="text-right">Total</th>
                                        <th class="text-right">Cobrado</th>
                                        <th class="text-right">Saldo</th>
                                        <th class="text-center">Estado</th>
                                        <th style="width:60px;" class="no-print">Acc.</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($comprobantes as $item): ?>
                                        <?php
                                            $cobrado = (float)$item->pago_neto - (float)$item->saldo;
                                            $diasVencer = (int)$item->dias_para_vencer;

                                            if ($item->estado_cobro == 1) {
                                                $estadoLabel = '<span class="label label-success">COBRADO</span>';
                                                $rowClass = '';
                                            } elseif ($item->estado_cobro == 2) {
                                                $estadoLabel = '<span class="label label-info">PARCIAL</span>';
                                                $rowClass = '';
                                            } else {
                                                if (!empty($item->fecvencimiento) && $diasVencer < 0) {
                                                    $estadoLabel = '<span class="label label-danger">VENCIDO (' . abs($diasVencer) . 'd)</span>';
                                                    $rowClass = 'danger';
                                                } elseif (!empty($item->fecvencimiento) && $diasVencer <= 7) {
                                                    $estadoLabel = '<span class="label label-warning">VENCE EN ' . $diasVencer . 'd</span>';
                                                    $rowClass = 'warning';
                                                } else {
                                                    $estadoLabel = '<span class="label label-primary">PENDIENTE</span>';
                                                    $rowClass = '';
                                                }
                                            }
                                        ?>
                                        <tr class="<?php echo $rowClass; ?>">
                                            <td><?php echo $item->id; ?></td>
                                            <td><?php echo $item->tipo_comprobante; ?></td>
                                            <td><strong><?php echo $item->serie . '-' . $item->numero; ?></strong></td>
                                            <td>
                                                <?php echo $item->cliente; ?>
                                                <br><small class="text-muted"><?php echo $item->cliente_ruc; ?></small>
                                            </td>
                                            <td><?php echo date('d/m/Y', strtotime($item->fecha)); ?></td>
                                            <td>
                                                <?php echo !empty($item->fecvencimiento)
                                                    ? date('d/m/Y', strtotime($item->fecvencimiento))
                                                    : '-'; ?>
                                            </td>
                                            <td><?php echo $item->moneda; ?></td>
                                            <td class="text-right"><?php echo number_format((float)$item->pago_neto, 2); ?></td>
                                            <td class="text-right text-success"><?php echo number_format($cobrado, 2); ?></td>
                                            <td class="text-right">
                                                <?php if((float)$item->saldo > 0): ?>
                                                    <strong class="text-danger"><?php echo number_format((float)$item->saldo, 2); ?></strong>
                                                <?php else: ?>
                                                    <span class="text-success">0.00</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center"><?php echo $estadoLabel; ?></td>
                                            <td class="no-print">
                                                <a href="<?php echo base_url('index.php/cobranzas/cobranzas/ver/'.$item->id); ?>"
                                                   class="btn btn-info btn-xs" title="Ver">
                                                    <i class="fa fa-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr style="font-weight:bold; background:#f9f9f9;">
                                        <td colspan="7" class="text-right">Totales:</td>
                                        <td class="text-right">S/ <?php echo number_format($total_saldo + $total_cobrado, 2); ?></td>
                                        <td class="text-right text-success">S/ <?php echo number_format($total_cobrado, 2); ?></td>
                                        <td class="text-right text-danger">S/ <?php echo number_format($total_saldo, 2); ?></td>
                                        <td colspan="2" class="no-print"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 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, .control-sidebar, .navbar,
    .dataTables_filter, .dataTables_length, .dataTables_paginate, .dataTables_info {
        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;
    }

    tr.danger  td { background-color: #f9d6d5 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    tr.warning td { background-color: #fdf3d0 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }

    .label {
        border: 1px solid #999;
        background: #fff !important;
        color: #000 !important;
    }

    .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: 33.33%;
    }
}
</style>

<script>
window.addEventListener('load', function () {
    $('#tablaCobranzas').DataTable({
        language: {
            lengthMenu: "Mostrar _MENU_ registros", zeroRecords: "No se encontraron resultados",
            info: "Mostrando _START_ al _END_ de _TOTAL_", infoEmpty: "Sin registros",
            infoFiltered: "(filtrado de _MAX_ registros)", search: "Buscar:",
            paginate: { first: "Primero", last: "Último", next: "Siguiente", previous: "Anterior" }
        },
        pageLength: 25, order: [[0, 'desc']]
    });
});
</script>