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

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

$desde = $_POST['desde'];
$hasta = $_POST['hasta'];
$dato = mysqli_real_escape_string($con, $_POST['dato']); 
$cond = "Liquidar";

// 2. Construcción SQL flexible
$sWhere = " WHERE condiciones != '$cond'";
if (!empty($desde) && !empty($hasta)) { $sWhere .= " AND fecha_factura BETWEEN '$desde' AND '$hasta'"; }
if (!empty($dato)) { $sWhere .= " AND id_cliente IN (SELECT id_cliente FROM clientes WHERE nombre_cliente LIKE '%$dato%')"; }
$sWhere .= " ORDER BY id_factura DESC";

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

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

// 4. Totales
$sql_total = mysqli_query($con, "SELECT SUM(total_venta) as total FROM facturas $sWhere");
$res_total = mysqli_fetch_array($sql_total);
$monto_total = $res_total['total'];

// 5. Consulta Principal
$sql = "SELECT * FROM facturas $sWhere LIMIT $offset,$per_page";
$query = mysqli_query($con, $sql);
?>

<div class="alert alert-warning text-center" style="border: 1px solid #faebcc; color: #8a6d3b;">
    <span style="font-size: 1.1em;">TOTAL DONACIONES:</span><br>
    <strong style="font-size: 1.5em;">$ <?php echo number_format($monto_total, 2, ",", "."); ?></strong>
    <span style="margin: 0 10px;">|</span>
    <strong style="font-size: 1.5em;">BsD <?php echo number_format($monto_total * $tasa_actual, 2, ",", "."); ?></strong>
</div>

<div class="text-right" style="margin-bottom: 10px;">
    <a href="imp_donaciones.php?dato=<?php echo $dato; ?>&desde=<?php echo $desde; ?>&hasta=<?php echo $hasta; ?>" target="_blank" class="btn btn-default btn-sm">
        <i class="glyphicon glyphicon-print"></i> Imprimir Reporte
    </a>
</div>

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed" style="background: white;">
        <thead>
            <tr class="info">
                <th>#</th>
                <th>Cliente</th>
                <th>Fecha</th>
                <th>Factura</th>
                <th class="text-right">Monto ($)</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $item = $offset + 1;
        if ($numrows > 0) {
            while ($row = mysqli_fetch_array($query)) {
                $id_cli = $row['id_cliente'];
                $res_cli = mysqli_query($con, "SELECT nombre_cliente FROM clientes WHERE id_cliente='$id_cli'");
                $f_cli = mysqli_fetch_array($res_cli);
        ?>
            <tr>
                <td><?php echo $item++; ?></td>
                <td><?php echo $f_cli['nombre_cliente']; ?></td>
                <td><?php echo date("d-m-Y", strtotime($row['fecha_factura'])); ?></td>
                <td><?php echo $row['numero_factura']; ?></td>
                <td class="text-right"><strong><?php echo number_format($row['total_venta'], 2, ",", "."); ?></strong></td>
            </tr>
        <?php } ?>
        <?php } else { ?>
            <tr><td colspan="5" class="text-center">Sin resultados</td></tr>
        <?php } ?>
        </tbody>
    </table>
</div>

<div class="text-center">
    <?php echo paginate('./reportes.php', $page, $total_pages, $adjacents); ?>
</div>