<?php
    include('ajax/is_logged.php');
    /* Connect To Database*/
    require_once ("config/db.php");
    require_once ("config/conexion.php");
    include("modal/estado_cuenta.php");
    
    include 'ajax/pagination.php'; 

    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 10; 
    $adjacents  = 4; 
    $offset = ($page - 1) * $per_page;

    // Conteo optimizado
    $count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM `compras` WHERE `abono` < `total`");
    $row = mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './reportes.php';

    // Consulta con JOIN para obtener nombres de proveedores de una vez
    $sql = "SELECT c.*, p.nombre_proveedor 
            FROM compras c 
            LEFT JOIN proveedores p ON c.proveedor = p.id_pro 
            WHERE c.abono < c.total 
            ORDER BY c.fecha DESC 
            LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
?>

<div class="panel panel-info" style="border-top: 3px solid #f39c12;">
    <div class="panel-heading" style="background: #fff; color: #444;">
        <div class="btn-group pull-right">
            <a href="imp_ctas_pagar.php" target="_blank" class="btn btn-danger btn-sm">
                <span class="glyphicon glyphicon-print"></span> DESCARGAR PDF
            </a>
        </div>
        <h4><i class='glyphicon glyphicon-list-alt'></i> Cuentas por Pagar</h4>
    </div>
    
    <div class="panel-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr class="warning">
                        <th>#</th>
                        <th>FECHA</th>
                        <th>FACTURA</th>
                        <th>PROVEEDOR</th>
                        <th class="text-right">MONTO</th>
                        <th class="text-right">ABONO</th>
                        <th class="text-right">POR PAGAR</th>
                        <th class="text-center">ACCIONES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($numrows > 0) {
                        $item = $offset + 1;
                        $total_general_pendiente = 0;
                        
                        while ($dato = mysqli_fetch_array($query)) {
                            $id_compra = $dato['id_compra'];
                            $fecha = date('d/m/Y', strtotime($dato['fecha']));
                            $num = $dato['numero_fact'];
                            $nombre_proveedor = $dato['nombre_proveedor'];
                            $pro = $dato['total'];
                            $abono = $dato['abono'];
                            $pagar = $dato['por_pagar'];
                            
                            $total_general_pendiente += $pagar;
                    ?>
                        <tr>
                            <td><?php echo $item++; ?></td>
                            <td><?php echo $fecha; ?></td>
                            <td><span class="label label-default"><?php echo $num; ?></span></td>
                            <td><strong><?php echo $nombre_proveedor; ?></strong></td>
                            <td class="text-right">$ <?php echo number_format($pro, 2); ?></td>
                            <td class="text-right text-success">$ <?php echo number_format($abono, 2); ?></td>
                            <td class="text-right text-danger" style="font-weight:bold;">$ <?php echo number_format($pagar, 2); ?></td>
                            <td class="text-center">
                                <?php if(in_array($_SESSION['rol'], ["gerencia", "pagos", "compras"]) && $pagar > 0) { ?>
                                    <div class="btn-group">
                                        <a href="#" class='btn btn-default btn-xs' 
                                           data-id="<?php echo $num;?>" 
                                           data-id2="<?php echo $pagar;?>" 
                                           data-id3="<?php echo $abono;?>" 
                                           data-toggle="modal" 
                                           data-target="#estado_cuenta" 
                                           title="Ver detalle de abonos">
                                           <i class="glyphicon glyphicon-stats"></i>
                                        </a>
                                        <a href="procesar_pago.php?id_compra=<?php echo $id_compra;?>" 
                                           class='btn btn-warning btn-xs' 
                                           title='Procesar Pago'>
                                           <i class="glyphicon glyphicon-credit-card"></i>
                                        </a>
                                    </div>
                                <?php } ?>
                            </td>
                        </tr>
                    <?php
                        }
                    ?>
                    <tr class="active">
                        <td colspan="6" class="text-right"><strong>TOTAL POR PAGAR (ESTA PÁGINA)</strong></td>
                        <td class="text-right"><h4 style="margin:0; font-weight:bold;" class="text-danger">$ <?php echo number_format($total_general_pendiente, 2); ?></h4></td>
                        <td></td>
                    </tr>
                    <?php
                    } else {
                    ?>
                        <tr>
                            <td colspan="8" class="text-center">No se encontraron cuentas pendientes por pagar.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        
        <div class="text-right">
            <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
        </div>
    </div>
</div>

<script>
$(document).ready(function (e) {
    $('#estado_cuenta').on('show.bs.modal', function(e) {    
        var id = $(e.relatedTarget).data().id;
        var id2 = $(e.relatedTarget).data().id2;
        var id3 = $(e.relatedTarget).data().id3;
        
        $(".outer_div2").html('<div class="text-center"><img src="./img/ajax-loader.gif"> Cargando detalle...</div>');
        
        $.ajax({
            url: 'ajax/detalle_abono.php?id=' + id,
            success: function(data) {
                $(".outer_div2").html(data).fadeIn('slow');
            }
        });
        
        $(".fac").html(id);
        $(".por_pagar").html(id2);
        $(".abonos").html(id3);
        $(e.currentTarget).find('#fac').val(id);
    });
});
</script>