<?php
session_start();
require_once ("../conexion.php");
require_once('../include/sesiones.php'); 
if (isset($_POST['cantidad'])){$cantidad=$_POST['cantidad'];}
if (isset($_POST['concepto'])){$concepto=$_POST['concepto'];}
if (isset($_POST['valor'])){$valor=$_POST['valor'];}
$tipo_envio = isset($_POST['tipo_envio']) ? $_POST['tipo_envio'] : null;
$fecha_inicio = isset($_POST['fecha_inicio']) ? $_POST['fecha_inicio'] : null;

if (!empty($cantidad))
{
    $insert_tmp=mysqli_query($con, "INSERT INTO dian_documento_temp (sop_nombre,sop_cantidad,sop_precio,sop_tipo_envio,sop_fecha_envio,usuario,empresa) 
    VALUES ('$concepto','$cantidad','$valor','$tipo_envio','$fecha_inicio','$usu_id','$empresa')");
}
$total_retencion=0;
$ret=mysqli_query($con,"SELECT IFNULL(SUM(ret_importe), 0) as ret_importe FROM retencion_doc_temp where empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con)); 
$rets=mysqli_fetch_array($ret);
$total_retencion=$rets['ret_importe'];
?>

<table class="table table-bordered table-hover table-striped">
	<tr>
		<th width="5%">CANTIDAD</th>
		<th>DESCRIPCION</th>
		<th width="10%">VR UNITARIO</th>
		<th width="10%"></th>
	</tr>
	<?php
		$sumador_total=0;
		$sql=mysqli_query($con, "SELECT * from dian_documento_temp where usuario='$usu_id' and empresa='$empresa'");
		while ($row=mysqli_fetch_array($sql))
		{
		$id=$row["sop_id"];
		$sop_cantidad=$row['sop_cantidad'];
		$sop_nombre=$row['sop_nombre'];
		$sop_precio=$row['sop_precio'];
		$total=$sop_cantidad*$sop_precio;
		$sumador_total+=$total;
	?>
	<tr>
		<td><?php echo $sop_cantidad;?></td>
		<td><?php echo $sop_nombre;?></td>
		<td><span class="pull-right"><?php echo number_format($sop_precio,0);?></span></td>
		<td>
			<!--<a data-id="<?php echo $id;?>" class="btn btn-edit btn-xs btn-warning"> <i class="btn-icon-only icon-edit"></i></a>-->
			<a href="#" id="del-<?php echo $row["sop_id"];?>" class="btn btn-xs btn-danger"> <i class="btn-icon-only icon-remove"></i></a>
			<script>
			$("#del-"+<?php echo $row["sop_id"];?>).click(function(e){
				e.preventDefault();
				p = confirm("Estas seguro?");
				if(p){
					$.get("./php_doc_soporte/eliminar_temp.php","sop_id="+<?php echo $row["sop_id"];?>,function(data){
						loadTabla();
					});
				}
			});
			</script>
		</td>
	</tr>		
	<?php } ?>

	<tr>
    	<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></td>
    	<td><span class="pull-right">RETENCIONES $</span></td>
		<td><span class="pull-right"><strong><?php echo number_format($total_retencion,0);?></strong></span></td>
		<td> <?php
        $ret=mysqli_query($con,"SELECT * FROM retencion_doc_temp where empresa='$empresa' and usuario='$usu_id'") or die(mysqli_error($con)); 
        while ($rets=mysqli_fetch_array($ret))
        {
            $rret_id=$rets['ret_id'];
            $retencion_ret_id=$rets['retencion_ret_id'];
            $rete=mysqli_query($con,"SELECT * FROM retencion where empresa='$empresa' and ret_id='$retencion_ret_id' ") or die(mysqli_error($con));
            $rete=mysqli_fetch_array($rete);
            $ret_nombre=$rete['ret_nombre'];
            $ret_porcentaje=$rete['ret_porcentaje'];
        ?>
        (<?php echo $ret_porcentaje;?>%)<a href="#" id="re-<?php echo $rets["ret_id"];?>"><i class="btn-icon-only icon-remove"></i></a>
        <script>
        $("#re-"+<?php echo $rets["ret_id"];?>).click(function(e){
        e.preventDefault();
        p = confirm("Estas seguro?");
        if(p){
            $.get("./php_doc_soporte/eliminar_retencion.php","ret_id="+<?php echo $rets["ret_id"];?>,function(data){
              loadTabla();
              loadtotal();
              loadbotones();
            });
          }
        });
        </script><?php } ?></td>
	</tr>	
	<tr>
    	<td></td>
    	<td><span class="pull-right">TOTAL $</span></td>
		<td><span class="pull-right"><strong><?php echo number_format($sumador_total-$total_retencion,0);?></strong></span></td>
		<td></td>
	</tr>	
</table>
    <div class="widget-content">
		<div class="col-md-12" style="padding:0px;">
            <form action="" method="post" id="retencion_form" name="retencion_form" class=""> 
                <div class="col-md-4" style="padding-left:0px"> 
                    <label>Tipo</label> 
                    <select class="form-control input-sm" name="retencion_select" id="retencion_select" onchange="calcularRetencion()" required>
                        <option value=""> - </option>
                        <?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']; ?>" 
                                    data-porcentaje="<?php echo $row_1['ret_porcentaje']; ?>"
                                >
                                    <?php echo $row_1['ret_nombre']; ?> (<?php echo $row_1['ret_porcentaje']; ?> %)
                                </option>
                        <?php } ?>
                    </select>
                </div>

                <div class="col-md-3" style="padding-left:0px"> 
                    <label>Base Imponible</label>
                    <input type="number" name="base_imponible"  class="form-control input-sm" 
                           id="base_imponible" autocomplete="off" onkeyup="calcularRetencion()" value="<?php echo round($sumador_total); ?>" />
                </div>

                <div class="col-md-3" style="padding-left:0px"> 
                    <label>Importe</label>
                    <input type="number" name="importe" value="0" class="form-control input-sm" 
                           id="importe" autocomplete="off" step="0.01" readonly />
                </div>

                <div class="col-md-2" style="padding-left:0px"> 
                    <label>&nbsp;</label>
                    <span class="input-group-btn">
                        <button name="btn_ret" id="btn_ret" type="submit" class="btn btn-warning btn-sm" style="width:100%">
                            % Aplicar Retención
                        </button>
                    </span>
                </div>   
            </form>
            <script>
            function calcularRetencion() {
                var selectRet   = document.getElementById('retencion_select');
                var baseInput   = document.getElementById('base_imponible');
                var importeInput= document.getElementById('importe');

                if (!selectRet || !baseInput || !importeInput) {
                    return;
                }

                var opcionSeleccionada = selectRet.options[selectRet.selectedIndex];
                var porcentaje = opcionSeleccionada.getAttribute('data-porcentaje');

                var base = parseFloat(baseInput.value);
                if (isNaN(base)) {
                    base = 0;
                }

                if (!porcentaje) {
                    importeInput.value = 0;
                    return;
                }

                var porcentajeNum = parseFloat(porcentaje);
                var importe = base * (porcentajeNum / 100);

                importeInput.value = importe.toFixed(2);
            }
            </script>
        </div>
</div>

<script type="text/javascript">
//retencion
$( "#retencion_form" ).submit(function( event ) {
$('#btn_ret').attr("disabled", true);
var parametros=$(this).serialize();
   $.ajax({
      type: "POST",
      url: "php_doc_soporte/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();
      loadtotal();
      loadbotones();
      }
  });
  event.preventDefault();
})
</script>