<?php
error_reporting(1); //No mostrar mensajes de errores por version de PHP
date_default_timezone_set('America/Lima');
require_once 'excel/reader.php';
require("class.phpmailer.php");
/*
$username="lq_adm_gestion";//"gesvetco_4045"; 
$password="WINxp512...";//"4045";
$database="lq_db_gestion";//"gesvetco_Sistema";
$connect=mysql_connect("localhost",$username,$password);
//
set_time_limit(0);
///////////////////////////////
@mysql_select_db($database,$connect) or die("<b>Error al momento de intentar conectarse con la Base de Datos</b>");
//////////////////////////////<-SE AGREGO ESTA LINEA
grs("SET NAMES utf8");
*/
$StrHWND="" ;
function GetHW(){
	$Fecha=date("d-m-y");
	$Hora=time();
	$FechaYHora=$Fecha.$Hora;
	return $FechaYHora;
}
if(strlen($_SESSION['SYS_USER_ID'])>0){
	if(strlen($StrHWND)==0){
		$StrHWND=GetHW();
	}
}
//
function GOM($StrId){
	if(strlen($StrId)==0){
		echo "value=\"Guardar\"";
	}else{
		echo "value=\"Modificar\"";
	}
}
//
function DIS($StrId){
	if(strlen($StrId)==0){
		echo "disabled=\"disabled\"";
	}
}	
//
ob_end_clean();
require("fpdf.php");
class PDF extends FPDF
{
	function Footer()
	{// Posici�n: a 1,5 cm del final
	$this->SetY(-15);
	// Arial italic 8
	$this->SetFont('Arial','',8);
	// N�mero de p�gina
	$this->Cell(0,10,'Pag '.$this->PageNo(),0,0,'C');
	}
}
//
function AD($StrItem,$Sel){
	if($Sel==1){
		echo "<option value=\"$StrItem\" selected=\"selected\">$StrItem</option>";
	}else{
		echo "<option value=\"$StrItem\" >$StrItem</option>";
	}		
}
//
function NF($Num,$Nd){
return number_format($Num,$Nd,'.','');
}
function NF2($Num,$Nd){
return number_format($Num,$Nd,'.',',');
}
function GetALM(){
$s="SELECT alm_nombre FROM almacenes 
	WHERE id_almacen>= 0 AND 
	alm_nombre LIKE '".V($_SESSION['SYS_USER_ALM'])."' ORDER BY alm_nombre";
return $s;
}
//
function ListALM($StrAlm){
	$ss="";
	$s="SELECT alm_nombre 
		FROM almacenes 
		WHERE id_almacen>=0 AND 
		alm_nombre LIKE '".V($_SESSION['SYS_USER_ALM'])."' ORDER BY alm_nombre";
	$rs = grs($s);
	while ($r = $rs->fetch_row()){
		if($StrAlm==$r[0]){
			$ss=$ss."<option value=\"$r[0]\" selected=\"selected\">$r[0]</option>";
		}else{
			$ss=$ss."<option value=\"$r[0]\" >$r[0]</option>";
		}
	}
	return $ss;
}
//
function AddJs(){
	echo "
	<script src=\"jquery-1.7.2.min.js\" type=\"text/javascript\"></script>
	<script src=\"jquery.maskedinput.min.js\" type=\"text/javascript\"></script>	
	";
}
//
function cF($H,$W){
	echo "left:50%;top:50%;	margin:-".$H."px 0 0 -".$W."px;";
}
//
function T($Str){
	if($Str=="TODOS" || $Str=="TODAS" || strlen($Str)==0){
		return "%";
	}else{
		return $Str;
	}
}
//
include("n2l.php");
//include("inicializar.php");
include("vbruntime.php");
include("pdf_runtime.php");
//
function PagGet($_StrPag,$StrCmd,$LStrTR,$VP_RegXPag){
$_RESTO=$LStrTR%$VP_RegXPag;
if($_RESTO!=0){
	$LStrTR=$LStrTR+($VP_RegXPag-$_RESTO);
}
if(strlen($_StrPag)==0 || $_StrPag==0 ){
	$_StrPag="1";	
}	
if($StrCmd=="MSig"){
	$_StrPag=$_StrPag +1;	
}
if($StrCmd=="MAnt"){
	$_StrPag=($_StrPag-1);
}
if($StrCmd=="MPri"){
	$_StrPag=1;
}
if($StrCmd=="MUlt"){
	$_StrPag=($LStrTR / $VP_RegXPag);
}
if($_StrPag>0){	
	if($LStrTR >$VP_RegXPag * $_StrPag){
		if(($_StrPag-1)*$VP_RegXPag==$LStrTR){
			$_StrPag=$_StrPag-1;
		}
	}
}
return $_StrPag;
}
//
function PagBtn($LStrTR,$VP_RegXPag,$LStrPag){	
$s="";
$_RESTO=$LStrTR%$VP_RegXPag;
if($_RESTO!=0){
	$LStrTR=$LStrTR+($VP_RegXPag-$_RESTO);
}
if($LStrTR>$VP_RegXPag){
if($LStrPag==1){
$s=$s."<input style=\"width:40px\" name=\"CmdNP\" type=\"button\" id=\"CmdNP\" value=\"|&lt;\"  onclick=\"fPrimero();\" disabled=\"disabled\"/>";
$s=$s."<input style=\"width:40px\" name=\"CmdNA\" type=\"button\" id=\"CmdNA\" value=\"<\"  onclick=\"fAnterior();\" disabled=\"disabled\" />";
}else{
$s=$s."<input style=\"width:40px\" name=\"CmdNP\" type=\"button\" id=\"CmdNP\" value=\"|&lt;\"  onclick=\"fPrimero();\"/>";
$s=$s."<input style=\"width:40px\" name=\"CmdNA\" type=\"button\" id=\"CmdNA\" value=\"<\"  onclick=\"fAnterior();\"/>";
}
if(($LStrPag==floor($LStrTR  /$VP_RegXPag)  ) ){
$s=$s."<input style=\"width:40px\" name=\"CmdNS\" type=\"button\" id=\"CmdNS\" value=\">\"  onclick=\"fSiguiente();\"  disabled=\"disabled\" />";
$s=$s."<input style=\"width:40px\" name=\"CmdNU\" type=\"button\" id=\"CmdNU\" value=\"&gt;|\"  onclick=\"fUltimo();\"  disabled=\"disabled\"/>";				
}else{
$s=$s."<input style=\"width:40px\" name=\"CmdNS\" type=\"button\" id=\"CmdNS\" value=\">\"  onclick=\"fSiguiente();\" />";
$s=$s."<input style=\"width:40px\" name=\"CmdNU\" type=\"button\" id=\"CmdNU\" value=\"&gt;|\"  onclick=\"fUltimo();\"/>";				
}
}
return $s;
}
//
function PagSql($s,$LStrPag,$VP_RegXPag,$LStrTR){	
if($LStrTR<=$VP_RegXPag){
return $s;
}else{
$LStrPag=$LStrPag-1;$StrTemp=$LStrPag * $VP_RegXPag;
return $s." LIMIT $StrTemp,$VP_RegXPag";
}
}
//PRINTER FUNCTION
function Pxy($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;word-wrap:break-word;height:11px;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX\">".$Str."</div>";
return $s."\n";
}
//
function xy($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX\">".$Str."</div>";
echo $s."\n";
}
function xy2($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX2\">".$Str."</div>";
echo $s."\n";
}

function xz($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"display:block;text-align:justify;left:$X"."cm;top:$Y"."cm;width:$A"."cm\"";
$s=$s." class=\"EX\">".$Str."</div>";
echo $s."\n";
}
//
function SER_NUM_EX($StrSerNum,&$STR_SER,&$STR_NUM){
$iHasta=0;
for($i=1;$i<=strlen($StrSerNum);$i++){
if(vbmid($StrSerNum,$i,1)=="-"){
$iHasta=$i;
break;
}
}
$STR_SER=trim(vbmid($StrSerNum,1,$iHasta -1));
$STR_NUM=trim(vbmid($StrSerNum,$iHasta+1,strlen($StrSerNum) - $iHasta));
}
//
function GenId($StrId,$sT){
	$ss="Select Count(*) From $sT";
	$rs = grs($ss);$row = $rs->fetch_row();		
	if($row[0]==0){
	$StrIdEx=1;
	}else{
	$ss="Select Max($StrId) From $sT";
	$rs = grs($ss);$row = $rs->fetch_row();		
	$StrIdEx=$row[0]+1;
	}
	return $StrIdEx;
}
//
function GetTC(){
if(GetC("tipocambio","")==0){
INSERT("tipocambio","'01-01-01',1");		
}
return gn("valor","tipocambio","");
}
//
function GetIGV(){return 18;}
//
function GenGI(){
$ss="Select Max(valor) From gindex";
$rs = grs($ss);$row = $rs->fetch_row();				
$StrIdEx=$row[0]+1;ejt("UPDATE gindex SET valor=valor+1");
return $StrIdEx;	
}
//
function TRIM_EX($s){
	$s=str_replace("'"," ",$s);
	$d=explode(" ",$s);
	$r="";
	for($i=0;$i<count($d);$i++){
		$x=trim($d[$i]);
		if(strlen($x)>0){
			$r=$r." ".$x;
		}
	}	
	return trim($r);
}
//
function V($s){
	if($s==null){
		return "";
	}else{
		return TRIM_EX($s);
	}
}
/*
function V($s){
	if($s==null){
		return "";
	}else{
		$s=str_replace("'"," ",$s);
		return trim($s);
	}
}
*/
function VU($s){
	if($s==null){
		return "";
	}else{
		$s=str_replace("'"," ",$s);
		return TRIM_EX(strtoupper($s));
	}
}
//
function TODOS($StrCer){
if($StrCer=="TODOS"){
echo "<option value=\"TODOS\" 
selected=\"selected\">TODOS</option>";
}else{
echo "<option value=\"TODOS\" >TODOS</option>";
}
}
//
function LIKE($StrV){
	if($StrV=="TODOS" || $StrV=="TODAS" || strlen($StrV)==0){
		return "%";
	}else{
		return $StrV;
	}	
}
//
function VV($StrVar){if($StrVar==null)return "&nbsp;";if(strlen(trim($StrVar))==0)return "&nbsp;";return $StrVar;}
//
function Gss($sC,$sT,$sW)
{return (strlen($sW)>0) ? "Select $sC From $sT Where $sW" : "Select $sC From $sT";}

function gn($sC,$sT,$sW)
{
	$ss=Gss($sC,$sT,$sW);
	$rs = grs($ss);
	$row = $rs->fetch_row();
	return (is_null($row[0])) ? "0" : $row[0];
}

function gs($sC,$sT,$sW)
{
	$ss=Gss($sC,$sT,$sW);
	$rs = grs($ss);
	$row = $rs->fetch_row();
	return (is_null($row[0])) ? "" : $row[0];
}
function GetC($sT,$sW)
{$ss=Gss("count(*)",$sT,$sW);$rs = grs($ss);$row = $rs->fetch_row();return (is_null($row[0])) ? "0" : $row[0];}
//
function GetSO($sC,$sT,$sW,$StrOrden){
$ss="Select $sC From $sT ";
if(strlen($sW)>0)
$ss=$ss." WHERE $sW ORDER BY $StrOrden";		
else
$ss=$ss." ORDER BY $StrOrden";		
$rs = grs($ss);$row = $rs->fetch_row();		
return (is_null($row[0])) ? "" : $row[0];
}
//
function grs($s){
	GLOBAL $CNN;
	$rs = $CNN->grs($s);	
	return $rs;
}

//function ejt($ss){$rs = grs($ss);}
function ejt($ss){
	GLOBAL $CNN;
	return $CNN->ejt($ss);//retorna el numero de filas efectadas
}
//
function DelAll($sT){
	return ejt("DELETE FROM $sT ");
}
//
function INSERT($sT,$StrValues){
	return ejt("INSERT INTO $sT VALUES ($StrValues)");
}
//
function DELETE($sT,$sW){
	return ejt("DELETE From $sT WHERE $sW");
}
//
function UPDATE($sT,$StrValues,$sW){
	return ejt("UPDATE $sT SET $StrValues WHERE $sW");
}
//
function JsMsg($StrMsg,$StrUrl){
	echo "
	<script language='javascript'> 
	alert('$StrMsg'); 
	location.href='$StrUrl';
	</script>
	";
}
//
function JsDir($StrUrl){
	echo "
	<script language='javascript'> 				
	location.href='$StrUrl';
	</script>
	";
}
function JsDirN($StrUrl){
	echo "
	<script language='javascript'> 				
	window.location='$StrUrl';
	</script>
	";
}
//
function SetVar($StrVar,$StrVal){
	if(gn("count(*)","variables","variable='$StrVar'")==0){
		ejt("INSERT INTO variables VALUES ('$StrVar','$StrVal')");
	}else{
		ejt("UPDATE variables SET valor='$StrVal' WHERE variable='$StrVar'");
	}
}
//
function GetVar($StrVar){
	return gs("valor","variables","variable='$StrVar'");
}
//
function IsNumber($StrNum){
if(is_numeric($StrNum))
return true;
else
return false;
}
//
function FCBO_($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N"){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	//
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrCam";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrCam";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function FCBOO_($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	//
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function IsDate($StrFecha){
$StrAnio="20".substr($StrFecha,6,2);
$StrMes=substr($StrFecha,3,2);
$StrDia=substr($StrFecha,0,2);	
if(!is_numeric($StrDia)) return false;
if(!is_numeric($StrMes)) return false;
if(!is_numeric($StrAnio)) return false;	
if (checkdate((int) $StrMes,(int) $StrDia, (int)$StrAnio)){
return true;
}else{
return false;
}
}
//
function ToDate($StrFecha){
if(strlen($StrFecha)==0){
return "1900-01-01";
}else{
$StrAnio="20".substr($StrFecha,6,2);
$StrMes=substr($StrFecha,3,2);
$StrDia=substr($StrFecha,0,2);	
return $StrAnio."-".$StrMes."-".$StrDia;
}
}
//
function GetHoraServer(){
$StrDate=date("r");
return $StrDate;}
function GetHora(){
$StrDate=date("H:i:s");
$StrHor=substr($StrDate,0,2);$StrMin=substr($StrDate,3,2);
$StrSeg=substr($StrDate,6,2);$StrHor=$StrHor;
if(strlen($StrHor)==1){
$StrHor="0".$StrHor;
}
return $StrHor.":".$StrMin.":".$StrSeg;
}
//
function GetHoraAP(){
$StrDate=GetHora();
$StrHor=substr($StrDate,0,2);$StrMin=substr($StrDate,3,2);
$StrSeg=substr($StrDate,6,2);$StrAP="AM";
if($StrHor>=13){
$StrAP="PM";$StrHor=$StrHor - 12;
}
if(strlen($StrHor)==1){
$StrHor="0".$StrHor;
}
return $StrHor.":".$StrMin.":".$StrSeg." ".$StrAP;
}
//
function EnviarEmail($StrTit,$StrAsunto,$StrCliente,$StrEmail,$StrTexto,$StrF1,$StrF2){
$mail = new PHPMailer();	
$mail->Host = "localhost";
$mail->From = "remite@email.com";//Correo de quien esta enviando.
$mail->FromName = $StrTit; //Quien esta enviando esto aparece en la bandeja
$mail->Subject = $StrAsunto; //Titulo del correo aparecen en la bandeja
$mail->AddAddress($StrEmail,$StrCliente);//Nombre 01->cliente ejt. Marco sayas
//$mail->AddAddress("destino2@correo.com","Nombre 02");	
$mail->Body =$StrTexto;
$mail->AltBody = "***";
if(strlen($StrF1)>0 && strlen($StrF2)>0){
$mail->AddAttachment($StrF1,$StrF2);
}
if(strlen($StrF1)>0 && strlen($StrF2)==0){
$mail->AddAttachment($StrF1);
}
if(strlen($StrF1)==0 && strlen($StrF2)>0){
$mail->AddAttachment($StrF2);
}
$mail->Send();
}
//
function VENTAS_GEN_SER_NUM($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$IdVen=gn("MAX(id_venta)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
$StrS=gs("ser","ventas","id_venta=$IdVen");$StrN=gs("num","ventas","id_venta=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function VENTAS_GEN_SER_NUM_MAX($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
$MAX_N=gn("max(inum)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID AND iser=$MAX_S");
//
$IdVen=gn("id_venta","ventas","id_alm=$ALM_ID AND 
id_com=$COM_ID AND iser=$MAX_S AND inum=$MAX_N");
$StrS=gs("ser","ventas","id_venta=$IdVen");
$StrN=gs("num","ventas","id_venta=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function GUIAS_GEN_SER_NUM_MAX($ALM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","guias","id_almacen=$ALM_ID ");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","guias","id_almacen=$ALM_ID ");
$MAX_N=gn("max(inum)","guias","id_almacen=$ALM_ID AND iser=$MAX_S");
$IdVen=gn("id_guia","guias","id_almacen=$ALM_ID AND iser=$MAX_S AND inum=$MAX_N");
$StrS=gs("ser","guias","id_guia=$IdVen");$StrN=gs("num","guias","id_guia=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function COTI_GEN_SER_NUM_MAX($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","cotizaciones","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","cotizaciones","id_alm=$ALM_ID AND id_com=$COM_ID");
$MAX_N=gn("max(inum)","cotizaciones","id_alm=$ALM_ID AND iser=$MAX_S AND id_com=$COM_ID");
$IdVen=gn("id_cotizacion","cotizaciones","id_alm=$ALM_ID AND 
iser=$MAX_S AND inum=$MAX_N AND id_com=$COM_ID");
$StrS=gs("ser","cotizaciones","id_cotizacion=$IdVen");
$StrN=gs("num","cotizaciones","id_cotizacion=$IdVen");
$STR_SER=$StrS;
$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function GetMES($i){
if($i==1) return "Enero";		if($i==2) return "Febrero";if($i==3) return "Marzo";
if($i==4) return "Abril";		if($i==5) return "Mayo";if($i==6) return "Junio";
if($i==7) return "Julio";		if($i==8) return "Agosto";if($i==9) return "Septiembre";
if($i==10) return "Octubre";	if($i==11) return "Noviembre";if($i==12) return "Diciembre";
return "****";}
function FECHA_ADD($lpDias,$lpMeses,$lpAnios){
$Fecha = mktime(0, 0, 0, date("m")+$lpMeses, date("d")+$lpDias, date("Y")+$lpAnios);
$StrFechaA= date("d-m-y", $Fecha);return $StrFechaA;}
function FECHA_DIASEM(){
$fecha= date("Y-m-d");$i = strtotime($fecha);
return jddayofweek(cal_to_jd(CAL_GREGORIAN, date("m",$i),date("d",$i), date("Y",$i)) , 0 );
}
function FECHA_SEM_PD(){
$iDia=(FECHA_DIASEM()-1)* -1;$StrFec=FECHA_ADD($iDia,0,0);
return $StrFec;}
function FECHA_HOY(){return date("d-m-y");}
function STOCK_ADD($IdAlm,$IdPro,$Cant){
if(gn("count(*)","stocks","id_almacen=$IdAlm AND id_producto=$IdPro")==0){
ejt("INSERT INTO stocks VALUES ($IdAlm,$IdPro,$Cant)");
}else{
ejt("UPDATE stocks SET stock=stock + $Cant WHERE id_almacen=$IdAlm AND id_producto=$IdPro");
}}
function STOCK_SUB($IdAlm,$IdPro,$Cant){
if(gn("count(*)","stocks","id_almacen=$IdAlm AND id_producto=$IdPro")==0){
$Cant=$Cant * -1;ejt("INSERT INTO stocks VALUES ($IdAlm,$IdPro,$Cant)");
}else{
ejt("UPDATE stocks SET stock=stock - $Cant WHERE id_almacen=$IdAlm AND id_producto=$IdPro");
}}

//
function gr($t,$w){
	if(strlen($w)==0){
		$ss="SELECT * FROM ".$t;
	}else{
		$ss="SELECT * FROM ".$t." WHERE ".$w;
	}
	$rs=grs($ss);
	$row = $rs->fetch_assoc();	
	return $row;
	
}
//
function PDF_COTI($Id){
$_CxL=90;
$_S=10;
	

$pdf = new PDF('P','mm',A4);
$pdf->AddPage();$pdf->SetFont('courier','B',16);

$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"INREVA S.A.C.",0,1);	
$pdf->SetFont('courier','',10);
$pdf->Cell(0,4,"SUMINISTROS ELECTRONICOS - EQUIPOS Y REPUESTOS ",0,1);	
$pdf->Cell(0,4,"AV. LAS MALVINAS 315 OF. 152",0,1);	


$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,vbl("PROFORMA".vbfill(" ",$_S),$_S)." : ".gs("CONCAT(SER,'-',NUM)","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("FECHA".vbfill(" ",$_S),$_S)." : ".gs("DATE_FORMAT(FEC,'%d-%m-%Y')","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("CLIENTE".vbfill(" ",$_S),$_S)." : ".gs("CLI","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("RUC".vbfill(" ",$_S),$_S)." : ".gs("RUC","vcotizaciones","ID=$Id"),0,1);
$_MON=gs("MON","vcotizaciones","ID=$Id");
if($_MON=="S"){
	$_MON="Soles   (S/.) ";
}else{
	$_MON="Dolares ($) ";
}
$_IIG=gs("IIG","vcotizaciones","ID=$Id");
if($_IIG=="0"){
	$_IIG="Los precios NO incluyen IGV";
}else{
	$_IIG="Los precios incluyen IGV";
}

$pdf->Cell(0,4,vbl("MONEDA".vbfill(" ",$_S),$_S)." : ".$_MON,0,1);	
$pdf->Cell(0,4,vbl("NOTA".vbfill(" ",$_S),$_S)." : ".$_IIG,0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
$_ENC="CODIGO".vbfill(" ",15)." "."DESCRIPCION".vbfill(" ",30)." "."PRECIO"." "."DSCTO"." "."CANT"."  "."IMPORTE";
$pdf->Cell(0,4,$_ENC,0,1);	
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
//
$s="SELECT COD,DES,FORMAT(PR,1),FORMAT(DT,1),KA,FORMAT(IMP,1) FROM vcotizaciones_det WHERE ID=$Id";
$result = grs($s);
while ($row = $result->fetch_row()){
	$_COD=vbl($row[0].vbfill(" ",21),21);
	$_DES=vbl($row[1].vbfill(" ",41),41);
	$_PRE=vbr(vbfill(" ",6).$row[2],6);
	$_DST=vbr(vbfill(" ",5).$row[3],5);
	$_KAN=vbr(vbfill(" ",4).$row[4],4);
	$_IMP=vbr(vbfill(" ",7).$row[5],7);
	$pdf->Cell(0,4,$_COD." ".$_DES." ".$_PRE." ".$_DST." ".$_KAN."  ".$_IMP,0,1);	
}
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
$_TOT="TOTAL : ".gs("FORMAT(TOT,1)","vcotizaciones","ID=$Id");
$pdf->Cell(0,4,vbfill(" ",$_CxL-strlen($_TOT)).$_TOT,0,1);	
//
$_S=20;
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	

$_FDP=vbl("FORMA DE PAGO".vbfill(" ",$_S),$_S)." : ".gs("fdp","cotizaciones_con","");	
$_TDE=vbl("TIEMPO DE ENTREGA".vbfill(" ",$_S),$_S)." : ".gs("tde","cotizaciones_con","");	
$_GAR=vbl("GARANTIA".vbfill(" ",$_S),$_S)." : ".gs("gar","cotizaciones_con","");	
$_VAL=vbl("VALIDES DE OFERTA".vbfill(" ",$_S),$_S)." : ".gs("val","cotizaciones_con","");	
$_STO=vbl("STOCK".vbfill(" ",$_S),$_S)." : ".gs("stock","cotizaciones_con","");	
$pdf->Cell(0,4,$_FDP,0,1);	
$pdf->Cell(0,4,$_TDE,0,1);	
$pdf->Cell(0,4,$_GAR,0,1);	
$pdf->Cell(0,4,$_VAL,0,1);	
$pdf->Cell(0,4,$_STO,0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	

//
$PDF_NAME="Cotizacion".gs("CONCAT(SER,'-',NUM)","vcotizaciones","ID=$Id").".pdf";
$pdf->Output($PDF_NAME);		
return $PDF_NAME;

}

function GenTxt($Nom,$Val){
	return "<input name=\"$Nom\" type=\"hidden\"  id=\"$Nom\" value=\"$Val\" />";
}
/////////////////////////////////////////////////////////////////////////////////////
//
function FCBO($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N"){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrCam";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrCam";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function FCBOO($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function XLS_INVENTARIO($ALM_){	
	$AX_FEC=date("Y-m-d");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('Inventario.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {		
		$COD=V($data->sheets[0]['cells'][$i][1]);
		$COD=str_replace("*","+",$COD);					
		$INV=vbval(V($data->sheets[0]['cells'][$i][6])); 
		//
		if(strlen($COD)==0) break;
		//
		$IDP=gn("id_producto","productos","pro_codigo='$COD'");
		if($IDP>0){
			$STOCK=gn("stock","stocks","id_almacen=$ALM_ AND id_producto=$IDP");
			$AX_ID=GenId("id_ajuste","ajustex");
			$AX_DIF=abs($STOCK - $INV);
			if($AX_DIF!=0){
				if($STOCK>$INV){						
					ejt("INSERT INTO ajustex VALUES ($AX_ID,".
					"'$AX_FEC',$ALM_,$IDP,'Q',$AX_DIF)");
				}else{
					ejt("INSERT INTO ajustex VALUES ($AX_ID,".
					"'$AX_FEC',$ALM_,$IDP,'A',$AX_DIF)");
				}
				ejt("UPDATE stocks SET stock=".$INV." WHERE ".
				"id_producto=$IDP AND id_almacen=".$ALM_);
			}
		}
	}
}
//
function XLS_PRECIOS($ALM_){	
	$AX_FEC=date("Y-m-d");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('inv_precios.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {		
		$COD=V($data->sheets[0]['cells'][$i][1]);
		$COD=str_replace("*","+",$COD);					
		$INV=trim(V($data->sheets[0]['cells'][$i][7])); 
		if(strlen($COD)==0) break;		
		if(strlen($INV)>0){	
			$INV=round(vbval($INV),2);	
			$INV=str_replace(",","",$INV);
			$IDP=gn("id_producto","productos","pro_codigo='$COD'");
			if($IDP>0){
				$ID_PRE=gn("id_pxs","precios",
						   "pxs_id_almacen=$ALM_ AND pxs_id_producto=$IDP");
				if($ID_PRE==0){
					$ID_PRE=GenId("id_pxs","precios");
					ejt("INSERT INTO precios VALUES ($ID_PRE,$ALM_,$IDP,$INV)");					
				}else{
					ejt("UPDATE precios SET pxs_precio=$INV WHERE id_pxs=$ID_PRE");
				}
				
				
			}
		}
	}
}
//
function extension($filename){
    return substr(strrchr($filename, '.'), 1);
}
//
function VCbo($Cbo){
	if(strlen($Cbo)==0)$Cbo="TODOS";
	if($Cbo=="TODOS"){$CboT="%";}else{$CboT=$Cbo;}
	return $CboT;
}
//--------
function VDex($StrDex){
	if(strlen($StrDex)==0){
		$StrDexT="1900-01-01";
	}else{
		if(IsDate($StrDex)==false){
			$StrDexT="1900-01-01";
		}else{
			$StrDexT=ToDate($StrDex);
		}
	}
	return $StrDexT;
}
//--------
function VHax($StrHax){
	if(strlen($StrHax)==0){
		$StrHaxT="2100-01-01";
	}else{
		if(IsDate($StrHax)==false){
			$StrHaxT="2100-01-01";
		}else{
			$StrHaxT=ToDate($StrHax);
		}
	}
	return $StrHaxT;	
}
//---
function PDF_VENTA($Id){
	$_CxL=90;
	$_S=10;
	//
	$pdf = new PDF('P','mm',A4);
	$pdf->AddPage();$pdf->SetFont('courier','B',16);
	//
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,"IMPORTACIONES DEO'S E.I.R.L.",0,1);	
	$pdf->SetFont('courier','',10);
	$pdf->Cell(0,4,"R.U.C. 20548482772",0,1);	
	$pdf->Cell(0,4,"JR. MESA REDONDA NRO. 952 INT. 214 MESA REDONDA (GALERIAS FULL TIENDAS) LIMA - LIMA - LIMA",0,1);	
	//
	$VEN_COM=gs("COM","wis_ventas","ID=$Id");
	//
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,vbl($VEN_COM.vbfill(" ",$_S),$_S)." : ".gs("CONCAT(SER,'-',NUM)","wis_ventas","ID=$Id"),0,1);	
	$pdf->Cell(0,4,vbl("FECHA".vbfill(" ",$_S),$_S)." : ".gs("FEC_","wis_ventas","ID=$Id"),0,1);	
	$pdf->Cell(0,4,vbl("CLIENTE".vbfill(" ",$_S),$_S)." : ".gs("CLI","wis_ventas","ID=$Id"),0,1);
	if($VEN_COM=="FACTURA"){
		$pdf->Cell(0,4,vbl("RUC".vbfill(" ",$_S),$_S)." : ".gs("RUC","wis_ventas","ID=$Id"),0,1);
	}else{
		$pdf->Cell(0,4,vbl("DNI".vbfill(" ",$_S),$_S)." : ".gs("DNI","wis_ventas","ID=$Id"),0,1);
	}
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
	$_ENC="CODIGO".vbfill(" ",15)." "."DESCRIPCION".vbfill(" ",31)." "."  PRECIO"." "."CANT"."  "."   IMPORTE";
	$pdf->Cell(0,4,$_ENC,0,1);	
	$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
	//
	$s="SELECT COD,DES,FORMAT(PRE,2) as PRECIO,CAN,FORMAT(IMP,2) as IMPORTE FROM wis_ventas_det WHERE ID=$Id";
	$result = grs($s);
	while ($row = $result->fetch_assoc()){
		$_COD=vbl($row['COD'].vbfill(" ",21),21);
		$_DES=vbl($row['DES'].vbfill(" ",42),42);
		$_PRE=vbr(vbfill(" ",8).$row['PRECIO'],8);
		$_KAN=vbr(vbfill(" ",4).$row['CAN'],4);
		$_IMP=vbr(vbfill(" ",10).$row['IMPORTE'],10);
		$pdf->Cell(0,4,$_COD." ".$_DES." ".$_PRE." ".$_KAN."  ".$_IMP,0,1);	
	}
	$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
	//
	if($VEN_COM=="FACTURA"){
		$_SUT=NF2(gn("STO","wis_ventas","ID=$Id"),2);
		$_IGV=NF2(gn("IGV","wis_ventas","ID=$Id"),2);
		$_TOT=NF2(gn("TOT","wis_ventas","ID=$Id"),2);
		//
		$_SUT=vbr(vbfill(" ",10).$_SUT,10);
		$_IGV=vbr(vbfill(" ",10).$_IGV,10);
		$_TOT=vbr(vbfill(" ",10).$_TOT,10);
		//
		$_V1=vbr(vbfill(" ",80)."SUB TOTAL    : ",80).$_SUT;
		$_V2=vbr(vbfill(" ",80)."I.G.V. (18%) : ",80).$_IGV;
		$_V3=vbr(vbfill(" ",80)."TOTAL        : ",80).$_TOT;
		//
		$pdf->Cell(0,4,$_V1,0,1);	
		$pdf->Cell(0,4,$_V2,0,1);
		$pdf->Cell(0,4,$_V3,0,1);
	}else{
		$_TOT=NF2(gn("TOT","wis_ventas","ID=$Id"),2);
		$_TOT=vbr(vbfill(" ",10).$_TOT,10);
		$_V3=vbr(vbfill(" ",80)."TOTAL        : ",80).$_TOT;
		$pdf->Cell(0,4,$_V3,0,1);
	}
	//
	$_S=20;
	$pdf->Cell(0,4,"",0,1);	
	$pdf->Cell(0,4,"",0,1);	
	//
	$PDF_NAME=$VEN_COM." ".gs("CONCAT(SER,'-',NUM)","wis_ventas","ID=$Id").".pdf";
	$pdf->Output($PDF_NAME);		
	return $PDF_NAME;

}
/*
if(gn("count(*)","fabricantes","id_fab=0")==0){
	ejt("INSERT INTO fabricantes VALUES (0,'')");
}
if(gn("count(*)","modelos","id_mod=0")==0){
	ejt("INSERT INTO modelos VALUES (0,'','')");
}
*/
function GET_IMG($COD){
	if(strlen($COD)==0){
			$IMG="vacio.png";
	}else{
		if(!is_numeric($COD)){
			$IMG="fotos/".$COD.".png";
			if(!file_exists($IMG)){
				$IMG="vacio.png";
			}
		}else{
			$COD=vbval($COD)*1;
			$IMG="fotos/".$COD.".png";				
			$Z=1;
			$Y=$Y.$IMG."@";
			if(!file_exists($IMG)){
				$IMG="fotos/0".$COD.".png";
				$Z=2;
				$Y=$Y.$IMG."@";
				if(!file_exists($IMG)){
					$IMG="fotos/00".$COD.".png";
					$Z=3;
					$Y=$Y.$IMG."@";
					if(!file_exists($IMG)){
						$IMG="fotos/000".$COD.".png";
						$Z=4;
						$Y=$Y.$IMG."@";
						if(!file_exists($IMG)){
							$IMG="fotos/0000".$COD.".png";								
							$Z=5;
							$Y=$Y.$IMG."@";
							if(!file_exists($IMG)){
								$IMG="vacio.png";
							}
						}
					}
				}
			}
		}
	}		
	return $IMG;
}
//
function TRIW($s){
	$ss="";
	for($i=1;$i<=strlen($s);$i++){
		$l=vbmid($s,$i,1);
		if($l==" "){
			$ss=trim($ss)." ";
		}else{
			$ss=$ss.$l;
		}
	}
	return trim($ss);
}
//
function STR_OK($s){
	$ss="";
	for($i=1;$i<=strlen($s);$i++){
		$l=vbmid($s,$i,1);
		if($l==" "){
			$ss=trim($ss)." ";
		}else{
			$ss=$ss.$l;
		}
	}
	return trim($ss);
}
function GET_NUMBER($s){
	if(strlen($s)==0){
		return 0;
	}else{
		$s=STR_OK($s);
		$l=explode(" ",$s);		
		if(count($l)==0){
			return 0;
		}else{
			for($i=0;$i<count($l);$i++){
				if(is_numeric($l[$i])){
					return vbval($l[$i]);
				}
			}
		}
		return 0;
	}
}

function V8($_BUF){
	if($_BUF==null){
		return "";
	}else{
		$_BUF = mb_convert_encoding($_BUF, 'UCS-2LE', 'UTF-8'); 
		//FALTA &	
		$_CES= array("?","�","\n","\t","\r","\n|\r","\"","\'","\\","%","'","�");
		$_BUF=str_replace($_CES," ",$_BUF);
		//
		$_LE1=array("�","�","�","�","�","�","�","�","�","�","�","�");
		$_LE2=array("a","e","i","o","u","A","E","I","O","U","N","n");
		$_BUF=str_replace($_LE1,$_LE2,$_BUF);
		$_BUF=str_replace($_LE1,$_LE2,$_BUF);
		//
		$_BUF=trim($_BUF,"[\n|\r|\n\r|\t]");		
		$_BUF = mb_convert_encoding($_BUF,'UTF-8', 'UCS-2LE'); 
		return $_BUF;
	}
}
//
function GW($STR_DES,$STR_CAM){
	$FF=STR_OK(str_replace("@","+",$STR_DES));		
	$LL=explode(" ",$FF);
	$WW="";
	if(count($LL)>0){
		for($i=0;$i<count($LL);$i++){
			if(strlen(trim($LL[$i]))>0){
				$WW=$WW." ".$STR_CAM." LIKE '%".$LL[$i]."%' AND";
			}
		}
	}
	//
	if(strlen($WW)>0){
		$WW="(".vbmid($WW,1,strlen($WW)-3).")";
	}else{
		$WW=$STR_CAM." LIKE '%".$Des."%'";
	}
}
//**------------------------------------------------------------------------
function D($StrDex){
	if(strlen($StrDex)==0){
		$StrDexT="1900-01-01";
	}else{
		if(IsDate($StrDex)==false){
			$StrDexT="1900-01-01";
		}else{
			$StrDexT=ToDate($StrDex);
		}
	}
	return $StrDexT;
}
//**------------------------------------------------------------------------
function H($StrHax){
	if(strlen($StrHax)==0){
		$StrHaxT="2100-01-01";
	}else{
		if(IsDate($StrHax)==false){
			$StrHaxT="2100-01-01";
		}else{
			$StrHaxT=ToDate($StrHax);
		}
	}
	return $StrHaxT;	
}
//**------------------------------------------------------------------------
function Ex($filename){
    return substr(strrchr($filename, '.'), 1);
}
//**------------------------------------------------------------------------

//**------------------------------------------------------------------------
function ImgA($P){
	$F1=$P.".jpg";
	$F2=$P.".png";
	$F3=$P.".gif";
	//
	if (file_exists($F1)){$FO=$F1;}
	if (file_exists($F2)){$FO=$F2;}
	if (file_exists($F3)){$FO=$F3;}
	//
	return $FO;	
}
//**------------------------------------------------------------------------
function ImgE($Img){
	unlink($Img);
}
//**------------------------------------------------------------------------
//**------------------------------------------------------------------------
//**------------------------------------------------------------------------
//**------------------------------------------------------------------------
function LP_GET_PLAN_EX($s){
	if(strlen(trim($s))==0){
		return 0;
	}
	$z=explode(" ",$s);
	$t=count($z);
	if($t==0){
		return 0;
	}
	for($i=0;$i<$t;$i++){
		if(is_numeric($z[$i])){
			return vbval($z[$i]);
		}
	}
	return 0;
}
//**------------------------------------------------------------------------
function LP_PLN_ADD($PLN){
	$PRE=LP_GET_PLAN_EX($PLN);
	$Hab="SI";
	$MinNac="-";
	$SmsNac="-";
	$GbNac="-";
	$MinInt="-";
	$SmsInt="-";
	$GbInt="-";
	$GbAv="-";
	$GbFc="-";
	$GbTe="-";
	$GbBo="-";
	//
	$Id=GenId("id_pln","planes");
	$s="INSERT INTO planes 
		VALUES ($Id,'$PLN',$PRE,'$Hab','$MinNac',
		'$SmsNac','$GbNac','$MinInt','$SmsInt',
		'$GbInt','$GbAv','$GbFc','$GbTe','$GbBo')";
	ejt($s);
	return $Id;	
}
//**------------------------------------------------------------------------
function LP_PLN_GET_ID($DES,$ACTUALIZAR){
	$CX=gn("id_pln","planes","pln_nom='$DES'");
	if($CX>0){
		return $CX;
	}else{
		if($ACTUALIZAR!="SI"){
			return 0;
		}else{
			return LP_PLN_ADD($DES);
		}
	}
}
//**------------------------------------------------------------------------
function LP_PLN_GET_ID_EX($PRE){
	$CX=gn("id_pln","planes","pln_pre=$PRE");
	return $CX;
}
//**------------------------------------------------------------------------
function LP_PRO_ADD($DES){
	$DAT=explode(" ",$DES);
	$MAR=$DAT[0];
	$MAR_ID=gn("id_mar","marcas","mar_nom='$MAR'");
	if($MAR_ID==0){
		$MAR_ID=GenId("id_mar","marcas");
		$s="INSERT INTO marcas VALUES ($MAR_ID,'$MAR','','SI')";
		ejt($s);
	}
	//
	$Cod="";
	$Mar_=$MAR_ID;
	$Noc="";
	$Nol=$DES;
	$Hab="SI";
	$Ram_=0;
	$Bat_=0;
	$Cpr_=0;
	$Cfr_=0;
	$Tam_=0;
	$pro_fot1="";
	$pro_fot2="";
	$pro_fot_des="";
	$pro_fly1="";
	$pro_fly2="";
	$pro_fly3="";
	$pro_vid_est1="";
	$pro_vid_est2="";
	$pro_vid_ins1="";
	$pro_vid_ins2="";
	$pro_pdf="";
	//
	$FILE="";
	$Id=GenId("id_pro","productos");
	$Kod=vbr("000000".$Id,6);
	$s="INSERT INTO productos 
		VALUES ($Id,'$Kod','$Cod',$Mar_,'$Noc',
		'$Nol','$Hab',$Ram_,$Bat_,$Cpr_,$Cfr_,$Tam_,
		'$FILE','$pro_fot1','$pro_fot2','$pro_fot_des',
		'$pro_fly1','$pro_fly2','$pro_fly3',
		'$pro_vid_est1','$pro_vid_est2',
		'$pro_vid_ins1','$pro_vid_ins2','$pro_pdf')";
	ejt($s);
	//
	$s."<br>";
	//
	return $Id;
}
//**------------------------------------------------------------------------
function LP_PRO_GET_ID($DES,$ACTUALIZAR){
	$CX=gn("id_pro","productos","pro_nol='$DES'");
	if($CX>0){
		return $CX;
	}else{
		if($ACTUALIZAR!="SI"){
			return 0;
		}else{
			return LP_PRO_ADD($DES);
		}
	}
}
//**------------------------------------------------------------------------
function TU($s){
	return trim(strtoupper($s));
}
//**------------------------------------------------------------------------
function DELETE_FILE($StrFile){
	if(file_exists($StrFile)){
		unlink ($StrFile);
	}
}
//---------------------------------------------------------------------------
function PID(&$StrId,$GET_ID,&$StrCmd,&$LStrPag,$GET_PAG){
	if(strlen($StrId)==0){
		$StrId=$GET_ID;
		if(is_numeric($StrId)==false){
			$StrId="";		
		}else{
			$StrCmd="AR";
			$LStrPag=$GET_PAG;
			if(!is_numeric($LStrPag)){
				$LStrPag="";
			}
		}
	}
}
//
function dex_($StrDex){
	if(strlen($StrDex)==0){
		$StrDexT="1900-01-01";
	}else{
		if(IsDate($StrDex)==false){
			$StrDexT="1900-01-01";
		}else{
			$StrDexT=ToDate($StrDex);
		}
	}
	return $StrDexT;
}
//
function hax_($StrHax){
	if(strlen($StrHax)==0){
		$StrHaxT="2100-01-01";
	}else{
		if(IsDate($StrHax)==false){
			$StrHaxT="2100-01-01";
		}else{
			$StrHaxT=ToDate($StrHax);
		}
	}
	return $StrHaxT;	
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function USU_PER_SET($USU,$ACC,$SON){
	$USU=vbval($USU);
	if(strlen($SON)==0)$SON="NO";
	//
	$CX=gn("id_up","usuarios_permisos","up_id_usu=$USU AND up_accion='$ACC'");
	if($CX>0){
		$s="UPDATE usuarios_permisos SET up_son='$SON' WHERE id_up=$CX";
		ejt($s);
	}else{
		$ID=GenId("id_up","usuarios_permisos");
		$s="INSERT INTO usuarios_permisos VALUES ($ID,$USU,'$ACC','$SON')";
		ejt($s);
	}
}
function USU_PER_GET($USU,$ACC){
	$USU=vbval($USU);
	$CX=gn("id_up","usuarios_permisos","up_id_usu=$USU AND up_accion='$ACC'");
	if($CX>0){
		return gs("up_son","usuarios_permisos","id_up=$CX");
	}else{
		return "NO";
	}
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
function MI_IP(){
	if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
	$ip = getenv("HTTP_CLIENT_IP");
	}
	elseif(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
	$ip = getenv("HTTP_X_FORWARDED_FOR");
	}
	elseif(getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
	$ip = getenv("REMOTE_ADDR");
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
	
	$ip = $_SERVER['REMOTE_ADDR'];
	}
	else {
	$ip = "Unknown";
	}
	return $ip;
}
function BIT_ADD($MNU,$MOD,$ACC,$MOD_ID,$SQL_CAB,$SQL_DET,$PHP){
	$ID=GenId("id_bit","bitacora");
	$USU_ID=vbval(V($_SESSION['SYS_USER_ID']));
	$USU=gs("nom","usuarios","id_usuario=$USU_ID");
	$IP=MI_IP();
	$FEC=date("Y-m-d");
	$HOR=GetHoraAP();
	$SES_ID=V($_SESSION['SYS_HW']);
	$SQL_CAB=str_replace("'","@",$SQL_CAB);
	$SQL_DET=str_replace("'","@",$SQL_DET);
	//
	$SQL_CAB=str_replace("\n"," ",$SQL_CAB);
	$SQL_DET=str_replace("\n"," ",$SQL_DET);
	$s="INSERT INTO bitacora 
		VALUES ($ID,$USU_ID,'$FEC','$HOR','$IP','$MNU',
		'$MOD','$ACC','$MOD_ID','$SQL_CAB','$SQL_DET','$USU','$SES_ID','$PHP')";
	ejt($s);
	return $ID;
}
function BIT_DET_ADD($BIT_ID,$SQL){
	$SQL=str_replace("'","@",$SQL);
	$SQL=str_replace("\n"," ",$SQL);
	$ID=GenId("id_bd","bitacora_det");
	$s="INSERT INTO bitacora_det VALUES ($ID,$BIT_ID,'$SQL')";
	ejt($s);
	
}
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function numberToWords($number) {
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0                   => 'zero',
        1                   => 'one',
        2                   => 'two',
        3                   => 'three',
        4                   => 'four',
        5                   => 'five',
        6                   => 'six',
        7                   => 'seven',
        8                   => 'eight',
        9                   => 'nine',
        10                  => 'ten',
        11                  => 'eleven',
        12                  => 'twelve',
        13                  => 'thirteen',
        14                  => 'fourteen',
        15                  => 'fifteen',
        16                  => 'sixteen',
        17                  => 'seventeen',
        18                  => 'eighteen',
        19                  => 'nineteen',
        20                  => 'twenty',
        30                  => 'thirty',
        40                  => 'forty',
        50                  => 'fifty',
        60                  => 'sixty',
        70                  => 'seventy',
        80                  => 'eighty',
        90                  => 'ninety',
        100                 => 'hundred',
        1000                => 'thousand',
        1000000             => 'million',
        1000000000          => 'billion',
        // Add more if needed
    );

    if (!is_numeric($number)) {
        return false;
    }

    if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) {
        // Overflow
        trigger_error(
            'numberToWords only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
            E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . numberToWords(abs($number));
    }

    $string = '';

    $fraction = null;
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }

    $number = (int)$number;

    $levels = array(
        1000000000 => 'billion',
        1000000    => 'million',
        1000       => 'thousand',
        100        => 'hundred',
    );

    foreach ($levels as $value => $name) {
        if ($number >= $value) {
            $count = (int)($number / $value);
            $number %= $value;
            $string .= numberToWords($count) . ' ' . $name . $separator;
        }
    }

    if ($number > 0) {
        if ($string != '') {
            $string .= $conjunction;
        }

        if ($number < 21) {
            $string .= $dictionary[$number];
        } else {
            $tens = ((int)($number / 10)) * 10;
            $units = $number % 10;
            $string .= $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
        }
    }

    $string = rtrim($string, $separator);

    if ($fraction !== null) {
        $string .= $decimal;
        $digits = str_split((string)$fraction);
        foreach ($digits as $digit) {
            $string .= $dictionary[$digit] . ' ';
        }
        $string = rtrim($string);
    }

    return $string;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function fxTraducir($NUM){
	$NUM=trim($NUM);
	$NUM=str_replace(",","",$NUM);
	$DEC="00";
	if(strpos($NUM,".")===false){
		//
	}else{
		$DAT=explode(".",$NUM);
		$NUM=trim($DAT[0]);
		$DEC=trim($DAT[1]);				
	}
	$LET=strtoupper(numberToWords($NUM));
	$LET=str_replace(","," ",$LET);
	if(vbval($NUM)==1){
		$LET=$LET." DOLLAR AND ".$DEC."/100";
	}else{
		$LET=$LET." DOLLARS AND ".$DEC."/100";
	}
	return $LET;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function fxTraducirLQ($NUM){
	$NUM=trim($NUM);
	$NUM=str_replace(",","",$NUM);
	$DEC="0";
	if(strpos($NUM,".")===false){
		//
	}else{
		$DAT=explode(".",$NUM);
		$NUM=trim($DAT[0]);
		$DEC=trim($DAT[1]);				
	}
	$LET=strtoupper(numberToWords($NUM));
	$LET=str_replace(","," ",$LET);
	if(vbval($DEC)==0){
		return $LET;
	}else{
		$LET_DEC=strtoupper(numberToWords($DEC));
		$LET_DEC=str_replace(","," ",$LET_DEC);
		return $LET." POINT ".$LET_DEC;
	}
}

//XML XML XML XML XML XML XML XML XML XML XML XML XML XML
//XML XML XML XML XML XML XML XML XML XML XML XML XML XML

function FEP($fecha){
	if(strlen($fecha)==0){
		return "";
	}else{
		if(strcmp($fecha,"1900-01-01")==0){
			return "";
		}else{
			$d=explode("-",$fecha);
			if(count($d)==0){
				return "";
			}else{
				if(strlen($d[2])==4){
					return $fecha;
				}else{
					return $d[2]."-".$d[1]."-".$d[0];
				}
			}
		}
	}
}
//
function ToDateEx($StrFecha){
	if(strlen($StrFecha)==0){
		return "1900-01-01";
	}else{
		$StrAnio=substr($StrFecha,6,4);
		$StrMes=substr($StrFecha,3,2);
		$StrDia=substr($StrFecha,0,2);	
		return $StrAnio."-".$StrMes."-".$StrDia;
	}
}


function ejt7($ss){
	GLOBAL $CNN;
	return $CNN->ejt7($ss);//retorna el id generado
}
//
function TU26($s){
	$s=str_replace("'","",$s);
	return trim(strtoupper($s));
}
//
function XML_EMP_ADD($RUC,$NOM,$RET='NO'){
	$XYZ=gn("id","ges_xml_empresas","emp_ruc='$RUC'");
	if($XYZ==0){
		$XYZ="INSERT INTO ges_xml_empresas (emp_ruc , emp_nom , emp_age) VALUES ('$RUC','$NOM','$RET')";
		ejt($XYZ);
	}else{
		if(func_num_args()==3){
			$s="UPDATE ges_xml_empresas SET emp_age='$RET' WHERE id=".$XYZ;
			ejt($s);
		}
	}
}
//
function XML_MND_ADD($MND){
	$XYZ=gn("id","ges_xml_mnd","nom='$MND'");
	if($XYZ==0){
		$XYZ="INSERT INTO ges_xml_mnd (nom) VALUES ('$MND')";
		ejt($XYZ);
	}
}
//
function XmlIsDate($StrFecha){
	$StrFecha=str_replace("/","-",$StrFecha);
	$D=explode("-",$StrFecha);
	if(count($D)!=3){
		return false;
	}
	$StrAnio=$D[2];
	$StrMes=$D[1];
	$StrDia=$D[0];
	//
	if(strlen($StrAnio)<4)return false;
	//
	if(!is_numeric($StrDia)) return false;
	if(!is_numeric($StrMes)) return false;
	if(!is_numeric($StrAnio)) return false;	
	if (checkdate((int) $StrMes,(int) $StrDia, (int)$StrAnio)){
		return true;
	}else{
		return false;
	}
}
function Xmldex_($StrDex){
	if(strlen($StrDex)==0){
		$StrDexT="1900-01-01";
	}else{
		if(XmlIsDate($StrDex)==false){
			$StrDexT="1900-01-01";
		}else{
			$StrDexT=ToDateEx($StrDex);
		}
	}
	return $StrDexT;
}
//
function Xmlhax_($StrHax){
	if(strlen($StrHax)==0){
		$StrHaxT="2100-01-01";
	}else{
		if(XmlIsDate($StrHax)==false){
			$StrHaxT="2100-01-01";
		}else{
			$StrHaxT=ToDateEx($StrHax);
		}
	}
	return $StrHaxT;	
}
//++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++
function XML_FAC_SET_PAG($KEY){
	$CAN_PEN=gn("count(*)","ges_xml_cuo",
				"id_cuo=$KEY AND cuo_anu='NO' AND cuo_tot_pag>0 AND cuo_pag_tot=0");
	$RET_PEN=gn("count(*)","ges_xml_cuo",
				"id_cuo=$KEY AND cuo_anu='NO' AND cuo_tot_ret>0 AND cuo_ret_tot=0");
	if($CAN_PEN==0 && $RET_PEN==0){
		$s="UPDATE ges_xml SET xml_pagado='SI' WHERE id_xml=$KEY";
	}else{
		$s="UPDATE ges_xml SET xml_pagado='NO' WHERE id_xml=$KEY";
	}
	ejt($s);
}
function XML_FAC_SET_PAG_EX($KEY){
	$CAL_TOT_FAC=gn("xml_tot","ges_xml","id_xml=$KEY");
	$CAL_TOT_CUO=gn("SUM(cuo_tot)","ges_xml_cuo","cuo_anu='NO' AND id_xml=$KEY");
	$CAL_TOT_PAG=gn("SUM(cuo_pag_tot + cuo_ret_tot)","ges_xml_cuo","cuo_pag='SI' AND id_xml=$KEY");	
	$CAL_PAG="NO";
	if($CAL_TOT_PAG>=$FAC_TOT){
		$CAL_PAG="SI";
	}
	//
	$s="UPDATE ges_xml 
		SET xml_tot_cuo=$CAL_TOT_CUO , 
			xml_tot_pag=$CAL_TOT_PAG ,
			xml_pagado='$CAL_PAG'
		WHERE id_xml=$KEY";
	ejt($s);
}
function XML_LOTE_GEN(){
	$HOY=date("Y-m-d");
	$HOY_COD=date("dmy");
	$CX=gn("cx","ges_xml_lotes","fec_cod='$HOY_COD'");
	if($CX==0){
		$KEY=GenId("id_lote","ges_xml_lotes");
		$s="INSERT INTO ges_xml_lotes VALUES ($KEY,'$HOY','$HOY_COD',0)";
		ejt($s);
		//
		return $HOY_COD."-01";
	}
	$CX=$CX+1;
	return $HOY_COD."-".vbr("00".$CX,2);

}
function XML_LOTE_ACT(){
	$HOY_COD=date("dmy");
	$s="UPDATE ges_xml_lotes SET cx=cx+1 WHERE fec_cod='$HOY_COD'";
	ejt($s);
}
//
function ParseFec($f){
	$D=explode("-",$f);
	$DIA=$D[2];
	$MES=$D[1];
	$ANI=$D[0];
	return $DIA."-".$MES."-".$ANI;
}
//
function EjtEx($ss){
	GLOBAL $CNN;
	return $CNN->EjtEx($ss);//retorna el id generado
}

?>