<div class="content-wrapper">
    <section class="content-header">
        <h1>Reporte de Cuentas por Pagar</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 Cuentas por Pagar</div>
                        <div style="font-size:11px; color:#555;">Emitido: <?php echo $fecha_reporte; ?></div>
                        <div style="font-size:11px; color:#555;">
                            <?php if($proveedor_id): ?>
                                Proveedor:
                                <?php
                                    foreach($proveedores as $p) {
                                        if ($p->id == $proveedor_id) { echo $p->razon_social; break; }
                                    }
                                ?>
                                &nbsp;|&nbsp;
                            <?php endif; ?>
                            <?php
                                $estados_label = array('1' => 'Pendiente', '2' => 'Pagado');
                                if ($estado !== null && $estado !== '') {
                                    echo 'Estado: ' . ($estados_label[$estado] ?? '') . ' &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" 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/logistica/cuentas_pagar'); ?>">
                            <div class="row">
                                <div class="col-md-3 form-group">
                                    <label>Proveedor</label>
                                    <select name="proveedor_id" class="form-control">
                                        <option value="">Todos los proveedores</option>
                                        <?php foreach($proveedores as $item): ?>
                                            <option value="<?php echo $item->id; ?>"
                                                <?php echo ($proveedor_id == $item->id) ? 'selected' : ''; ?>>
                                                <?php echo $item->razon_social; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group">
                                    <label>Estado</label>
                                    <select name="estado" class="form-control">
                                        <option value="">Todos</option>
                                        <option value="1" <?php echo ($estado == '1') ? 'selected' : ''; ?>>Pendiente</option>
                                        <option value="2" <?php echo ($estado == '2') ? 'selected' : ''; ?>>Pagado</option>
                                    </select>
                                </div>
                                <div class="col-md-2 form-group">
                                    <label>F. Emisión 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>F. Emisión 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/logistica/cuentas_pagar'); ?>" 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 -->
        <?php if(!empty($agrupado)): ?>
        <div class="row no-print" id="cardsResumen" style="margin-bottom:5px !important; height: 45px;">
            <div class="col-md-4">
                <div class="panel panel-default">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Total deuda</h4>
                        <h3>S/ <?php echo number_format($total_general_deuda, 2); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="panel panel-success">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Total pagado</h4>
                        <h3 class="text-success">S/ <?php echo number_format($total_general_pagado, 2); ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="panel panel-danger">
                    <div class="panel-body text-center">
                        <h4 class="text-muted">Saldo pendiente</h4>
                        <h3 class="text-danger">S/ <?php echo number_format($total_general_saldo, 2); ?></h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- RESUMEN PARA IMPRESIÓN -->
        <table class="print-only tabla-resumen-print">
            <tr>
                <td>
                    <strong>Total deuda:</strong> S/ <?php echo number_format($total_general_deuda, 2); ?>
                </td>
                <td>
                    <strong>Total pagado:</strong> S/ <?php echo number_format($total_general_pagado, 2); ?>
                </td>
                <td>
                    <strong>Saldo pendiente:</strong> S/ <?php echo number_format($total_general_saldo, 2); ?>
                </td>
            </tr>
        </table>

        <!-- TABLAS POR PROVEEDOR -->
        <?php foreach($agrupado as $proveedor => $data_prov): ?>
        <div class="row" style="margin-bottom:5px !important;">
            <div class="col-md-12">
                <div class="panel panel-default reporte-panel">
                    <div class="panel-heading" style="background:#f4f4f4;">
                        <strong><i class="fa fa-building-o"></i> <?php echo strtoupper($proveedor); ?></strong>
                        <span class="pull-right">
                            Saldo: <strong class="text-danger">S/ <?php echo number_format($data_prov['total_saldo'], 2); ?></strong>
                        </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>Tipo</th>
                                    <th>Serie-Número</th>
                                    <th>F. Emisión</th>
                                    <th>F. Vencimiento</th>
                                    <th>Condición</th>
                                    <th class="text-right">Total</th>
                                    <th class="text-right">Pagado</th>
                                    <th class="text-right">Saldo</th>
                                    <th class="text-center">Estado</th>
                                    <th style="width:45px;" class="no-print">Acc.</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($data_prov['items'] as $item): ?>
                                    <?php
                                        $tipos = array('F'=>'Factura','B'=>'Boleta','RH'=>'R.Hon.','O'=>'Otro');
                                        $tipoLabel = isset($tipos[$item->tipo_comprobante]) ? $tipos[$item->tipo_comprobante] : $item->tipo_comprobante;
                                        $pagado = (float)$item->total - (float)$item->saldo;

                                        if ($item->estado == 2) {
                                            $estadoLabel = '<span class="label label-success">PAGADO</span>';
                                            $rowClass = '';
                                        } elseif ($item->estado == 1) {
                                            $diasVencer = (int)$item->dias_para_vencer;
                                            if (!empty($item->fecha_vencimiento) && $diasVencer < 0) {
                                                $estadoLabel = '<span class="label label-danger">VENCIDO (' . abs($diasVencer) . 'd)</span>';
                                                $rowClass = 'danger';
                                            } elseif (!empty($item->fecha_vencimiento) && $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 = '';
                                            }
                                        } else {
                                            $estadoLabel = '<span class="label label-default">ANULADO</span>';
                                            $rowClass = '';
                                        }
                                    ?>
                                    <tr class="<?php echo $rowClass; ?>">
                                        <td><?php echo $tipoLabel; ?></td>
                                        <td><strong><?php echo $item->serie . '-' . $item->numero; ?></strong></td>
                                        <td><?php echo date('d/m/Y', strtotime($item->fecha_emision)); ?></td>
                                        <td>
                                            <?php echo !empty($item->fecha_vencimiento)
                                                ? date('d/m/Y', strtotime($item->fecha_vencimiento))
                                                : '-'; ?>
                                        </td>
                                        <td><?php echo $item->forma_pago ?? '-'; ?></td>
                                        <td class="text-right"><?php echo number_format((float)$item->total, 2); ?></td>
                                        <td class="text-right text-success"><?php echo number_format($pagado, 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/logistica/comprobante_proveedor/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="background:#f9f9f9; font-weight:bold;">
                                    <td colspan="5" class="text-right">Subtotal:</td>
                                    <td class="text-right"><?php echo number_format($data_prov['total_deuda'], 2); ?></td>
                                    <td class="text-right text-success"><?php echo number_format($data_prov['total_pagado'], 2); ?></td>
                                    <td class="text-right text-danger"><?php echo number_format($data_prov['total_saldo'], 2); ?></td>
                                    <td colspan="2" class="no-print"></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- TOTAL GENERAL -->
        <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-body">
                        <div class="row">
                            <div class="col-md-4 text-right"><h4><strong>TOTAL GENERAL</strong></h4></div>
                            <div class="col-md-2 text-right">
                                <small class="text-muted">Deuda total</small><br>
                                <strong>S/ <?php echo number_format($total_general_deuda, 2); ?></strong>
                            </div>
                            <div class="col-md-2 text-right">
                                <small class="text-muted">Pagado</small><br>
                                <strong class="text-success">S/ <?php echo number_format($total_general_pagado, 2); ?></strong>
                            </div>
                            <div class="col-md-2 text-right">
                                <small class="text-muted">Saldo pendiente</small><br>
                                <strong class="text-danger">S/ <?php echo number_format($total_general_saldo, 2); ?></strong>
                            </div>
                            <div class="col-md-2"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TOTAL GENERAL — IMPRESIÓN -->
        <table class="print-only tabla-resumen-print" style="border-top:2px solid #333; margin-top:8px;">
            <tr>
                <td style="text-align:right; font-weight:bold;">TOTAL GENERAL:</td>
                <td><strong>Deuda:</strong> S/ <?php echo number_format($total_general_deuda, 2); ?></td>
                <td><strong>Pagado:</strong> S/ <?php echo number_format($total_general_pagado, 2); ?></td>
                <td><strong>Saldo:</strong> S/ <?php echo number_format($total_general_saldo, 2); ?></td>
            </tr>
        </table>

        <?php else: ?>
        <div class="row">
            <div class="col-md-12">
                <div class="alert alert-info">
                    <i class="fa fa-info-circle"></i>
                    No se encontraron comprobantes para los filtros seleccionados.
                </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;
        page-break-inside: avoid;
        margin-bottom: 8px !important;
    }

    .reporte-panel .panel-heading {
        background: #eee !important;
        color: #000 !important;
        font-size: 12px;
        padding: 5px 10px;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }

    .tabla-reporte {
        font-size: 10px;
    }
    .tabla-reporte th, .tabla-reporte td {
        padding: 3px 5px !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: 25%;
    }
}
</style>