<?php
session_start();
require_once('../conexion.php');
require_once('../include/sesiones.php'); 

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
    $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
    include '../include/pagination.php'; //include pagination file
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 20; //how much records you want to show
    $adjacents  = 4; //gap between pages after number of adjacents
    $offset = ($page - 1) * $per_page;
    if($q==0){
    $count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM ventas where ven_estado='sin pagar' and empresa='$empresa' and sucursal='$sucursal'");
    $row= mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './P_pos.php';
    $sql="SELECT *, DATE_FORMAT(`ven_fecha`,'%d-%m-%Y') as ven_fecha FROM ventas where ven_estado='sin pagar' and empresa='$empresa' and sucursal='$sucursal' order by ven_id desc LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
    }
    else
    {
    $count_query=mysqli_query($con, "SELECT count(*) AS numrows FROM ventas where Cliente_clie_id='$q' and ven_estado='sin pagar' and  empresa='$empresa' and sucursal='$sucursal'");
    $row= mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './P_pos.php';
    $sql="SELECT *, DATE_FORMAT(`ven_fecha`,'%d-%m-%Y') as ven_fecha FROM ventas where Cliente_clie_id='$q' and ven_estado='sin pagar'   and  empresa='$empresa' and sucursal='$sucursal'  order by ven_id desc LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
    }
    if ($numrows>0){
?>
<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th width="9%">FACT N°</th>
            <th width="10%">FECHA</th>
            <th>CLIENTE</th>
            <th width="5%">DIAS</th>
            <th width="10%">TOTAL</th>
            <th width="10%">ABONO</th>
            <th width="10%">SALDO</th>
            <th width="15%"></th>
        </tr>
    </thead>
    <tbody  class="buscar">
<?php 
$sumador_abono=0;  
$sumador_saldo=0; 
$sumador_total_fac=0;  
$vencido=0;
while ($reg=mysqli_fetch_array($query))
{  
    $id=$reg['ven_id'];
    $ven_id=$reg['ven_id'];
    $ven_n_venta=$reg['ven_n_venta'];
    $ven_fecha=$reg['ven_fecha'];
    $ven_dias=$reg['ven_dias'];
    $usuario=$reg['usuario'];
    $ven_nombre=$reg['ven_nombre'];
    $ven_forma_de_pago=$reg['ven_forma_de_pago'];

    $venci=0;

    
    $sumador_combo=0;
    $sumador_total=0;

    $neto=0;
    $total_descuento=0;
    $total_iva=0;
    $total_retencion=0;
    $sumador_articulos=0;


    $ret=mysqli_query($con, "SELECT * FROM retencion_venta where ventas_ven_id='$ven_id' ") or die(mysqli_error($con)); 
    $rets=mysqli_fetch_array($ret);
    $ret_porcentaje=!empty($rets['porcentaje']);

    include('../include/total_venta.php');
    $total_retencion+=($neto+$sumador_combo-$total_descuento)*($ret_porcentaje/100);
    $sumador_total=$sumador_articulos+$sumador_combo-$total_retencion;

    $sql1=mysqli_query($con, "SELECT sum(veab_abono) as total from venta_abonos where ventas_ven_id='$ven_id' ");
    $sql1=mysqli_fetch_array($sql1);
    $total_abono=$sql1['total'];

    $devo_total=0;
    $sql1=mysqli_query($con, "SELECT * from devolucion where empresa='$empresa' and ventas_ven_id='$ven_id'");
    while ($row=mysqli_fetch_array($sql1))
    {
        $dev_id=$row["dev_id"];
        $dev_referencia=$row["dev_referencia"];
        $dev_cantidad=$row['dev_cantidad'];
        $dev_precio=$row['dev_precio'];
        $devo_total+=$dev_precio; 
    }

    $saldo=$sumador_total-$total_abono;

?>
            <tr>
                <td><?php echo $reg['ven_prefijo']; ?><?php  echo $ven_n_venta; ?></td>
                <td><?php echo $ven_fecha; ?></td>
                <td><?php echo $ven_nombre; ?></td>
                <td>
                <?php 
                $vence = strtotime($ven_fecha."+ ".$ven_dias." days");
                date("Y-m-d",$vence) . "\n";
                $fecha=date('Y-m-d ');

                $hasta=date("Y-m-d",$vence) . "\n";
                $hoy=$fecha;
                $dias = (strtotime($hasta)-strtotime($hoy))/86400;
                $dias = abs($dias);

                if($hasta >= $hoy){
                echo '-'; echo $dias = floor($dias);
                }
                else{
                echo '+'; echo $dias = floor($dias);
                $vencido+=$saldo;
                }
                  $venci+=$vencido;
                ?>
                </td>
                <td><span class="pull-right"><?php echo number_format($sumador_total,0); ?></span></td>
                <td><span class="pull-right"><?php  echo number_format($total_abono,0); ?></span></td>
                <td><span class="pull-right"><?php  
               
                if($ven_forma_de_pago=="Credito")
                  { 
                    $saldo_t=$sumador_total-$total_abono-$devo_total;
                    if ($saldo_t<=0) 
                    {
                      echo $saldo='0';
                    }
                    else
                    {
                      $saldo=$saldo_t;
                      echo number_format($saldo,0); 
                    }
                  }
                  else 
                  {
                    echo '';
                  }
                  ?></span></td>
                <td>
                    <a href="#abonos<?php echo $reg['ven_id']; ?>" class="btn btn-xs btn-default" data-toggle="modal">Abonos</a>
                    <?php include ('../php_ventas/historial_abono.php'); ?>
                    <a href="#" data-id="<?php echo $id;?>" title="Ver Detalle" class="btn btn-xs btn-info btn_detalle" data-toggle="modal" > 
                    <i class="btn-icon-only icon-eye-open"></i></a>
                    <?php include ('../include/boton_venta2.php'); ?>
                </td>
            </tr> 
            <?php 
            $sumador_saldo+=$saldo;
            $sumador_abono+=$total_abono;
            $sumador_total_fac+=$sumador_total;

             } ?>
            <tr>
                <td colspan=4></td>
                <td><span class="pull-right"><?php echo number_format($sumador_total_fac,0);?></span></td>
                <td><span class="pull-right"><?php echo number_format($sumador_abono,0);?></span></td>
                <td><span class="pull-right"><strong><?php echo number_format($sumador_saldo,0); ?></strong></span></td>
                <td></td>
            </tr> 
            <tr>
                <td colspan=8><span class="pull-right">
                    <?php echo paginate($reload, $page, $total_pages, $adjacents); ?></span>
                </td>
            </tr>
        </table>
<?php } } ?>
<script>
    $(".btn_detalle").click(function(){
        id = $(this).data("id");
        $.get("./php_pos/forms_detalle.php","id="+id,function(data){
            $("#form-detalle").html(data);
        });
        $('#detalle').modal('show');
    });
</script>