<?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)));
    $tipo=mysqli_real_escape_string($con,(strip_tags($_REQUEST['tipo'], ENT_QUOTES)));
    include '../include/pagination.php'; 
    $page=(isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page=20;
    $adjacents=4; 
    $offset=($page - 1) * $per_page;

    if($tipo=='remision')
    {

        $count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM ventas where (ven_tipo='remision' or ven_tipo='pos') and empresa='$empresa' and apertura='$apertura' and (ven_n_venta like '%$q%' OR ven_nombre like '%$q%' OR ven_cc like '%$q%' OR ven_guia like '%$q%')");
        $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_tipo='remision' or ven_tipo='pos') and empresa='$empresa' and apertura='$apertura' and (ven_n_venta like '%$q%' OR ven_nombre like '%$q%' OR ven_cc like '%$q%' OR ven_guia like '%$q%') order by ven_id desc LIMIT $offset,$per_page";
    }
    else
    {
        $count_query=mysqli_query($con,"SELECT count(*) AS numrows FROM ventas where (ven_tipo='pos electronico' or ven_tipo='electronica') and empresa='$empresa' and apertura='$apertura' and (ven_n_venta like '%$q%' OR ven_nombre like '%$q%' OR ven_cc like '%$q%' OR ven_guia like '%$q%')");
        $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_tipo='pos electronico' or ven_tipo='electronica') and empresa='$empresa' and apertura='$apertura' and (ven_n_venta like '%$q%' OR ven_nombre like '%$q%' OR ven_cc like '%$q%' OR ven_guia like '%$q%') order by ven_id desc LIMIT $offset,$per_page";
    }
    
    $query = mysqli_query($con, $sql);
    if ($numrows>0)
    {
       
?>
<div class="table-responsive">
    <table class="table table-bordered table-hover table-striped" id="datos" style="font-size: 9pt;">
        <thead>
            <tr>
                <td></td>
                <th>N°</th>
                <th width="10%">FECHA</th>
                <th>CLIENTE</th>
                <th>F.PAGO</th>
                <th>TOTAL</th>
                <th>ABONOS</th>
                <th>NOTAS CREDITO</th>
                <th>SALDO</th>
                <th width="15%"></th>
            </tr>
        </thead>
        <tbody  class="buscar">
        <?php 
        while ($reg=mysqli_fetch_array($query))
            {
                $id=$reg["ven_id"];
                $ven_id=$reg['ven_id'];
                $ven_estado=$reg['ven_estado'];
                $estado_dian=$reg['estado_dian'];
                $clie_id=$reg['Cliente_clie_id'];
                $ven_forma_de_pago=$reg['ven_forma_de_pago'];

                include 'saldodeventas.php';
              ?>
            <tr>
                <td><?php  echo $estados;?></td>
                <td><?php echo $reg['ven_prefijo']; ?><?php echo $reg['ven_n_venta']; ?></td>
                <td><?php echo $reg['ven_fecha'];?> - <?php  echo $reg['ven_hora']; ?></td>
                <td><?php echo $reg['ven_nombre']; ?></td>
                <td><?php echo $ven_forma_de_pago; ?></td>
                <td><p class="pull-right"><?php echo number_format($sumador_total,0); ?></p></td>
                <td><p class="pull-right"><?php echo number_format($total_abono,0);  ?></p> </td>
                <td><p class="pull-right"><?php echo number_format($devo_total,0); ?></p></td>
                <td><p class="pull-right"><?php echo number_format($saldo,0); ?></p></td>
                <td>
                    <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  if($reg['ven_estado']<>"anulada") { ?>
                    <div class="btn-group " >

                    <button type="button" class="btn btn-xs  btn-default dropdown-toggle" data-toggle="dropdown"><i class="fas fa-plus"></i> <span class="caret"></span></button>
                        <ul class="dropdown-menu" role="menu">
                        <?php 

                        $per = mysqli_query($con,"SELECT * FROM  modulo_permiso where usuario='$usu_id' and mod_id='24' and modp_nombre='Anular Ventas' ") or die(mysqli_error($con));
                        $permi = mysqli_fetch_array($per);
                        $estado_anular=$permi['estado'];
                        if ($estado_anular=='Activo') {
                        if ($devo_total<=0 && $ven_estado<>'anulada' && $estado_dian<>'Aprobada'){?>
                            <li><a  href="#" data-id="<?php echo $id;?>" class="btn-anular"><i class="fas fa-ban"></i> Anular</a></li>
                        <?php } } ?>

                        <?php 
                        $per = mysqli_query($con,"SELECT * FROM  modulo_permiso where usuario='$usu_id' and mod_id='24' and modp_nombre='Realizar Abonos' ") or die(mysqli_error($con));
                        $permi = mysqli_fetch_array($per);
                        $estado_abonar=$permi['estado'];
                        if ($estado_abonar=='Activo') {
                            if ($ven_estado=="sin pagar") { ?>
                            <li><a href="#" data-id="<?php echo $id;?>" class="btn-abonar"><i class="fas fa-hand-holding-usd"></i> Abonar</a></li>
                        <?php } } ?>

                        <?php 
                        $per=mysqli_query($con,"SELECT * FROM modulo_permiso where usuario='$usu_id' and mod_id='24' and modp_nombre='Nota Credito'") or die(mysqli_error($con));
                        $permi = mysqli_fetch_array($per);
                        $estado_nota=$permi['estado'];
                        if ($estado_nota=='Activo') { ?>

                        <?php  
                            if($reg['ven_nombre']<>"CLIENTE MOSTRADOR" && $ven_estado<>'anulada'){ ?>
                            <li><a href="P_devolucion.php?ven_id=<?php echo $ven_id;?>" title="Devoluciones Y Descuentos"><i class="fas fa-undo-alt"></i> Nota Credito</a></li>
                        <?php } } ?>
                      
                            <li><a href="#" data-id="<?php echo $id;?>" class="btn-cliente"><i class="fas fa-user-edit"></i> Modificar Cliente</a></li>

                            <?php if ($ven_forma_de_pago=='Contado' || $ven_forma_de_pago=='Transferencia' || $ven_forma_de_pago=='Tarjeta' ) { ?>
                            <li><a  href="#" data-id="<?php echo $id;?>" class="btn-modificar_pago"><i class="fas fa-credit-card"></i> Modificar Metodo Pago</a></li>
                        <?php } ?>
                        
                        <?php if($ven_forma_de_pago=="Credito"){?>
                            <li class="divider"></li>
                            <li><a href="#abonos<?php echo $reg['ven_id']; ?>" data-toggle="modal" ><i class="fas fa-history"></i> Historial de Abonos</a></li>
                        <?php }?>
                        </ul>
                        <?php include ('../php_ventas/historial_abono.php'); ?> 
                    </div>
                    <?php include ('../include/boton_venta2.php'); } ?>
                     
                </td>
            </tr>
           <?php }?>

            <tr>
                <td colspan=5></td>
                <td ><strong><span class="pull-right" style="color:#008000;"><h5>
                    <?php
                        $total_ventas=0;
                        $ven1=mysqli_query($con,"SELECT * from ventas where ven_estado<>'anulada' and ven_tipo='$tipo' and apertura='$apertura' and usuario='$usu_id'");
                        while ($vent1=mysqli_fetch_array($ven1))
                            {
                                $sumador_combo=0;
                                $sumador_total=0;

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

                                $ven_id=$vent1['ven_id'];
                                $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;
                                $total_ventas+=$sumador_total;
                            }
                      
                        echo number_format($total_ventas,0); 
                    ?></h5></span></strong>
                </td>
                <td colspan=5></td>
            </tr>
            <tr>
                <td colspan=11>
                    <span class="pull-right">
                        <?php echo paginate($reload, $page, $total_pages, $adjacents); ?>
                    </span>
                </td>
            </tr>
        </table>
      </div>
<?php } } ?>

<script>
    $(".btn-anular").click(function(){
        id = $(this).data("id");
        $.get("./php_pos/forms_anular.php","id="+id,function(data){
            $("#form-anular").html(data);
        });
        $('#anular').modal('show');
    });
</script>


<script>
    $(".btn-abonar").click(function(){
        id = $(this).data("id");
        $.get("./php_pos/forms_abonar.php","id="+id,function(data){
            $("#form-abonar").html(data);
        });
        $('#abonar').modal('show');
    });
</script>
  

<script>
    $(".btn-cliente").click(function(){
        id = $(this).data("id");
        $.get("./php_pos/forms_cliente.php","id="+id,function(data){
            $("#form-cliente").html(data);
        });
        $('#cliente').modal('show');
    });
</script>

<script>
    $(".btn-modificar_pago").click(function(){
        id = $(this).data("id");
        $.get("./php_pos/forms_modificar_metodo_pago.php","id="+id,function(data){
            $("#form-modificar_pago").html(data);
        });
        $('#modi-pago').modal('show');
    });
</script>

<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>

<script>
   function enviar_email(ven_id){
      VentanaCentrada('./libraries/pdf/pdf_correos/email_venta.php?ven_id='+ven_id,'Factura','','800','600','true');
    }
</script>

