<?php
 @session_start();
  $vg_login=$_SESSION["usuario"];
  if($vg_login<>""){}
 else
  {echo "<script>";
   echo "window.location='../index.php';";
   echo "</script>";
  }	
include "../valida_permisos.php";
$vg_programa = F_programa();
include "../seguridad.php";
$ip=getenv("REMOTE_ADDR");
date_default_timezone_set('America/Bogota');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>SIVI</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<LINK REL="SHORTCUT ICON" HREF="../sivi.ico">
<LINK href="../general.css" type=text/css rel=stylesheet>
<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="../bootstrap/js/bootstrap.min.js"></script>
 <link rel="stylesheet" href="../toastn/style.css">
 <script src="../toastn/cute-alert.js"></script>
 
 <script language="javascript">
function format(input)
{
var num = input.value.replace(/\./g,'');
if(!isNaN(num)){
num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1.');
num = num.split('').reverse().join('').replace(/^[\.]/,'');
input.value = num;
}

else{ //alert('Solo se permiten numeros');
input.value = input.value.replace(/[^\d\.]*/g,'');
}
}
</script>

</head>


<BODY onLoad="parametros.cliente.focus();">
<?php

include "../conexion.php";
$id="";$nombre="";$estado="";$descripcion="";
$preciounitario="";$precioventa="";$productofamilia="";$marca="";$iva="";$codigobarra="";
$cliente="";	
   							  
if(isset($_REQUEST["oculto"]))
{ 
	$cliente=$_REQUEST["cliente"]; 
	
	 if($_REQUEST["oprocesar"]==1)
    {
		     $c=1; $paso=0;
			  $canti=$_REQUEST["canti"];$errrosaldo=0;
			  while($c<=$canti)
			   {  
				 if(isset($_REQUEST['ch'.$c])) {$val=1; }  else {$val=0;} 
				   
				   if($val==1)
					  {  
					   $factura=$_REQUEST['factura'.$c];
					   $valorpagado=str_replace('.','',$_REQUEST['valorpagado'.$c]);
					   $totalpagado=$_REQUEST['total'.$c];
					   $saldopen=$_REQUEST['saldo'.$c];
					   if($valorpagado==""){$valorpagado=0;}
					  
					   if($valorpagado<=$saldopen && $valorpagado>0){$pasasaldo=1;} else {$pasasaldo=0;$errrosaldo=1;}
					   if($pasasaldo==1)
					    {
					      $horasistema=date("H:i:s");

						$sql_contar=mysqli_query($conexion,"SELECT count(*) as contar from venta_credito 
								where cliente='".$cliente."'
								and factura='".$factura."'
								and fecsis='".date("Y-m-d")."'
								and hora='".$horasistema."'
								and valor='".$valorpagado."'");
						while($datosrs= mysqli_fetch_row($sql_contar)){ $contar=$datosrs[0];}
						if($contar>=1){}
						else
 						{
					  	  $sql_insert=mysqli_query($conexion,"insert into venta_credito(cliente,factura,valor,fecsis,hora,usuario)
						 							values('".$cliente."','".$factura."','".$valorpagado."',
										'".date("Y-m-d")."','".$horasistema."','".$vg_login."')"); 
						   if($sql_insert)
						     {$paso=1;}
						 }
					    }  						  
					  
					   }//fin valida chequeo
				  $c=$c+1;
			   }//fin cliclo
			 if($paso==1)
			   { /*echo "<script>";   echo "alert('Se registraron los valores pagados del credito')"; echo "</script>";*/
			    ?>				  
						<script>
                            cuteToast({
                                  type: "success", // or 'info', 'error', 'warning', success
                                  message: "Se registraron los valores pagados del credito",
                                  timer: 2000
                                })
                            </script>
                        <?php
			   }
			 if($errrosaldo==1)
			    { /*echo "<script>";   echo "alert('los valores ingresados superan el valor del saldo, verifica por favor')"; echo "</script>";*/
				  ?>				  
						<script>
                            cuteToast({
                                  type: "error", // or 'info', 'error', 'warning', success
                                  message: "los valores ingresados superan el valor del saldo, verifica por favor",
                                  timer: 2000
                                })
                            </script>
                        <?php
				}
	}  		
}


?>
<form name="parametros" method="post" action="" >
  <div id="informes" class="container text-center" style="width:100%;">
    <div class="panel panel-default">
      <div class="panel-heading" align="left">VENTAS CREDITO</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="texto" >
                    <tr> 
                      <td width="107" height="0">Cliente</td>
                      <td width="232" height="0"><div align="left">
                        <input name="cliente" type="text"   id="cliente" value="<?php echo $cliente; ?>" 
                        class="form-control" data-placement="right" title="Digite no Cliente" style="width: 150px" 
								onKeyPress="if(event.keyCode==13){titulo.id();} if(event.keyCode>=48 && event.keyCode<=58){} else {event.keyCode=8;}"
								onFocus="this.style.background='#ccffff'" onBlur="this.style.background='#ffffff'">
                      </div></td>
                      <td width="187" align="left" valign="middle"><input name="buscar" type="submit" id="buscar" value="Buscar Venta" title="Clic para Buscar"  class="btn btn-primary"></td>
                      <td width="171" align="left" valign="middle"><input name='ccliente' type='button'  id='ccliente' value='Buscar Cliente'   class="btn btn-primary"  
						  onClick="javascript:window.open('frm_cliente_buscar.php?preventa=<?php echo $id; ?>&Obuscar=0','Reportekardex','menubar=1,toolbar=0,location=0,directories=0,status=1,scrollbars=1,width=800,height=500');" ></td>
                      <td width="215" align="left" valign="middle"><input name='procesar' type='submit'  id='procesar' value='Procesar Pagos'   class="btn btn-primary"  
						  onClick="oprocesar.value=1;" ></td>
                      <td width="423" align="left" valign="middle">
                      <a href="reporte_excel_creditos.php" class="btn btn-primary">Excel Creditos</a>
<input name='ccliente' type='button'  id='ccliente' value='Calculadora'   class="btn btn-primary"  
						  onClick="javascript:window.open('frm_vc_calculadora.php?cliente=<?php echo $cliente; ?>&Obuscar=1','Pagacliente','menubar=1,toolbar=0,location=0,directories=0,status=1,scrollbars=1,width=800,height=500');" >
                      </td>

                    </tr>
                    <tr> 
                      <td height="1" colspan="6">
                      <div align="left">
                      <?php
						  if($cliente<>"")
					       {
						   
						    if($cliente>0)
							  {	$sql_contar=mysqli_query($conexion,"SELECT count(*) as contar from cliente where id='".$cliente."'");
								while($datosrs= mysqli_fetch_row($sql_contar)){ $contar=$datosrs[0];}
								if($contar>=1)
								{
									$sql_contar=mysqli_query($conexion,"SELECT nombre,direccion,telefono,documento from cliente where id='".$cliente."'");
									while($datosrs= mysqli_fetch_row($sql_contar)){ $nombrec=$datosrs[0];}
								}
							  }	
							 else {$nombrec="";} 
						   
						   
							echo "<center> <table width='100%' border='1' bordercolor='#FFfff' cellpadding='0' cellspacing='0' class='table table-hover'>";
							echo "<tr class='btn-primary'><td colspan='8'><CENTER>DETALLE DE VENTA CLIENTE:".strtoupper($nombrec)."</CENTER></td></tr>";
							echo "<tr>";
							echo "<td width='5%' class='btn-primary'><center></center></td>";
							echo "<td class='btn-primary'><center>No Factura</center></td>";
							echo "<td class='btn-primary'><center>Fecha</center></td>";							
							echo "<td class='btn-primary'><center>Total</center></td>";	
							echo "<td class='btn-primary'><center>Efectivo</center></td>";		
							echo "<td class='btn-primary'><center>Saldo</center></td>";		
							echo "<td class='btn-primary'><center></center></td>";							
							echo "<td class='btn-primary'><center>";
							 echo "<table width='100%' border='0' cellpadding='0' cellspacing='0' >";
							echo " <tr>																					
									  <td align='center' width='30%'>Valor</td>
									  <td  width='30%'>Fec.Pago</td>
									  <td  width='10%'>Hor.Pago</td>
									  </tr>";
							echo "</table>";
							"</td>";							
							echo "</tr>";
					   $efectivopagados="";
					   		if($cliente<>""){$sqlcliente="and cliente='".$cliente."'";}else  {$sqlcliente="";}
							
							 $sql_datos=mysqli_query($conexion,"SELECT factura,fecsis,valor,empresa from credito
													 where id>0
													 $sqlcliente													
													 order by fecsis asc");
								$c=1;	$sumaiva=0; $sumag=0;	$sumaI=0;		$sumacr=0;	 $sumas=0; $efectivopagado=0; $colorpu=""; $valorpagado=0;
							   while ($datos= mysqli_fetch_row($sql_datos))//04e
								  { 
									$factura=$datos[0];									
									$fecha=$datos[1];
									$total=$datos[2];
									$empresa=$datos[3];
									
									$sumacr=$sumacr+$total;
									$efectivopagado=0;
									 $sql_contar=mysqli_query($conexion,"select count(*) as contar from venta_credito 
									 								where factura='".$factura."' and cliente='".$cliente."'"); 
									 while($datosrs= mysqli_fetch_row($sql_contar)){ $contar=$datosrs[0];}
									 if($contar>=1)
									  {
									    $sql_consulta=mysqli_query($conexion,"select sum(valor) as efectivopag from venta_credito 
																			  where factura='".$factura."' and cliente='".$cliente."'");
										while($datosrs= mysqli_fetch_row($sql_consulta)){ $efectivopagado=$datosrs[0];}
									  }
									$saldo=	$total-	$efectivopagado;	
									$sumas=$sumas+$saldo;						 
									 
									 echo "<tr>
											  <td width='5%'>";
											  if($saldo>0)
											   {
											    echo "<div align='center'><input type='checkbox' name='ch$c'>
												       <input name='factura$c' id='factura$c' type='hidden' class='texto'  value='$factura' size='5' readonly>
													   <input name='total$c' id='total$c' type='hidden' class='texto'  value='$total' size='5' readonly>
													   <input name='saldo$c' id='saldo$c' type='hidden' class='texto'  value='$saldo' size='5' readonly><br>
													   <input name='mod' src='../imagenes/guardar.jpg' style='width:30px; height=30px'  type='image' id='mod' value='+' title='Clic para Procesar pagos'   onClick='oprocesar.value=1;' >
													   </div>";
												}
										echo " </td>																					
											  <td>$factura</td>
											  <td>$fecha</td>
											  <td><div align='right'>".number_format($total,0)."</div></td>	
											  <td>
											  <div align='right'>
											  <input name='valorpagado$c' id='valorpagado$c' type='text'  value='$efectivopagados' size='10'
											  class='form-control' data-placement='right'
											   style='text-align: right;width: 140px' 
											   onkeyup='format(this)' onChange='format(this)' onFocus='format(this)' 
											  onKeyPress='return valida(event);'  >
											  </div>
											  <td><div align='right'>".number_format($saldo,0)."</div></td>	
											  </td>										  											 
											  <td align='center'>";
											  ?> 
                                               <img src="../imagenes/imprimir.png" width="50" height="50" alt="Clic para Imprimir"
                                              onClick="javascript:window.open('imprimepos.php?id=<?php echo $factura; ?>&empresa=<?php echo $empresa; ?>','imprimepos','menubar=1,toolbar=0,location=0,directories=0,status=1,scrollbars=1,width=400,height=500');"/>
<img src="../imagenes/informes.png" width="30" height="30" alt="Clic para Imprimir"
                                              onClick="javascript:window.open('imprimepos_cartera.php?cliente=<?php echo $cliente; ?>','imprimepos','menubar=1,toolbar=0,location=0,directories=0,status=1,scrollbars=1,width=400,height=500');"/>

											  <?php
                                              echo "</td>	
											  <td>";
											   echo "<table width='100%' border='1' cellpadding='0' cellspacing='0' class='table table-hover'>";
											   $sql_abonos=mysqli_query($conexion,"select id,valor,fecsis,hora,usuario from venta_credito
											   										where factura='".$factura."' and cliente='".$cliente."'"); 
											 
											  while($datosabono= mysqli_fetch_row($sql_abonos))//04e
								  				{ 
													$id=$datosabono[0];
													$valorpag=$datosabono[1];
													$fecsispag=$datosabono[2];
													$horapag=$datosabono[3];
													$usuario=$datosabono[4];
													echo " </td>																					
														  <td align='right' width='30%'>".number_format($valorpag)."</td>
														  <td  width='30%'>$fecsispag</td>
														  <td  width='10%'>$horapag</td>
														  <td>";
														  ?>
                                                          <img src="../imagenes/imprimir.png" width="30" height="30" alt="Clic para Imprimir"
                                              onClick="javascript:window.open('imprimepos_abono.php?id=<?php echo $factura; ?>&idpago=<?php echo $id;?>','imprimepos','menubar=1,toolbar=0,location=0,directories=0,status=1,scrollbars=1,width=400,height=500');"/>
														  <?php
                                                          echo "</td>
														  </tr>";
												}
												echo "</table>";
											  echo "</td>										 										 
											</tr>";
											$c=$c+1;
								  }	//04
								 
								echo "<tr >";
									  echo "																					
									  <td colspan=3><div align='right'>TOTAL CREDITO</div></td>
									  <td bgcolor='#00CC66'><div align='center'><font size='5'><strong>".number_format($sumacr)."</strong></font></div></td>
									  <td></td>	
									  <td bgcolor='#00CC66'><div align='center'><font size='5'><strong>".number_format($sumas)."</strong></font></div></td>
									</tr>";		
								echo "<tr >";
								echo "</table></center>";
								$canti=$c-1;  
								echo "<input type='hidden' name='canti' value='$canti' readonly size='10'>";				
						   
						   }
						   ?> 
                      </div></td>
                    </tr>
                    <tr> 
                      <td colspan="6"><div align="center">
                        <input name="oprocesar" type="hidden" id="oprocesar">
                          <input name="oculto" type="hidden" id="oculto">
                          <br>
                        </div></td>
                    </tr>
                  </table>
                    
</TD>
                </TR>
            </TBODY>
            </TABLE>
 </div>
</div>  
 
 
<script>
function valida(e){
    tecla = (document.all) ? e.keyCode : e.which;
	//Tecla de retroceso para borrar, siempre la permite
	 if (tecla==8){
        return true;
    }  
	if (tecla==46){
        return true;
    } 
	
	if (tecla==120 || tecla==88){
        return true;
    } 
    // Patron de entrada, en este caso solo acepta numeros
    patron =/[0-9]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}
</script>

  
</form>
<div id="resultado"></div>
</body>
</html>
