<?php
session_start();
require_once ("../conexion.php");
require_once('../include/sesiones.php');
if (isset($_POST['art_id'])){$art_id=$_POST['art_id']; $art_id;}
if (isset($_POST['art_referencia'])){$art_referencia=$_POST['art_referencia'];}
if (isset($_POST['cantidad'])){$cantidad=$_POST['cantidad'];}
if (isset($_POST['precio_venta'])){$precio_venta=$_POST['precio_venta'];}
if (isset($_POST['nombre'])){$nombre=$_POST['nombre'];}
if (isset($_POST['iva'])){ $iva=$_POST['iva'];}
if (isset($_POST['fecha_vencimiento'])){ $fecha_vencimiento=$_POST['fecha_vencimiento'];}
if (isset($_POST['flete'])){ $flete=$_POST['flete'];}
if (isset($_POST['atributo_estado'])){ $atributo_estado=$_POST['atributo_estado'];}
if (isset($_POST['atributo1'])){$atributo1=$_POST['atributo1'];}
if (isset($_POST['atributo2'])){$atributo2=$_POST['atributo2'];}


if (!empty($cantidad))
{
    if ($atributo_estado=='si')
    {    
        $atri11=mysqli_query($con,"SELECT * FROM atributos1 where atri_id='$atributo1'");
        $atri11 = mysqli_fetch_array($atri11);
        if (isset($atri11['atri_nombre'])) { $atri_nombre= $atri11['atri_nombre']; } else { $atri_nombre='';}

        $atri2=mysqli_query($con,"SELECT * FROM atributos2 where atri_id2='$atributo2'");
        $atri2 = mysqli_fetch_array($atri2);
        if (isset($atri2['atri_nombre2'])) { $atri_nombre2=' - '.$atri2['atri_nombre2']; } else { $atri_nombre2='';}

            $atributos=$atri_nombre .$atri_nombre2;
    }
    else
    {
        $atributos='';
    }

    $sqll=mysqli_query($con,"SELECT comt_art_id FROM compra_detalle_temp WHERE comt_art_id='$art_id' and atributo1='$atributo1' and atributo2='$atributo2' and empresa='$empresa' and usuario='$usu_id'") ;
    if($roww=mysqli_fetch_array($sqll))
    { 
        $can7=mysqli_query($con,"SELECT * FROM compra_detalle_temp WHERE comt_art_id='$art_id' and atributo1='$atributo1' and atributo2='$atributo2' and empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con));  
        while($dato=mysqli_fetch_array($can7))
        {
            $r=$dato['comt_art_id'];            
            $c=$dato['comt_cantidad'];
            $suma=$cantidad+$c;
        }
        $registros=mysqli_query($con,"UPDATE compra_detalle_temp Set comt_cantidad='$suma',comt_precio='$precio_venta' Where comt_art_id='$art_id'  and atributo1='$atributo1' and atributo2='$atributo2' and empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con));
    }
    else
    {   
        $insert_tmp=mysqli_query($con, "INSERT INTO compra_detalle_temp (comt_art_id,comt_referencia,comt_cantidad,comt_nombre,comt_precio,comt_iva,comt_desc_desp_iva,comt_flete,fecha_vencimiento,atributo1,atributo2,usuario,empresa) 
        VALUES ('$art_id','$art_referencia','$cantidad','$nombre $atributos','$precio_venta','$iva','0','$flete','$fecha_vencimiento','$atributo1','$atributo2','$usu_id','$empresa')");
    }
}
?>
<table class="table table-bordered table-hover table-striped">
<tr>
    <th width="10%">CODIGO</th>
    <th>DESCRIPCIÓN</th>
    <th width="8%">CANTIDAD</th>
    <th width="10%"><span class="pull-right">PRECIO UNIT</span></th>
    <th width="8%"><span class="pull-right">IMP</span></th>
    <th width="8%"><span class="pull-right">DESC.</span></th>
    <th width="10%"><span class="pull-right">PRECIO TOTAL</span></th>
    <th width="10%"></th>
</tr>
<?php
    $sumador_total=0;
    $sumador_iva=0;
    $sumador_descuento=0;
    $total_cargo_adicional=0;
    $sql=mysqli_query($con, "SELECT * from compra_detalle_temp where usuario='$usu_id' and empresa='$empresa' ");
    $art=mysqli_num_rows($sql);
    while ($row=mysqli_fetch_array($sql))
    {
    $id=$row["comt_id"];
    $comt_id=$row["comt_id"];
    $comt_referencia=$row['comt_referencia'];
    $comt_nombre=$row['comt_nombre'];
    $comt_cantidad=$row['comt_cantidad'];
    $comt_precio=$row['comt_precio'];
    $comt_iva=$row['comt_iva'];
    $comt_desc_desp_iva=$row['comt_desc_desp_iva'];
    $comt_flete=$row['comt_flete'];
    $cargo_adicional=$comt_flete*$comt_cantidad;
    $precio_total=$comt_precio*$comt_cantidad;
    $iva_uni=($comt_precio*$comt_iva)/100;
    $iva=($precio_total*$comt_iva)/100;
    $sumador_iva+=$iva;//Sumador
    $sumador_total+=$precio_total;//Sumador
    $total_cargo_adicional+=$cargo_adicional;//Sumador
    $sumador_descuento+=$comt_desc_desp_iva;
?>
        <tr>
            <td><?php echo $comt_referencia;?></td>
            <td><?php echo $comt_nombre;?><?php if($row['lote']<>null) { ?>(<strong>LOT:</strong> <span style="color:red"><?php echo $row['lote'];  ?></span>)<?php }?></td>
            <td><?php echo $comt_cantidad;?></td>
            <td><span class="pull-right"><?php echo number_format($comt_precio,2);?></span></td>
            <td><span class="pull-right"><?php echo number_format($iva_uni,0);?></span></td>
            <td><span class="pull-right"><?php echo number_format($comt_desc_desp_iva,0);?></span></td>
            <td><span class="pull-right"><?php echo number_format($precio_total,0);?></span></td>
            <td >
                <a data-id="<?php echo $id;?>" class="btn btn-edit btn-xs btn-info"> <i class="btn-icon-only icon-edit"></i></a>
                <a href="#" id="del-<?php echo $row["comt_id"];?>" class="btn btn-xs btn-danger"> <i class="btn-icon-only icon-remove"></i></a>
              <?php if ($negocio_neg_id==1){ 
                $can1=mysqli_query($con,"SELECT * FROM seriales_com_temp where compra_detalle_temp_comt_id='$comt_id'") or die(mysqli_error($con)); 
                $dat=mysqli_fetch_array($can1);
                $result = mysqli_num_rows($can1);
                    if($result == 0)
                    {
            ?>
                <a  data-id="<?php echo $id;?>" data-toggle="modal" class="btn btn-ser btn-xs btn-default" title="Serial"> <i class="btn-icon-only icon-barcode"></i></a>
            <?php } else { ?>
                <a  data-id="<?php echo $id;?>" data-toggle="modal" class="btn btn-ser_tabla btn-xs btn-default" title="Serial"> <i class="btn-icon-only icon-barcode"></i></a>
            <?php } }?>
                <script>
                    $("#del-"+<?php echo $row["comt_id"];?>).click(function(e){
                    e.preventDefault();
                    p = confirm("Estas seguro?");
                    if(p){
                    $.get("./php_compras/eliminar.php","comt_id="+<?php echo $row["comt_id"];?>,function(data){
                    loadTabla();
                        });
                        }
                    });
                </script>
            </td>
        </tr>       
<?php } ?>
        <tr>
            <td><span class="pull-right"></span></td>
            <td></td>
            <td><span class="pull-left">  
                <?php
                    $sum=mysqli_query($con,"SELECT sum(comt_cantidad) as comt_cantidad FROM compra_detalle_temp where empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con));
                    $sum=mysqli_fetch_array($sum);
                    $comt_cantidad=$sum['comt_cantidad'];
                ?>
                <strong><a  title="" class=""><span class="badgeazul"><i class="btn-icon-only "><?php echo $comt_cantidad; ?></i></span></a></strong>
            </td>
            <td></td>
            <td></td> 
            <td><span class="pull-right">SUBTOTAL</span></td>
           <td><span class="pull-right"><strong><?php echo number_format($sumador_total,0);?></strong></span></td>
           <td></td>
        </tr>
        <tr>
            <td><span class="pull-right"></span></td>
            <td></td>
            <td></td> 
            <td></td>
            <td></td>
            <td><span class="pull-right">IMPUESTO</span></td>
            <td><span class="pull-right"><strong><?php echo number_format($sumador_iva,0);?></strong></span></td>
            <td></td>
        </tr>
        <tr>
            <td></td> 
            <td></td> 
            <td></td> 
            <td><span class="pull-right"></span></td>
            <td colspan=2><span class="pull-right">DESC. CONDICIONAL</span></td>
            <td><span class="pull-right"><strong><?php echo number_format($sumador_descuento,0);?></strong></span></td>
            <td></td>
        </tr>
         <tr>
            <td><span class="pull-right"></span></td>
            <td></td>
            <td></td> 
            <td></td>
            <td></td>
            <td><span class="pull-right">RETENCION</span></td>
            <td><span class="pull-right"><strong>
                <?php
                    $retencion=0;
                    $ret=mysqli_query($con,"SELECT * FROM retencion_compra_temp where empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con)); 
                    $rets=mysqli_fetch_array($ret);

                    if (isset($rets['ret_porcentaje'])) 
                    {
                        $retencion= ($ret_porcentaje=$rets['ret_porcentaje'])/100*$sumador_total;
                        echo number_format($retencion,0);
                    }
                ?>
            </strong></span></td>
            <td>
                <?php
                    $ret=mysqli_query($con,"SELECT * FROM retencion_compra_temp where empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con)); 
                    while ($rets=mysqli_fetch_array($ret))
                    {
                        $ret_porcentaje=$rets['ret_porcentaje'];
                    ?>
                    <h5> (<?php echo $ret_porcentaje;?>%)<a href="#" id="re-<?php echo $rets["ret_id"];?>"><i class="btn-icon-only icon-remove"></i></a></h5>
                    <script>
                    $("#re-"+<?php echo $rets["ret_id"];?>).click(function(e){
                      e.preventDefault();
                      p = confirm("Estas seguro?");
                      if(p){
                        $.get("./php_compras/eliminar_retencion.php","ret_id="+<?php echo $rets["ret_id"];?>,function(data){
                          loadTabla();
                        });
                      }
                    });
                    </script>
                <?php }?>
            </td>
        </tr>
        <tr>
            <td><span class="pull-right"></span></td>
            <td></td>
            <td></td> 
            <td></td>
            <td></td>
            <td><span class="pull-right">CARGO AD</span></td>
            <td><span class="pull-right"><strong><?php echo number_format($total_cargo_adicional,0);?></strong></span></td>
            <td></td>
        </tr>
        <tr>
            <td><span class="pull-right"></span></td>
            <td></td>
            <td></td> 
            <td></td>
            <td></td>
            <td><span class="pull-right">TOTAL</span></td>
            <td><span class="pull-right"><strong><?php echo number_format(($total_compra=$sumador_total+$sumador_iva+$total_cargo_adicional)-$retencion-$sumador_descuento,0);?></strong></span></td>
            <td></td>
        </tr>
</table>
<script>
//retencion
$( "#form_retencion" ).submit(function( event ) {
$('#btn_ret').attr("disabled", true);
var parametros=$(this).serialize();
   $.ajax({
      type: "POST",
      url: "php_compras/registrar_retencion.php",
      data: parametros,
        beforeSend: function(objeto){
         $('#tabla').html('<center><img src="./img/ajax-loader.gif"> CARGANDO...</center>');
        },
      success: function(datos){
      $("#tabla").html(datos);
      $('#btn_ret').attr("disabled", false);
      loadTabla();
      }
  });
  event.preventDefault();
})
</script>
<?php
if ($art >0) { 
   
?>
    <div class="col-md-7" style="padding:0px;"></div>
    <div class="col-md-3" style="padding:0px;">
        <form action="" method="post" id="form_retencion" name="form_retencion" class="">
            <div class="input-group">
                <select class="form-control input-sm" name="retencion" required>
                    <?php
                        $result_1=mysqli_query($con,"SELECT * FROM retencion WHERE empresa='$empresa'");  
                        while ($row_1=mysqli_fetch_array($result_1)) 
                        {   ?>
                            <option value='<?php echo $row_1['ret_id']; ?>' ><?php echo $row_1['ret_nombre']; ?> (<?php echo $row_1['ret_porcentaje']; ?> %)</option> 
                    <?php } ?>
                </select>
                <span class="input-group-btn">
                <button name="btn_ret" id="btn_ret" type="submit" class="btn btn-warning  btn-sm" >Retención</button></span>
            </div>
        </form>
    </div>
    <div class="col-md-2" style="padding:0px;">
        <button href="#completar_compra" class="btn btn-success pull-right" data-toggle="modal" type="button"><i class=" icon-ok"> </i><strong>Completar Compra</strong></button>
    </div></br></br>  

<?php } ?>
 <?php  include ('completar_compra.php');?> 

<script>
    $(".btn-edit").click(function(){
        id = $(this).data("id");
        $.get("./php_compras/form_modificar.php","id="+id,function(data){
            $("#form-edit").html(data);
        });
        $('#editModal').modal('show');
    });
</script>
<div class="modal fade" id="editModal" 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">ACTUALIZAR</h4>
            </div>
            <div class="modal-body">
                <div id="form-edit"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
    $(".btn-ser").click(function(){
        id = $(this).data("id");
        $.get("./php_compras/form_serial.php","id="+id,function(data){
            $("#form-serial").html(data);
        });
        $('#reg_ser').modal('show');
    });
</script><!-- /.modal en C_compras_registar -->


<script>
    $(".btn-ser_tabla").click(function(){
        id = $(this).data("id");
        $.get("./php_compras/form_serial_tabla.php","id="+id,function(data){
            $("#form-tabla_serial").html(data);
        });
        $('#reg_ser_tabla').modal('show');
    });
</script>
<div class="modal fade" id="reg_ser_tabla" 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">SERIALES</h4>
            </div>
            <div class="modal-body">
                <div id="form-tabla_serial"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->



 <div class="modal fade" id="n_serial" 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">NUEVO SERIAL</h4>
            </div>
            <div class="modal-body">
                <div id="form-n_serial"></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->       