<?php	
	session_start();

	if (empty($_POST['usuario'])) {
           $errors[] = "Usuario vacío";
        } else if (
			!empty($_POST['usuario']) 
		){

		include "../config/config.php";//Contiene funcion que conecta a la base de datos
		include "../lib/email.php";
		$usuario=mysqli_real_escape_string($con,(strip_tags($_POST["usuario"],ENT_QUOTES)));
		$nombre=mysqli_real_escape_string($con,(strip_tags($_POST["nombre"],ENT_QUOTES)));
		$apellidos=mysqli_real_escape_string($con,(strip_tags($_POST["apellidos"],ENT_QUOTES)));
		$email=mysqli_real_escape_string($con,(strip_tags($_POST["email"],ENT_QUOTES)));
		$pass_email=mysqli_real_escape_string($con,(strip_tags($_POST["password"],ENT_QUOTES)));
		$password=sha1(md5(mysqli_real_escape_string($con,(strip_tags($_POST["password"],ENT_QUOTES)))));
		$created_at=date("Y-m-d H:i:s");
		//$user_id=$_SESSION['user_id'];
		
		if (isset($_POST['is_admin'])) {
			$is_admin=1;
		}else{
			$is_admin=0;
		}

		$profile_pic="default.png";


		$usuarios=mysqli_query($con, "select * from user where username='$usuario'");
			if (mysqli_num_rows($usuarios)>0) {
				$errors []= "El Usuario Ya existe.";
				
			}else{

				$sql="INSERT INTO user (username,name,lastname, email,password, profile_pic, is_active, is_admin, created_at) VALUES (\"$usuario\", \"$nombre\", \"$apellidos\", \"$email\", \"$password\",\"$profile_pic\", 1, $is_admin,  \"$created_at\")";
				$query_new_insert = mysqli_query($con,$sql);
					if ($query_new_insert){
						$messages[] = "El usuario ha sido ingresado satisfactoriamente.";
							//sleep(1);
							print("<script>window.location='./usuarios.php'</script>");




	//URL BASE
	$url_base_config=mysqli_query($con,"select * from configuration where name='url_base'");
	$rw_url_base=mysqli_fetch_array($url_base_config);
	$url_base=$rw_url_base['val'];

	//enviar email:
	register_user($email_smtp,$password_smtp,$from_name_smtp,$Host_smtp,$Port_smtp,$url_base,     $email,$usuario,$pass_email);

					} else{
						$errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con);
					}
			}
		} else {
			$errors []= "Error desconocido.";
		}
		
		if (isset($errors)){
			
			?>
			<div class="alert alert-danger" role="alert">
				<button type="button" class="close" data-dismiss="alert">&times;</button>
					<strong>Error!</strong> 
					<?php
						foreach ($errors as $error) {
								echo $error;
							}
						?>
			</div>
			<?php
			}
			if (isset($messages)){
				
				?>
				<div class="alert alert-success" role="alert">
						<button type="button" class="close" data-dismiss="alert">&times;</button>
						<strong>¡Bien hecho!</strong>
						<?php
							foreach ($messages as $message) {
									echo $message;
								}
							?>
				</div>
				<?php
			}

?>