<?php
include('is_logged.php');
require_once ("../config/db.php");
require_once ("../config/conexion.php");

// 1. Obtener Tasa
$con_tasa = mysqli_query($con, "SELECT * FROM tasa WHERE id_tasa='1'");
$dato_tasa = mysqli_fetch_array($con_tasa);
$tasa_actual = $dato_tasa['tasa'];

// 2. Parámetros
$dato = mysqli_real_escape_string($con, $_POST['dato']); 
$tienda = $_SESSION['estado'];
$credito = "SI";

// 3. Consulta con JOIN (Igual a la tuya)
$sTable = "facturas f INNER JOIN clientes c ON f.id_cliente = c.id_cliente";
$sWhere = "WHERE f.estado_factura='1' AND f.credito='$credito'";

if (!empty($tienda)) {
    $sWhere .= " AND f.almacen='$tienda'";
}

if (!empty($dato)) {
    $sWhere .= " AND c.nombre_cliente LIKE '%$dato%'";
}

$sWhere .= " ORDER BY f.id_factura ASC";

// 4. Paginación
include 'pagination.php';
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
$per_page = 30;
$adjacents = 4;
$offset = ($page - 1) * $per_page;

$count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable $sWhere");
$row = mysqli_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows / $per_page);
$reload = './reportes.php';

$sql = "SELECT f.*, c.nombre_cliente FROM $sTable $sWhere LIMIT $offset,$per_page";
$query = mysqli_query($con, $sql);
?>

<div class="table-responsive">
    <table class="table table-striped table-bordered">
        <thead>
            <tr class="info">
                <th>#</th>
                <th>TIENDA</th>
                <th>RAZON SOCIAL</th>
                <th>FECHA</th>
                <th>FACTURA</th>
                <th class="text-center">TOTAL / ABONADO</th>
                <th>ESTADO</th>
                <th class="text-right">ACCIONES</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $item = $offset;
        $total_por_cobrar = 0;
        
        if ($numrows > 0) {
            while ($row = mysqli_fetch_array($query)) {
                $id_factura = $row['id_factura'];
                $nom_cliente = $row['nombre_cliente'];
                $almacen = $row['almacen'];
                $fecha = date("d/m/Y", strtotime($row['fecha_factura']));
                $num = $row['numero_factura'];
                $total_v = $row['total_venta'];
                $abonado = $row['abono'];
                
                $condicion_factura = $row['condiciones'];
                $estado_factura = $row['estado_factura'];
                $cre = $row['credito'];

                $item++;
                
                // Lógica de etiquetas (Se mantiene igual)
                if ($abonado == 0) {
                    $text_estado = "Sin Abonar"; $label_class = 'label-danger';
                } else {
                    $text_estado = "Abonando"; $label_class = 'label-warning';
                }
        ?>
            <tr>
                <td><?php echo $item; ?></td>
                <td><?php echo $almacen; ?></td>
                <td><?php echo $nom_cliente; ?></td>
                <td><?php echo $fecha; ?></td>
                <td><?php echo $num; ?></td>
                <td class="text-center">
                    <strong>$<?php echo number_format($total_v, 2, ",", "."); ?></strong> / 
                    <span class="text-success">$<?php echo number_format($abonado, 2, ",", "."); ?></span>
                </td>
                <td><span class="label <?php echo $label_class; ?>"><?php echo $text_estado; ?></span></td>
                <td class="text-right">
                    <?php if(in_array($_SESSION['rol'], ['ventas', 'pagos', 'gerencia', 'supervisor'])) { ?>
                        <a href="procesar_cobro.php?id_factura=<?php echo $id_factura; ?>" class="btn btn-info btn-xs">
                            PROCESAR PAGO
                        </a>
                    <?php } ?>
                </td>
            </tr>
        <?php
                // Acumulamos el saldo real pendiente (Total - Abono)
                $total_por_cobrar += ($total_v - $abonado);
            }
        ?>
            <tr class="warning">
                <td colspan="5" class="text-right"><strong>TOTAL GENERAL PENDIENTE:</strong></td>
                <td class="text-center"><strong>$<?php echo number_format($total_por_cobrar, 2, ",", "."); ?></strong></td>
                <td colspan="2"></td>
            </tr>
            <tr>
                <td colspan="8">
                    <span class="pull-right">
                        <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
                    </span>
                </td>
            </tr>
        <?php 
        } else { 
            echo "<tr><td colspan='8' class='text-center'>No hay cuentas por cobrar registradas.</td></tr>";
        } 
        ?>
        </tbody>
    </table>
</div>