<?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)));
    $ser = mysqli_real_escape_string($con,(strip_tags($_REQUEST['ser'], ENT_QUOTES)));

    $mes = mysqli_real_escape_string($con,(strip_tags($_REQUEST['mes'], ENT_QUOTES)));
    $ano = mysqli_real_escape_string($con,(strip_tags($_REQUEST['ano'], ENT_QUOTES)));

    include '../include/pagination.php';
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 15; 
    $adjacents  = 4; 
    $offset = ($page - 1) * $per_page;
    $count_query   = mysqli_query($con, "SELECT count(*) AS numrows FROM compras  
      where empresa='$empresa' and sucursal='$sucursal' and (proveedor_nombre like '%$q%' OR com_n_compra like '%$q%' OR com_facturaproveedor like '%$q%') ");
    $row= mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = '../C_compras.php';

    if ($ser<>null) {
      $sqlser = mysqli_query($con,"SELECT * FROM seriales_compra 
      where  ser_codigo='$ser' ");
      $sqlser=mysqli_fetch_array($sqlser);
      $compra_detalle_comd_id=$sqlser['compra_detalle_comd_id'];

      $sqlser1 = mysqli_query($con,"SELECT * FROM compra_detalle 
      where comd_id='$compra_detalle_comd_id'");
      $sqlser1=mysqli_fetch_array($sqlser1);
      $compras_com_id=$sqlser1['compras_com_id'];

      $sqlc = mysqli_query($con,"SELECT * FROM compras 
      where com_id='$compras_com_id' and  empresa='$empresa' and sucursal='$sucursal' 
      order by com_id desc LIMIT $offset,$per_page");
    }
    else
    {
        if ($mes==0) {
            $sqlc = mysqli_query($con,"SELECT * FROM compras 
      where empresa='$empresa' and sucursal='$sucursal' and (proveedor_nombre like '%$q%' OR com_n_compra like '%$q%' OR com_facturaproveedor like '%$q%')
      order by com_id desc LIMIT $offset,$per_page");

        } else{ 
            
       $sqlc = mysqli_query($con,"SELECT * FROM compras 
      where empresa='$empresa' and sucursal='$sucursal' and MONTH(com_fecha)='$mes' AND YEAR(com_fecha)='$ano' and (proveedor_nombre like '%$q%' OR com_n_compra like '%$q%' OR com_facturaproveedor like '%$q%')
      order by com_id desc LIMIT $offset,$per_page");
    }
}

    if ($numrows>0){
?>
<div class="table-responsive">
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <td width="5%"></td>
                <th width="7%">Nº</th>
                <th width="10%">Nº FACTURA</th>
                <th width="9%">FECHA</th>
                <th>PROVEEDOR</th>
                <th>TOTAL</th>
                <th>SALDO</th>
                <th width="14%"></th>
            </tr>
        </thead>
    <tbody  class="buscar">
<?php 
while ($reg=mysqli_fetch_array($sqlc))
{
    $com_id=$reg['com_id'];
    $sumador_total=0;
    $neto=0;
    $total_retencion=0;
    $total_cargo_adicional=0;
    $sql=mysqli_query($con, "SELECT * from compra_detalle where compras_com_id='$com_id' and empresa='$empresa'");
    while ($rew=mysqli_fetch_array($sql))
    {
        $comd_cantidad=$rew['comd_cantidad'];
        $comd_precio=$rew['comd_precio'];
        $comd_iva=$rew['comd_iva'];
        $comd_flete=$rew['comd_flete'];
        $cargo_adicional=$comd_flete*$comd_cantidad;
        $precio_total=$comd_precio*$comd_cantidad;
        $iva=($precio_total*$comd_iva)/100;
        $neto+=$precio_total;//Sumador
        $sumador_total+=$precio_total+$iva;//Sumador
        $total_cargo_adicional+=$cargo_adicional;
    }

    $ret=mysqli_query($con,"SELECT * FROM retencion_compra where empresa='$empresa' and compras_com_id='$com_id'") or die(mysqli_error($con)); 
    $rets=mysqli_fetch_array($ret);
    if (isset($rets['ret_porcentaje'])) 
    {
       $total_retencion=($ret_porcentaje=$rets['ret_porcentaje']/100)*$neto;
    }

    $total_real=$sumador_total+$total_cargo_adicional-$total_retencion;

    $sql=mysqli_query($con, "SELECT sum(coab_abono) as coab_abono from compra_abonos where compras_com_id='$com_id' and empresa='$empresa'");
    $sql1=mysqli_fetch_array($sql);
    $coab_abono=$sql1['coab_abono'];
    $saldo=$total_real-$coab_abono;


?>
    <tr>
        <td><?php
            if($reg['com_estado']=="Pagado")
                {
                    echo $estados='<a title="" class=""><span class="badgeazul"><i class="btn-icon-only">Pagada</i></span></a>';
                }
                else  
                {
                    echo $estados='<a title="" class=""><span class="badgenaranja"><i class="btn-icon-only">Sin Pagar</i></span></a>';
                }
            ?>
        </td>
                <td><?php echo $reg['com_n_compra']; ?></td>
                <td><?php echo $reg['com_facturaproveedor']; ?></td>
                <td><?php echo $reg['com_fecha']; ?></td>
                <td><?php echo $reg['proveedor_nombre']; ?></td>
                <td><p class="pull-right"><?php echo number_format($total_real,0); ?></p></td>
                <td><p class="pull-right"> <?php 
                    if($reg['com_estado']<>"Pagado")
                    {
                        echo number_format($saldo,0);
                    }
                ?>
                </td>
                <td>
                    <div class="btn-group">
                    <button type="button" class="btn btn-xs  btn-default dropdown-toggle" data-toggle="dropdown" title="Mas acciones"><i class="fa-solid fa-plus"></i></i> <span class="caret"></span></button>
                        <ul class="dropdown-menu" role="menu">
                            <?php  if($reg['com_estado']=="Sin pagar") { ?>
                            <li><a href="#" data-id="<?php echo $reg['com_id'];?>" class="btn-abonar">Abonar</a></li>
                            <?php  }  ?>
                            <!-- <li><a href='C_compras_devolucion.php?com_id=<?php //echo $reg['com_id']; ?>' class="">Devolucion</a></li>-->
                            <li class="divider"></li>
                            <li><a href="#" data-id="<?php echo $reg['com_id'];?>" class="btn-detalle" >Detalles</a></li>
                        </ul>
                    </div>
                    <?php 
                    $files = glob("../img/img_facturas/$com_id.pdf");
                    if(count($files) > 0) 
                    { 
                        foreach($files as $file) 
                        { 
                    ?> <a data-id="<?php echo $reg['com_id'];?>" class="btn btn-pdf btn-xs btn-success"> <i class="btn-icon-only icon-upload"></i></a>
                    <?php } } else { ?>
                    <a data-id="<?php echo $reg['com_id'];?>" class="btn btn-pdf btn-xs btn-primary" title="Subir pdf"><i class="btn-icon-only icon-upload"></i></a>
                    <?php  }  ?>

                    <?php 
                    $est=mysqli_query($con,"SELECT * FROM modulo_permiso WHERE mod_id='16' and modp_nombre='Modificar Compra' and usuario='$usu_id' ") or die(mysqli_error($con));
                    $est1=mysqli_fetch_array($est);
                    $estado_edi_com=$est1['estado'];
                    if ($estado_edi_com=='Activo') 
                    { ?>
                        <a href="C_compras_modificar.php?com_id=<?php echo $reg['com_id']; ?>" title="Modificar" class="btn btn-xs btn-info" data-toggle="modal"><i class="btn-icon-only icon-edit"></i> </a>
                    <?php   }  ?>

                    <?php 
                    $est_eli=mysqli_query($con,"SELECT * FROM modulo_permiso WHERE mod_id='16' and modp_nombre='Eliminar Compra' and usuario='$usu_id' ") or die(mysqli_error($con));
                    $est2=mysqli_fetch_array($est_eli);
                    $estado_eli_com=$est2['estado'];
                    if ($estado_eli_com=='Activo') 
                    { ?>

                    <a href="#" class='btn btn-xs btn-danger' title='Eliminar Compra' onclick="eliminar('<?php echo $reg['com_id'];?>');"><i class="btn-icon-only icon-remove"></i></a> 
                     <?php  }  ?>
                </td>
            </tr>
           <?php }?>
            <tr>
                <td colspan=8><span class="pull-right">
                <?php
                    echo paginate($reload, $page, $total_pages, $adjacents);
                ?></span>
                <input type="hidden" name="pagina" id="pagina" value="<?php echo $page; ?>">
                </td>
            </tr>
        </tbody>
    </table>
</div>    
<?php } } ?>
 <script>
function eliminar (id)
{
    var q= $("#q").val();
    if (confirm("Realmente deseas eliminar la Compra")){ 
    $.ajax({
        type: "GET",
        url: "php_compras/eliminar_compra.php",
        data: "id="+id,"q":q,
     beforeSend: function(objeto){
         $('#resultados').html('<center><img src="./img/ajax-loader.gif"> CARGANDO...</center>');
      },
        success: function(datos){
    $("#resultados").html(datos);
    load(1);
    }
      });
    }
}
</script>

<script>
    $(".btn-abonar").click(function(){
      id = $(this).data("id");
      $.get("./php_compras/form_abonar.php","id="+id,function(data){
        $("#form-abonar").html(data);
      });
      $('#ModalAbonar').modal('show');
    });
</script>
<div class="modal fade" id="ModalAbonar" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">ABONAR</h4>
            </div>
            <div class="modal-body">
                <div id="form-abonar"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->



<script>
    $(".btn-pdf").click(function(){
      id = $(this).data("id");
      var pagina=$("#pagina").val();
      $.get("php_compras/form_pdf.php","id="+id+"&pagina="+pagina,function(data){
        $("#form-pdf").html(data);
      });
      $('#Modalpdf').modal('show');
    });
</script>
<div class="modal fade" id="Modalpdf" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
            </div>
            <div class="modal-body">
                <div id="form-pdf"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


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


