KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.4.62
System : FreeBSD fbsdweb2.web.rcn.net 14.1-RELEASE FreeBSD 14.1-RELEASE releng/14.1-n267679-10e31f0946d8 GENERIC amd64
User : www ( 80)
PHP Version : 8.3.8
Disable Function : NONE
Directory :  /domains/logicswapweb/aplicaciones/admon/carrito/fnc/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /domains/logicswapweb/aplicaciones/admon/carrito/fnc/pedido.php
<?php 
	/**
	* Realiza operaciones basicas sobre pedidos.
	*
	* 
	*
	* @autor Geyffer Acosta;
	* @version 1.0
	* @access public
	* @package Carrito
	*/
	class Pedido extends Aplicacion
	{
		/**
		* contains the articles
		* @var array
		* @see Pedido($subDir="/panel_aplicaciones/",$dirSetup="aplicaciones/admon/carrito/")), setPlantillas($pProd), modVinculoWeb($vinc,$est,$nApli)
		*/

		var $util;
		var $fecha_actual;
		var $aplicacion = "carrito";
		var $dirSetup = "/aplicaciones/admon/carrito";
		var $tokenNone="none";
		var $pProductos=''; // plantilla para mostrar los productos de un pedido
		var $pPedido=''; // plantilla para mostrar la informacion general de un pedido
		var $codigo='';

		function Pedido($subDir="/panel_aplicaciones/",$dirSetup="aplicaciones/admon/carrito/")
		{
			$this->Aplicacion();
			$this->fecha_actual = date('Y-m-d');
			$this->util=new Utileria();
			$this->subDir = $subDir;
			$this->dirSetup = $dirSetup;
			srand((double)microtime()*1000000);
			$this->codigo = rand();

		} 
		function randCodigo()
		{
			srand((double)microtime()*1000000);
			$this->codigo = rand();
		}

		/**
		* Asigna documento plantilla para mostrar un pedido.
		*
		* @param string $pPed localizacion del archivo fuente de la plantilla para mostrar un pedido.
		* @return boolean retorna falso si algun error ocurre
		* @access public
		*/
		function setPlantillas($pPed)
		{
			if($pPed)
			{
				$this->pProductos=$pPed;
				return true;
			}else
			{
				$out=trim($this->getMensaje("[250]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"setPlantillas($pPed)",$this->id);
				return false;
			}
		}
		/**
		* Modifica un vinculo de un usuario con la aplicacion carrito de compras.
		*
		* @param string $vinc cadena compuesta por el id del vinculo a modificar y el email del usuario correspondiente separados por "|". ej: 12|[email protected]
		* @param string $est nuevo estado (preactivo, activo, bloqueado)
		* @return boolean retorna falso si algun error ocurre
		* @access public
		*/
		function modVinculoWeb($vinc,$est)
		{
			$vec=explode("|",$vinc);
			$id = $vec[0];

			$sql='';
			if($est=='activo' || $est=='preactivo' || $est=='bloqueado' || $est=='eliminado')
			{
					$sql="update vinculo_web set estado='$est' where usuario_web ='$id' and aplicacion = '$this->id'";
			}else
			{
				$out=trim($this->getMensaje("[252]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"modVinculoWeb($vinc,$est)",$this->id);
				return false;
			}
			if($this->execute($sql))
			{
				if($est=="activo")
				{
					$nms="[094]";
				}else if($est=="bloqueado")
				{
					$nms="[100]";
				}else 
				{
					$nms="[273]";
				}
				$out=$this->getMensaje($nms,"confirmacion")." ".$vec[1];
				$this->setSalida(true,$out,"modVinculoWeb($vinc,$est,$nApli)",$this->id);
				return true;
			}else
			{
				$out=trim($this->getMensaje("[027]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"modVinculoWeb($vinc,$est,$nApli)",$this->id);
				return false;
			}
		}

		/**
		* Elimina un vinculo de un usuario con la aplicacion carrito de compras.
		*
		* @param string $vinc cadena compuesta por el id del vinculo a modificar y el email del usuario correspondiente separados por "|". ej: 12|[email protected]
		* @return boolean retorna falso si algun error ocurre
		* @access public
		*/
		function delSubscripcion($vinc)
		{
			$vec=explode("|",$vinc);
			$id = $vec[0];
			//$sql="delete from vinculo_web where usuario_web='$id' and aplicacion = '$this->id'";
			$sql="update vinculo_web set estado='eliminado' where usuario_web ='$id' and aplicacion = '$this->id'";
			if($this->execute($sql))
			{
					$out=$this->getMensaje("[098]","confirmacion")." ".$vec[1];
					$this->setSalida(true,$out,"delSubscripcion($vinc)",$this->id);
					return true;
			}else
			{
					$out=trim($this->getMensaje("[027]","error")." ".$vec[1]);
					$out.="\\n:Desc: ".trim($this->getException());
					$this->setSalida(false,$out,"delSubscripcion($vinc)",$this->id);
					return false;
			}

		}

		/*
		*funcion listarUsuarios
		*descripcion trae todos los usuarios disponibles
		*			 apli: id de la aplicacion relacionada con los usuarios a listar
		*			 est: estado de los usuarios que se quieren listar
		*/
		function listarUsuarios($apli = false,$inicio,$limite,$class,$nApli,$est, $find='')
		{
		
			if($est=="todos")
			{
					$sql="select  user.id, user.nombres, user.apellidos, user.login, user.email, vinc.estado from usuario_web as user, vinculo_web as vinc where vinc.estado <> 'eliminado' and vinc.usuario_web=user.id and vinc.aplicacion='$apli' order by user.nombres limit $inicio, $limite";
			}else
			{
					$sql="select  user.id, user.nombres, user.apellidos, user.login, user.email, vinc.estado from usuario_web as user, vinculo_web as vinc where vinc.estado <> 'eliminado' and vinc.usuario_web=user.id and vinc.aplicacion='$apli' and vinc.estado='$est' order by user.nombres limit $inicio, $limite";
			}
			if($find)
			{
					    $sql = "select user.id, user.nombres, user.apellidos, user.login, user.email, vinc.estado
						from usuario_web as user, vinculo_web as vinc
					    where vinc.estado <> 'eliminado' and user.id = vinc.usuario_web and vinc.aplicacion='$this->id' and ((user.nombres like '%$find%') or (user.email like '%$find%') or (user.apellidos like '%$find%') or (user.login like '%$find%')) order by user.nombres asc LIMIT $inicio,$limite";
			}
			
			if($this->execute($sql))
			{
				echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("Nombre","nowrap","","");t.AddColumn("Login","nowrap","",""); t.AddColumn("tipo","","center",""); t.AddColumn("Seleccion","","center","");';
				$i=1;
				$j=0;
				if ($this->numRows()>0) 
				{
					while(list($id,$nombre,$apellido,$login,$email,$estado)=$this->fetchRow())
					{
						if($estado!='eliminado')
						{
							if($estado=="bloqueado")
							{
								$imagen="<img src=\"img/usuarioBloqueado.gif\" onClick=\"fncConsultarUsr(\'$id\')\" height=\"15\" width=\"15\">";
							}else
							{
								$imagen="<img src=\"img/usuario.gif\" onClick=\"fncConsultarUsr(\'$id\')\">";
							}
							
							$nombre=ucfirst(strtolower($nombre))." ".ucfirst(strtolower($apellido));
							if(strlen($nombre)>31)
							{
								$nombre=substr($nombre,0,30)."...";
							}
							echo "t.AddLine('$imagen','<!--$nombre--><a class=\"arial12\" onClick=\"fncConsultarUsr(\'$id\')\">$nombre </a>', '<!--$email--><a class=\"arial12\" onClick=\"fncConsultarUsr(\'$id\')\">$email</a>','$login', '<INPUT class=\"radio\" name=\"usuario_$j\" type=\"checkbox\" value=\"$id|$email\">');";
							echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\');\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');"; 
			
							$j++;
						}
					}
					echo "t.WriteRows();";
				} else 
				{
					$out=trim($this->getMensaje("[023]","confirmacion"));
					echo "document.write('<TR><TD colspan=\"4\" align=\"center\"><BR>$out $ests<BR>&nbsp;</TD></TR>');";
				}
				echo "</script>";
				return true;
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				echo "<TR><TD colspan=\"4\" align=\"center\"><BR>$out<BR>&nbsp;</TD></TR>";
				$this->setSalida(false,$out,"listarUsuarios($apli = false,$inicio,$limite,$class,$nApli,$est, $find)",$this->nombre);
				return false;
			}
			
		}
		/*
		funcion cantidadUsuarios
		descripcion devuelve el nuemro de usuarios en esta aplicacion
		*/
		function cantidadUsuarios($nApli, $est, $find='')
		{
			$sql = '';

			if($est=="todos")
			{
					$sql="select  user.id from usuario_web as user, vinculo_web as vinc where  vinc.estado <> 'eliminado' and vinc.usuario_web=user.id and vinc.aplicacion='$this->id' ";
			}else
			{
					$sql="select  user.id from usuario_web as user, vinculo_web as vinc where  vinc.estado <> 'eliminado' and vinc.usuario_web=user.id and vinc.aplicacion='$this->id' and vinc.estado='$est'";
			}
			if($find)
			{
					    $sql = "select user.id, vinc.estado
						from usuario_web as user, vinculo_web as vinc
					    where  vinc.estado <> 'eliminado' and  user.id = vinc.usuario_web and vinc.aplicacion='$this->id' and ((user.nombres like '%$find%') or (user.email like '%$find%') or (user.apellidos like '%$find%') or (user.login like '%$find%'))";
			}
			
			if($this->execute($sql))
			{
				$out=trim($this->getMensaje("[025]","confirmacion"));
				$this->setSalida(true,$out,"cantidadUsuarios($nApli)",$this->nombre);	
				return $this->numRows();
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"cantidadUsuarios($nApli)",$this->nombre);
				return false;
			}
		}




		function listarHistorial($apli = false,$inicio,$limite,$class,$nApli,$est, $find='')
		{
		
			if($est=="todos")
			{
					$sql="select  cp.cliente, cp.nombres, cp.apellidos, count(cp.cliente), cp.email, cp.pais from carrito_pedidos as cp where 1 group by cp.cliente order by cp.nombres limit $inicio, $limite";
			}else
			{
					$sql="select  cp.cliente, cp.nombres, cp.apellidos, count(cp.cliente), cp.email, cp.pais from carrito_pedidos as cp where 1 group by cp.cliente order by cp.nombres limit $inicio, $limite";
			}
			if($find)
			{
					    $sql = "select  cp.cliente, cp.nombres, cp.apellidos, count(cp.cliente), cp.email, cp.pais
						from carrito_pedidos as cp 
					    where ((cp.nombres like '%$find%') or (cp.email like '%$find%') or (cp.apellidos like '%$find%')) group by cp.cliente order by cp.nombres asc LIMIT $inicio,$limite";
			}
			
			if($this->execute($sql))
			{
				echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("Nombre","nowrap","","");t.AddColumn("Login","nowrap","",""); t.AddColumn("tipo","","center",""); t.AddColumn("Seleccion","","center","");';
				$i=1;
				$j=0;
				if ($this->numRows()>0) 
				{
					while(list($id,$nombre,$apellido,$login,$email,$estado)=$this->fetchRow())
					{
						if($estado=="bloqueado")
						{
							$imagen="<img src=\"img/usuarioBloqueado.gif\" onClick=\"fncConsultarUsrHist(\'$id\')\" height=\"15\" width=\"15\">";
						}else
						{
							$imagen="<img src=\"img/usuario.gif\" onClick=\"fncConsultarUsrHist(\'$id\')\">";
						}
						if($estado=="eliminado")
						{
							$imagen="<img src=\"img/usuarioEliminado.gif\" onClick=\"fncConsultarUsrHist(\'$id\')\" height=\"15\" width=\"15\">";
						}
						
						$nombre=ucfirst(strtolower($nombre))." ".ucfirst(strtolower($apellido));
						if(strlen($nombre)>31)
						{
							$nombre=substr($nombre,0,30)."...";
						}
						echo "t.AddLine('$imagen','<!--$nombre--><a class=\"arial12\" onClick=\"fncConsultarUsrHist(\'$id\')\">$nombre </a>', '<!--$email--><a class=\"arial12\" onClick=\"fncConsultarUsrHist(\'$id\')\">$email</a>','$login', '<INPUT class=\"radio\" name=\"historial\" type=\"radio\" value=\"$id\">');";
						echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\');\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');"; 
		
						$j++;
					}
					echo "t.WriteRows();";
				} else 
				{
					$out=trim($this->getMensaje("[275]","confirmacion"));
					echo "document.write('<TR><TD colspan=\"4\" align=\"center\" class=\"$class\" ><BR>$out $ests<BR>&nbsp;</TD></TR>');";
				}
				echo "</script>";
				return true;
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				echo "<TR><TD colspan=\"4\" align=\"center\"><BR>$out<BR>&nbsp;</TD></TR>";
				$this->setSalida(false,$out," listarHistorial($apli = false,$inicio,$limite,$class,$nApli,$est, $find='')",$this->nombre);
				return false;
			}
			
		}
		/*
		funcion cantidadUsuarios
		descripcion devuelve el nuemro de usuarios en esta aplicacion
		*/
		function cantidadUsuariosHistorial($nApli, $est, $find='')
		{
			$sql = '';

			if($est=="todos")
			{
					$sql="select  cp.cliente from carrito_pedidos as cp  where 1 group by cp.cliente";
			}else
			{
					$sql="select  cp.cliente from carrito_pedidos as cp  where 1 group by cp.cliente";
			}
			if($find)
			{
					    $sql = "select cp.cliente
						from  carrito_pedidos as cp 
					    where ((cp.nombres like '%$find%') or (cp.email like '%$find%') or (cp.apellidos like '%$find%')) group by cp.cliente";
			}
			
			if($this->execute($sql))
			{
				$out=trim($this->getMensaje("[025]","confirmacion"));
				$this->setSalida(true,$out,"cantidadUsuariosHistorial($nApli, $est, $find='')",$this->nombre);	
				return $this->numRows();
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"cantidadUsuariosHistorial($nApli, $est, $find='')",$this->nombre);
				return false;
			}
		}

		function getEstadoUsuario($id)
		{
			$sql="select vw.estado from vinculo_web as vw where vw.aplicacion = '$this->id' and vw.usuario_web = '$id'";
			if($this->execute($sql))
			{
				$out=trim($this->getMensaje("[044]","confirmacion"));
				$this->setSalida(true,$out,"getEstadoUsuario($id)",$this->nombre);	
				list($est) = $this->fetchRow();
				
				return $est;
			}else
			{
				$out=trim($this->getMensaje("[027]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"getEstadoUsuario($id)",$this->nombre);
				return false;
			}
		}

		function modPedido($id_pedido, $estado)
		{
			$var = explode("|", $id_pedido);
			$id_pedido = $var[0];
			$sql = "update carrito_pedidos set estado='$estado' where id = '$id_pedido'";
			if($estado == "despachado")
			{
				$date = date('Y-m-d h-i-s');
				$sql = "update carrito_pedidos set estado='$estado', fecha_ent = '".$date."' where id = '$id_pedido'";
			}
			if($this->execute($sql))
			{
				$out=trim($this->getMensaje("[270]","confirmacion"));
				$this->setSalida(true,$out,"mod_pedido($id_pedido, $estado)",$this->nombre);	
				return true;
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"mod_pedido($id_pedido, $estado))",$this->nombre);
				return false;
			}
		}

		function delPedido($id_pedido)
		{
			$var = explode("|", $id_pedido);
			$id_pedido = $var[0];
			$sql = "delete from carrito_linea_venta where pedido = '$id_pedido'";
			
			if($this->execute($sql))
			{
				$sql = "delete from carrito_pedidos where id = '$id_pedido'";
				if($this->execute($sql))
				{
					$out=trim($this->getMensaje("[271]","confirmacion"));
					$this->setSalida(true,$out,"delPedido($id_pedido)",$this->nombre);	
					return true;
				}
			}else
			{
				$out=trim($this->getMensaje("[026]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"delPedido($id_pedido)",$this->nombre);
				return false;
			}
		}
		
		
		function totalPedido($idPedido)
		{
			$var = explode("|", $id_pedido);
			$id_pedido = $var[0];
			$sql = 'select sum(clv.valor*clv.cantidad)
					 from carrito_linea_venta as clv  
					 where  clv.pedido = '. $idPedido .'';
					 
					
			if($this->execute($sql))
			{
				list($cant)=$this->fetchRow();
				$out=trim($this->getMensaje("[102]","confirmacion"));
				return $cant;
			}else
			{
				$out=trim($this->getMensaje("[028]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"totalPedido($idPedido)",'Carrito de compras');
				return false;
			}

		}
		
		function listarPedidos($inicio,$limite,$class,$est,$find,$nApli, $id_cli='')
		{

			if($est=="todos")
			{
				$sql = 'select cp.id, cp.fecha_ing, cp.estado, cp.nombres, cp.apellidos'
					. ' from carrito_pedidos as cp'
					. ' where 1 order by cp.fecha_ing desc LIMIT '.$inicio.','.$limite;
			}else
			{
				$sql = 'select cp.id, cp.fecha_ing, cp.estado, cp.nombres, cp.apellidos'
					. ' from carrito_pedidos as cp'
					. ' where  cp.estado=\''.$est.'\' order by cp.fecha_ing desc LIMIT '.$inicio.','.$limite;
			}
		
	
			if(!empty($find)){
				$sql = 'select cp.id, cp.fecha_ing, cp.estado, cp.nombres, cp.apellidos'
					. ' from carrito_pedidos as cp'
					. ' where ((cp.nombres like \'%'.$find.'%\') or (cp.email like \'%'.$find.'%\') or (cp.apellidos like \'%'.$find.'%\') or (cp.fecha_ing like \'%'.$find.'%\')) order by cp.fecha_ing desc LIMIT '.$inicio.','.$limite;
				$est="find";
			}

			if(!empty($id_cli))
			{
				$sql = 'select cp.id, cp.fecha_ent, cp.estado, cp.fecha_ing'
					. ' from carrito_pedidos as cp'
					. ' where cp.cliente = '.$id_cli.' order by fecha_ing desc LIMIT '.$inicio.','.$limite;

			}
		
			if($this->execute($sql))
			{
				echo '<script>var t = new SortTable("t");t.AddColumn("ico","width=\"20\"","center","");t.AddColumn("Nombre","nowrap","","");t.AddColumn("id_pedido","","center",""); t.AddColumn("fecha1","","center","");t.AddColumn("fecha2","","center",""); t.AddColumn("Seleccion","","center","");';
				$i=1;
				$j=0;
				if ($this->numRows()>0) 
				{
					$array = array();
					while($row=$this->fetchRow())
					{
						$array[] = $row;
					}
					$c = 0;
					while(list($id,$fecha_ing, $estado, $nombre , $apellido)=$array[$c])
					{
						$total = $this->totalPedido($id);
						if(!$total)$total=0;
						$c++;						
						if($estado=="preactivo")
						{
							$imagen="<img src=\"img/pedidos/preactivo.gif\" onClick=\"fncConsultarUsr(\'$id\',true)\">";
						}
						if($estado=="activo")
						{
							$imagen="<img src=\"img/pedidos/activo.gif\" onClick=\"fncConsultarUsr(\'$id\',true)\">";
						}
						if($estado=="despachado")
						{
							$imagen="<img src=\"img/pedidos/despachado.gif\" onClick=\"fncConsultarUsr(\'$id\',true)\">";
						}
						if($estado=="cancelado")
						{
							$imagen="<img src=\"img/pedidos/cancelado.gif\" onClick=\"fncConsultarUsr(\'$id\',true)\">";
						}
						$total = '$ '.number_format($total,2,'.',',');
						$cliente=ucfirst(strtolower($nombre))." ".ucfirst(strtolower($apellido));
						echo "t.AddLine('$imagen',' <a class=\"$class\" onClick=\"fncAccion(\'visualizar\',\'$id\')\">$cliente </a>', '$id', '$fecha_ing','$total', '<INPUT class=\"radio\" name=\"pedido\" type=\"radio\" value=\"$id|$cliente\">');";
						echo "t.AddLineProperties('id=\"tr_$j\" class=\"$class\" align=\"left\" onMouseOver=\"mOvr(this,\'#faff95\',\'tr_$j\');\" onMouseOut=\"mOut(this,\'#FFFFFF\',\'tr_$j\')\"');"; 
		
						$j++;
					}
					echo "t.WriteRows();";
				} else 
				{
					$out = "";
					/*if($est=="todos"){$out=trim($this->getMensaje("[103]","confirmacion"));}
					if($est=="enviado"){$out=trim($this->getMensaje("[104]","confirmacion"));}
					if($est=="pendiente"){$out=trim($this->getMensaje("[105]","confirmacion"));}
					if($est=="find"){$out=trim($this->getMensaje("[106]","confirmacion"));}
					*/
					$out=trim($this->getMensaje("[272]","confirmacion"));
					echo "document.write('<TR><TD colspan=\"5\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>');";
				}
				echo "</script>";
				return $this->numRows();
			}else
			{
				$out=trim($this->getMensaje("[206]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				echo "<TR><TD colspan=\"4\" align=\"center\" class=\"$class\"><BR>$out<BR>&nbsp;</TD></TR>";
				$this->setSalida(false,$out,"listarPedidos($inicio,$limite,$class,$est,$nApli)",$nApli);
				return false;
			}
			
			
			
		} // fin function listarPedidos
		
		/*
		*funcion cantidadPedidos
		*descripcion devuelve el numero pedidos 
		*/
		function cantidadPedidos($est,$find,$ini,$lim,$nApli, $id_cli='')
		{
			if($est=="todos")
			{
				$sql = 'select count(*)'
					. ' from carrito_pedidos as cp'
					. ' where 1';
			}else
			{
				$sql = 'select count(*)'
					. ' from carrito_pedidos as cp'
					. ' where  cp.estado=\''.$est.'\'';
			}
		
	
			if(!empty($find)){
				$sql = 'select count(*)'
					. ' from carrito_pedidos as cp'
					. ' where ((cp.nombres like \'%'.$find.'%\') or (cp.email like \'%'.$find.'%\') or (cp.apellidos like \'%'.$find.'%\') or (cp.fecha_ing like \'%'.$find.'%\'))';
			}

			if(!empty($id_cli))
			{
				$sql = 'select count(*)'
					. ' from carrito_pedidos as cp'
					. ' where  cp.cliente = '.$id_cli;

			}
		
		
			if($this->execute($sql)){
				list($cant)=$this->fetchRow();
				$out=trim($this->getMensaje("[268]","confirmacion"));
				$this->setSalida(true,$out,"cantidadPedidos($est,$find,$ini,$lim,$nApli)",$nApli);
				return $cant;
			}else{
				$out=trim($this->getMensaje("[206]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"cantidadPedidos($est,$find,$ini,$lim,$nApli)",$nApli);
				return false;
			}
		}

		function getPedido($id_pedido)
		{
			$var = explode("|", $id_pedido);
			$id_pedido = $var[0];
			$sql = 'select cp.id, cp.fecha_ing, cp.estado, cp.nombres, cp.apellidos, cp.cliente'
					. ' from carrito_pedidos as cp'
					. ' where cp.id = '.$id_pedido;
			if($this->execute($sql)){
				$ped = array();
				$row = $this->fetchRow();
				$ped['id'] = $row[0];
				$ped['fecha'] = $row[1];
				$ped['estado'] = $row[2];
				$ped['cliente'] = ucfirst($row[3]).' '.ucfirst($row[4]);
				$ped['idCliente'] = $row[5];
				$total = $this->totalPedido($id_pedido);
				if(!$total)$total=0;

				$ped['total'] = $total;
				$out=trim($this->getMensaje("[267]","confirmacion"));
				$this->setSalida(true,$out,"getPedido($id_pedido)",$nApli);
				return $ped;
			}else{
				$out=trim($this->getMensaje("[206]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"getPedido($id_pedido)",$nApli);
				return false;
			}
		}

		function getDetallesPedido($id_pedido)
		{
			$var = explode("|", $id_pedido);
			$id_pedido = $var[0];
			$sql = 'select clv.prod_nombre ,clv.cantidad, clv.valor
					 from carrito_linea_venta as clv 
					 where  clv.pedido = '. $id_pedido;

			if($this->execute($sql)){
				$ped = array();
				while($row = $this->fetchRow())
				{
					$ped[] = $row;
				}
				$out=trim($this->getMensaje("[266]","confirmacion"));
				//$this->setSalida(true,$out,"getDetallesPedido($id_pedido)",$this->nombre);
				return $ped;
			}else{
				$out=trim($this->getMensaje("[205]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"getDetallesPedido($id_pedido)",$this->nombre);
				return false;
			}
		}

		function mostrarPedido($id_pedido, $hist=0, $userMod='')
		{
			$var 		= explode("|", $id_pedido);
			$id_pedido 	= $var[0];
			$detalles 	= $this->getDetallesPedido($id_pedido);
			$info 		= $this->getPedido($id_pedido);
			//echo "esto ques es ?:".$this->pProductos;
			if($info)
			{
				if($this->pProductos)
				{
					$tags = array();
					$tags[] = '[-pedido-]';
					$tags[] = '[-fecha-]';
					$tags[] = '[-cliente-]';
					$tags[] = '[-estado-]';

					$tags[] = '[-producto-]';
					$tags[] = '[-cantidad-]';
					$tags[] = '[-valor-]';
					$tags[] = '[-subtotal-]';
					$tags[] = '[-total-]';

					$values = array();
					$values['[-pedido-]'] = $info['id'];
					$values['[-fecha-]'] = $info['fecha'];
					$values['[-cliente-]'] = $info['cliente'];
					$estado = $info['estado'];
					$listEstado = '<select name="estado" class="listado"  style="width:80px"'.$userMod.' ';
					if($hist == 1)$listEstado .= ' disabled ';
					$listEstado .= '>';
					$listEstado .='<option value="preactivo" ';
					if ($estado=="preactivo")
					{
						$listEstado .=' selected ';
					}
					$listEstado .='>Preactive</option><option value="activo"';
					if ($estado=="activo")
					{
						$listEstado .= ' selected ';
					}
					$listEstado .=' >Active</option><option value="despachado" ';
					if ($estado=="despachado")
					{
						$listEstado .=' selected ';
					}
					$listEstado .='>Shipped</option><option value="cancelado"';
					if ($estado=="cancelado")
					{
						$listEstado .= ' selected ';
					}
					$listEstado .= '>Cancelled</option></select> ';

					$values['[-estado-]'] = $listEstado;

					$values['[-producto-]'] = 0;
					$values['[-cantidad-]'] = 0;
					$values['[-valor-]'] = 0;
					$values['[-subtotal-]'] = 0;
					$values['[-total-]'] = 0;
					
					// se muestran los campos de acuerdo a la plantilla
					$pl = $this->leerPlantilla($this->pProductos);
					$p = explode("[-varios-]", $pl);
					$s = '';
					if($p)
					{					
						$total = 0;	
						$n = count($p); // cada bloque que se mostrara varias veces esta entre dos etiquetas [-varios-]
						for($i=0; $i < $n; $i++)
						{
							if(($i%2) == 0)
							{
								$s.=$this->reemplazar($p[$i], $tags, $values);
							}else
							{	// mostrar varios
								for($j = 0; $j < count($detalles); $j++)
								{
									list($prod, $cant, $valor)=$detalles[$j];
									$values['[-producto-]'] = $prod;
									$values['[-cantidad-]'] = $cant;
									$values['[-valor-]'] = '$ '.number_format( $valor,2,'.',',');
									$subtotal = ($valor*$cant);
									$values['[-subtotal-]'] = number_format( $subtotal,2,'.',',');
									$total += ($valor*$cant);
									$values['[-total-]'] = number_format( $total,2,'.',',');
									$s.=$this->reemplazar($p[$i], $tags, $values);
								}
							}
						}
					}
					echo $s;
				}else
				{
					$out=trim($this->getMensaje("[251]","error"));
					$this->setSalida(true,$out,"listarProductosPedido($id_pedido)",$this->nombre);
					return false;
				}		
			}else
			{
				$out=trim($this->getMensaje("[251]","error"));
				$this->setSalida(true,$out,"listarProductosPedido($id_pedido)",$this->nombre);
				return false;
			}

		} // fin function listarProductosPedido($id_pedido)

		/*
			Lee el archivo plantilla y lo devuelve como una cadena de caracteres
		*/
		function leerPlantilla($file)
		{
			$f = fopen($file, "r");
			$buffer = '';
			if($f)
			{
				while (!feof($f)) {
				   $buffer .= fgets($f, 4096);
				}
				fclose($f);	
			}else
			{
				$out=trim($this->getMensaje("[018]","error"));
				$this->setSalida(true,$out,"leerPlantilla($file)",$this->nombre);
				return false;
			}
			return $buffer;
		}

		function reemplazar($str, $tags, $values)
		{
			$str_copy = $str;
			if($tags && $str && $values)
			{
				$n = count($tags);
				$r = str_replace($tags, $values, $str_copy);
				return $r;

			}else
			{
				$out=trim($this->getMensaje("[250]","error"));
				$out.="\\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"reemplazar($str, $tags, $values)",$this->nombre);
				return false;
			}
		}

		/**
		* Registra un pedido de forma permanente en la bd.
		*
		* @param array $cliente_info contiene los datos de el cliente.
		* @param matrix $prods cada fila contiene el id del producto y la cantidad correspondiente
		* @return boolean retorna falso si algun error ocurre
		* @access public
		*/
		function registrarPedido($cliente_info, $prods, $codigo)
		{

			if($this->codigo == $codigo)
			{
				$this->reactivarDB();
				$cliente_info['estado'] = $this->getEstadoUsuario($cliente_info['id']); // consultamos estado actual del cliente
				/* verificamos que el cliente este activo en esta aplicacion*/
				if($cliente_info['estado'] && $cliente_info['estado'] != 'activo')
				{
					$out=trim($this->getMensaje("[276]","confirmacion"));
					$out.=" \\n:Desc: ".trim($this->getException());
					$this->setSalida(false,$out,"registrarPedido($id_cli, $prods)",$this->nombre);
					return false;
				}
				if(!$prods && count($prods) == 0)
				{
					$out=trim($this->getMensaje("[277]","confirmacion"));
					$out.=" \\n:Desc: ".trim($this->getException());
					$this->setSalida(false,$out,"registrarPedido($id_cli, $prods)",$this->nombre);
					return false;
				}else
				{
					
					$catalogo = new Catalogo();
					if(!$catalogo)
					{
						$out=trim($this->getMensaje("[254]","error"));
						$out.=" \\n:Desc: ".trim($this->getException());
						$this->setSalida(false,$out,"registrarPedido($id_cli, $prods)",$this->nombre);
						return false;
					}
					$id_pedido = 0;
		
					$date = date('Y-m-d h-i-s');
					$hoy = date('Y-m-d');
					$sql = 'insert into carrito_pedidos values (default, "'.$cliente_info['id'].'", "'.$date.'", "null", "preactivo", "'.$cliente_info['nombres'].'", "'.$cliente_info['apellidos'].'", "'.$cliente_info['email'].'", "'.$cliente_info['direccion'].'", "'.$cliente_info['ciudad'].'", "'.$cliente_info['pais'].'", "'.$cliente_info['telefono_fijo'].'", "'.$cliente_info['telefono_movil'].'" )';
		
			
					if($this->execute($sql))
					{
						//echo $sql;
						$i = 0;
						$prods_registrados = 0;
						$id_pedido = $this->insertId();
						while($prods2=$prods[$i])
						{
							$pr++;
							$id_prod =$prods2['id_pro']; 
							$cant=$prods2['cantidad']; 
		
							$producto = $catalogo->getInfoProducto($id_prod);
							if($producto)
							{
								$valor = $producto['valor'];
								// verificamos si el producto esta en promocion
								if($hoy <= $producto['fecha_fin'] && $producto['estado_oferta'] == 'vigente')
								{
									$valor = $producto['valor_oferta'];
								}
		
								$sql = 'insert into carrito_linea_venta values ('.$id_pedido.','.$producto['id'].',"'.$producto['nombre'].'", "'.$producto['referencia'].'",'.$cant.','.$valor.')';
								if($this->execute($sql))
								{
									$prods_registrados++;
								}
							}
		
							$i++;
						}
						//$i++;
						// no se pudo registrar todos los productos
						if($i!=$prods_registrados)
						{
							// borrar los registros q se ingresaron el la bd
							$sql ='delete from carrito_linea_venta where pedido='.$id_pedido;
							$this->execute($sql);
							$sql ='delete from carrito_pedidos where id='.$id_pedido;
							$this->execute($sql);
		
		
		
							$out=trim($this->getMensaje("[253]","error"));
							$out.="\\n:Desc: ".trim($this->getException());
							$this->setSalida(false,$out,"registrarPedido($cliente_info, $prods)",$this->nombre);
							return false;
						}else
						{
							$out=trim($this->getMensaje("[278]","confirmacion"));
							$out.="\\n:Desc: ".trim($this->getException());
							$this->setSalida(true,$out,"registrarPedido($cliente_info, $prods)",$this->nombre);
							return $id_pedido;
						}
	
					}else
					{
						$out=trim($this->getMensaje("[253]","error"));
						$out.="\\n:Desc: ".trim($this->getException());						
						$this->setSalida(false,$out,"registrarPedido($cliente_info, $prods)",$this->nombre);
						return false;
					}
				}
			}else
			{
				$this->mostrarMensaje("Error, codigo invalido.");
			}
		} // fin function registrarPedido

		function mostrarContenidoCarrito($prods, $ruta='')
		{
			arsort($prods);
			if(!$prods || count($prods) <= 0)
			{
				$this->mostrarMensaje("Your Shopping Cart is empty.");
				return false;
			}
			if(!$ruta)$ruta = "./../aplicaciones/admon/carrito/plantillas/itemsPedido.htm";
			$catalogo = new Catalogo();
			if(!$catalogo)
			{
				$out=trim($this->getMensaje("[254]","error"));
				$out.=" \\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"mostrarContenidoCarrito($carrito)",$this->nombre);
				return false;
			}
			$i = 0;
			$productos = array();
			$id_pedido = $this->insertId();

			$tags = array();
			$tags[] = '[-imagen-]';
			$tags[] = '[-producto-]';

			$tags[] = '[-tipo-]';
			$tags[] = '[-parent-]';
			
			$tags[] = '[-referencia-]';
			$tags[] = '[-valor-]';
			$tags[] = '[-cantidad-]';
			$tags[] = '[-subtotal-]';
			$tags[] = '[-id_producto-]';
			$tags[] = '[-total-]';
			$tags[] = '[-codigo-]';

			$values = array();
			$values['[-imagen-]'] 		= '';
			$values['[-producto-]'] 	= '';
			
			$values['[-tipo-]'] 		= '';
			$values['[-parent-]'] 		= '';
		
			$values['[-referencia-]'] 	= '';
			$values['[-valor-]'] 		= '';
			$values['[-cantidad-]'] 	= '';
			$values['[-subtotal-]'] 	= '';
			$values['[-id_producto-]'] 	= '';
			$values['[-total-]'] 		= '';
			$values['[-codigo-]'] 		= $this->codigo;

			$subt = 0;
			$total = 0;

			// se muestran los campos de acuerdo a la plantilla
			$pl = $this->leerPlantilla($ruta);
			$p = explode("[-varios-]", $pl);
			$s='';

			$n = count($p); // cada bloque que se mostrara varias veces esta entre dos etiquetas [-varios-]
			
			for($i=0; $i < $n; $i++)
			{
				if(($i%2) == 0)
				{
					$s.=$this->reemplazar($p[$i], $tags, $values);
				}else
				{	// mostrar varios
					$pr = 0;
					while($prods2=$prods[$pr])
					{
						$id_prod =$prods2['id_pro']; 
						$cant=$prods2['cantidad']; 

						$producto = $catalogo->getInfoProducto($id_prod);
						$imagenes = $catalogo->getImagenes($id_prod);
						if($producto)
						{
							$valor = $producto['valor'];
							// verificamos si el producto esta en promocion
							if($hoy <= $producto['fecha_fin'] && $producto['estado_oferta'] == 'vigente')
							{
								$valor = $producto['valor_oferta'];
							}
							$values['[-producto-]'] 	= $producto['nombre'];

							$values['[-tipo-]'] 		= $producto['tipo'];
							$values['[-parent-]'] 		= $producto['parent'];
							
							$values['[-referencia-]'] 	= $producto['referencia'];
							$values['[-valor-]'] 		= '$ '.number_format( $valor,2,'.',',');
							$values['[-cantidad-]'] 	= $cant;
							$subt = $valor*$cant;
							$total += $subt;
							$values['[-subtotal-]'] 	= '$ '.number_format( $subt,2,'.',',');	
							$values['[-id_producto-]'] 	= $id_prod;	
							$values['[-total-]'] 		= '$ '.number_format( $total,2,'.',',');
							
							$s.=$this->reemplazar($p[$i], $tags, $values);
						}
						$pr++;
					}
				}
			}
			echo $s;
			return true;
		
		} // fin function mostrarContenidoCarrito

		function getContenidoCarrito($prods, $ruta='')
		{
			if(!$prods || count($prods) <= 0)
			{
				$this->mostrarMensaje("There are not products registered.");
				return false;
			}
			if(!$ruta)$ruta = "./../aplicaciones/admon/carrito/plantillas/itemsPedido.htm";
			$catalogo = new Catalogo();
			if(!$catalogo)
			{
				$out=trim($this->getMensaje("[254]","error"));
				$out.=" \\n:Desc: ".trim($this->getException());
				$this->setSalida(false,$out,"mostrarContenidoCarrito($carrito)",$this->nombre);
				return false;
			}
			$i = 0;
			$productos = array();
			$id_pedido = $this->insertId();

			$tags = array();
			$tags[] = '[-imagen-]';
			$tags[] = '[-producto-]';
			$tags[] = '[-referencia-]';
			$tags[] = '[-valor-]';
			$tags[] = '[-cantidad-]';
			$tags[] = '[-subtotal-]';
			$tags[] = '[-id_producto-]';
			$tags[] = '[-total-]';
			$tags[] = '[-codigo-]';

			$values = array();
			$values['[-imagen-]'] = '';
			$values['[-producto-]'] = '';
			$values['[-referencia-]'] = '';
			$values['[-valor-]'] = '';
			$values['[-cantidad-]'] = '';
			$values['[-subtotal-]'] = '';
			$values['[-id_producto-]'] = '';
			$values['[-total-]'] = '';
			$values['[-codigo-]'] = $this->codigo;

			$subt = 0;
			$total = 0;

			// se muestran los campos de acuerdo a la plantilla
			$pl = $this->leerPlantilla($ruta);
			$p = explode("[-varios-]", $pl);
			$s='';

			$n = count($p); // cada bloque que se mostrara varias veces esta entre dos etiquetas [-varios-]
			
			for($i=0; $i < $n; $i++)
			{
				if(($i%2) == 0)
				{
					$s.=$this->reemplazar($p[$i], $tags, $values);
				}else
				{	// mostrar varios
					$pr = 0;
					while($prods2=$prods[$pr])
					{
						$id_prod =$prods2['id_pro']; 
						$cant=$prods2['cantidad']; 

						$producto = $catalogo->getInfoProducto($id_prod);
						$imagenes = $catalogo->getImagenes($id_prod);
						if($producto)
						{
							$valor = $producto['valor'];
							// verificamos si el producto esta en promocion
							if($hoy <= $producto['fecha_fin'] && $producto['estado_oferta'] == 'vigente')
							{
								$valor = $producto['valor_oferta'];
							}
							$values['[-producto-]'] = $producto['nombre'];
							$values['[-referencia-]'] = $producto['referencia'];
							$values['[-valor-]'] = '$ '.number_format( $valor,2,'.',',');
							$values['[-cantidad-]'] = $cant;
							$subt = $valor*$cant;
							$total += $subt;
							$values['[-subtotal-]'] = '$ '.number_format( $subt,2,'.',',');	
							$values['[-id_producto-]'] = $id_prod;	
							$values['[-total-]'] ='$ '.number_format( $total,2,'.',',');	
							$s.=$this->reemplazar($p[$i], $tags, $values);
						}
						$pr++;
					}
				}
			}
			return $s;
		} // fin function mostrarContenidoCarrito


		/*
		La informacionde registro de un cliente debe estar completa a la hora de realizar un pedido,
		los unicos datos que no son necesarios son los telefonos.
		*/
		function informacionCompleta($cliente_info)
		{
			$inf = count($cliente_info);

			for($i=0; $i < $inf; $i++)
			{
				if($cliente_info[$i] == 'NULL' || $cliente_info[$i] == 'null')
				{
					if(! ($cliente_info['telefono_movil'] == $cliente_info[$i]) || !($cliente_info['telefono_fijo'] == $cliente_info[$i])) 
					return false;
				}
			}
			return true;
		}
		
	} // fin clase Pedido 

?>

Anon7 - 2021