<?



$tpl->assign("POST_NOMBRE", $_POST['nombre']);
$tpl->assign("POST_APELLIDO", $_POST['apellido']);
$tpl->assign("POST_EMPRESA", $_POST['empresa']);
$tpl->assign("POST_DIRECCION", $_POST['direccion']);
$tpl->assign("POST_CP", $_POST['cp']);
$tpl->assign("POST_EMAIL", $_POST['email']);
$tpl->assign("POST_TELEFONO", $_POST['telefono']);

if (md5($_POST['norobot']) == $_SESSION['randomnr2'])	{		
		
	if ((isset($_POST['register'])))
			{  
				
						$rand_password = rand_passwd();			
						
						/***VARIABLES POR POST ***/
						
						$vals = count($_POST);
						$tags = array_keys($_POST); // obtiene los nombres de las varibles
						$valores = array_values($_POST);// obtiene los valores de las varibles
						
						// crea las variables y les asigna el valor
																
						for($i=0;$i<$vals;$i++){
							$$tags[$i]=$valores[$i]; 
							$tpl->assign($tags[$i], stripslashes(strip_tags($valores[$i])));
						}
						
						$email = strtolower($email);
						$user_key = md5($email.$fecha);
						

						 /* *** WHMCS XML API Sample Code *** */
						 
							$url = "http://www.afterfuture.net/clientes/includes/api.php"; # URL to WHMCS API file goes here
											$url = "http://www.afterfuture.net/clientes/includes/api.php"; # URL to WHMCS API file goes here
											$username = "zardet"; # Admin username goes here
											$password = "ssbtp=1174"; # Admin password goes here
										 
											 $postfields["username"] = $username;
											 $postfields["password"] = md5($password);
											 $postfields["action"] = "validatelogin";
						
											 $postfields["action"] = "addclient"; 
											 $postfields["firstname"] = $nombre;
											 $postfields["lastname"] = $apellido;
											 $postfields["companyname"] = $empresa;
											 $postfields["email"] = $email;
											 $postfields["address1"] = $direccion;
											 $postfields["city"] = $ciudad;
											 $postfields["state"] = $estado;
											 $postfields["postcode"] = $cp;
											 $postfields["country"] = 'MX';
											 $postfields["phonenumber"] =  $telefono;
											 $postfields["password2"] = $rand_password;
											 $postfields["currency"] = "1";
						 
											 $ch = curl_init();
											 curl_setopt($ch, CURLOPT_URL, $url);
											 curl_setopt($ch, CURLOPT_POST, 1);
											 curl_setopt($ch, CURLOPT_TIMEOUT, 100);
											 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
											 curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
											 $data = curl_exec($ch);
											 curl_close($ch);
										  
									 
									 $data = explode(";",$data);
									 foreach ($data AS $temp) {
									   $temp = explode("=",$temp);
									   $results[$temp[0]] = $temp[1];
									 }			
		
		
									$query = "SELECT * FROM usuarios WHERE usuarios.email = '".$email."' LIMIT 1";
									$verifyuser = $engine->DB->QueryToArray($query);
								
									$user_key = md5($email.$fecha);
								
									if($verifyuser != ''){
										
										$query = "UPDATE usuarios SET 
													nombre			= '".$nombre."',
													empresa			= '".strtoupper($empresa)."',
													email			= '".$email."',
													telefono 		= '".$telefono."', 
													celular 		= '".$celular."', 
													ciudad 			= '".$ciudad."', 
													estado 			= '".$estado."',
													pais			= '".$pais."',
													password		= '".md5($rand_password)."',
													boletin			= '".$boletin."',
													status			= 'registrado',
													user_key		= '".$user_key."',
													fecha_registro	= '".$fecha."'
													WHERE email 	= '".$email."'";
													
										$update = $engine->DB->QueryToArray($query);
				
										}
										else{
											
											$query = "INSERT INTO usuarios (nombre, empresa, email, telefono, celular, ciudad, estado, pais, password, boletin, status, user_key, fecha_registro) 
													   VALUES ('".$nombre."',
														'".strtoupper($empresa)."',
														'".$email."',
														'".$telefono."',
														'".$celular."',
														'".$ciudad."',
														'".$estado."',
														'".$pais."',
														'".md5($rand_password)."',
														'".$boletin."',
														'registrado',
														'".$user_key."',
														'".$fecha."')";
											
											$insert = $engine->DB->QueryToArray($query);  
				
									}
		
		
						if($results["result"]=="success"){
														
							$tpl->assign('USER_KEY', 		$user_key);
							$tpl->assign('USER_EMAIL', 		$email);
							$tpl->assign('USER_PASSWORD', 	$rand_password);
							
							$tpl_registro_mail 		= modulo_html(MODULOS_DIR.'/registro_mail.tpl');
		
							$form_send = $tpl->fetch('string:'.$tpl_registro_mail);
				
							$query = "SELECT * FROM sitios WHERE sitios.id = '".SITIO_ID."'";
							
							$smtp = $engine->DB->QueryToArray($query);
							
							require ($_SERVER['DOCUMENT_ROOT'].'/classes/class.phpmailer.php');
					
							$sitio_titulo	= $smtp[0]['titulo'];
							$mailsender		= $smtp[0]['email'];
							$mailto 		= $email;
							$host_url 		= $smtp[0]['smtp_servidor'];
							$host_puerto 	= $smtp[0]['smtp_puerto'];
							$host_user 		= $smtp[0]['smtp_user'];
							$host_password 	= $smtp[0]['smtp_password'];
							
							$mail = new PHPMailer();
							
							$mail->IsSMTP(); // telling the class to use SMTP
							$mail->Host       = $host_url; // SMTP server
							$mail->Helo		  = $host_url;
							$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
																	   // 1 = errors and messages
																	   // 2 = messages only
							$mail->SMTPAuth   = true;                  // enable SMTP authentication
							if($smtp[0]['smtp_tipo'] == 'google'){
									$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
								}
							$mail->Port       = $host_puerto;          // set the SMTP port for the GMAIL server
							$mail->Username   = $host_user;  		   // GMAIL username
							$mail->Password   = $host_password;        // GMAIL password
							
							$mail->AddReplyTo($mailsender, $sitio_titulo);
							
							$mail->SetFrom($mailsender, $sitio_titulo);
							
							$mail->Subject    = "Confirma tu Registro!";
							
							$mail->AltBody    = "Para ver este mensaje, por favor utilice visualizador compatible con HTML!"; // optional, comment out and test
							
							$mail->MsgHTML($form_send);
							
							$mail->AddAddress($mailto, $nombre);
							
							$mail->Send();
								
							echo '<div class="alert alert-success"><strong>Te Haz Registrado!</strong><br /> En breve recibirás un email con tus datos de acceso y las instrucciones para completar tu registro.</div>';
							
							}
							else{
								
							echo '<div class="alert alert-danger"><strong>Error!</strong><br />'.$results["message"].'</div>';
	
						}
						
						
			}


}
?>

<? if(isset($_GET['verificar'])):?>

		<?
				$tpl->assign("VERIFY_KEY", $_GET['verificar']);
				
				$registro_display		= modulo_html(MODULOS_DIR.'/registro_verify.tpl');
				$tpl->assign("FORM_VERIFY", $tpl->fetch('string:'.$registro_display));
        ?>

    	{$FORM_VERIFY}

<? endif;?>

<? if(isset($_POST['verify'])):?>

		<?
					
						$query = "SELECT * FROM usuarios WHERE usuarios.user_key = '".$_POST['user_key']."' AND usuarios.status = 'registrado' LIMIT 1";
						$verifyuser = $engine->DB->QueryToArray($query);
					
						if($verifyuser != ''){
							
							$query = "UPDATE usuarios SET 
										status			= 'verificado'
										WHERE user_key 	= '".$_POST['user_key']."'";
										
							$update = $engine->DB->QueryToArray($query);
	
								$tpl->assign("FORM_VERIFY", '<div class="alert alert-success"><strong>Haz completado tu Registro!</strong><br /> Ahora puedes acceder como usuario registrado.</div>');
							
							}
						else{
								$tpl->assign("FORM_VERIFY", '<div class="alert alert-danger"><strong>Error de Verificación!</strong><br /> Esta clave no es válida.</div>');
							}

        ?>

    	{$FORM_VERIFY}

<? endif; ?>


<? if(isset($_POST['get_data'])): ?>
		<?

				echo $_GET['var_data'];
				
				switch ($_GET['var_data']) {
					case 'estados':
							$query = "SELECT 
									  world_City.ID,
									  world_City.Name,
									  world_City.CountryCode,
									  world_City.District,
									  world_City.Population
									FROM
									 world_City
									WHERE world_City.CountryCode = '".$_POST['get_data']."'
									GROUP   BY world_City.District";				
									$estados = $engine->DB->QueryToArray($query);
									
									$option_list.= '<option value="">Elige tu Estado</option>';

									if($estados != ''): 
											foreach($estados as $estado){
												$option_list.= '<option value="'.$estado['District'].'"'.$opselect.'>'.utf8_decode($estado['District']).'</option>';
											} 
									endif;
							
									$tpl->assign("RETURN_DATA2", $tpl->fetch('string:'.$option_list));
									?>{$RETURN_DATA2}<?
						break;
					case 'ciudades':
									$query = "SELECT * FROM world_City WHERE world_City.District = '".$_POST['get_data']."' ORDER BY world_City.Name ASC";				
									$ciudades = $engine->DB->QueryToArray($query);
									
									$option_list.= '<option value="">Elige tu Ciudad</option>';

									if($ciudades != ''): 
											foreach($ciudades as $ciudad){
												$option_list.= '<option value="'.$ciudad['Name'].'"'.$opselect.'>'.utf8_decode($ciudad['Name']).'</option>';
											} 
									endif;
									$tpl->assign("RETURN_DATA3", $tpl->fetch('string:'.$option_list));
									?>{$RETURN_DATA3}<?
						break;
				}

        ?>

<? endif; ?>

<?	
	if($_POST['get_data'] == ''):
	
				$query = "SELECT * FROM world_Country ORDER BY world_Country.Name ASC";				
				
				$paises = $engine->DB->QueryToArray($query);
				
				
				$option_list.= '<option value="">Elige tu País</option>';
				$option_list.= '<option value="MEX">MEXICO</option>';
				
				//if($paises != ''): 
//				
//						foreach($paises as $pais){
//							$option_list.= '<option value="'.$pais['Code'].'"'.$opselect.'>'.strtoupper($pais['Name']).'</option>';
//						} 
//				endif;
							
				$tpl->assign("RETURN_DATA1", $tpl->fetch('string:'.$option_list));
	
				$registro_display		= modulo_html(MODULOS_DIR.'/registro_form.tpl');
				$tpl->assign("FORM_REGISTRO", $tpl->fetch('string:'.$registro_display));

	endif;
?>

{$FORM_REGISTRO}