<?php
	require_once("../../classes/main_classes.php");

	//OBJECTS
	$retrieveObj=new RETRIEVE();
	$insertObj=new INSERT();
	$rowcountObj=new ROWCOUNT();
	$updateObj=new UPDATE();
	$deleteObj=new DELETE();
	$root_dir_getObj=new ROOTDIRGET();
	$sendemailObj=new SEND_EMAIL();
	
	$mailer_r_path="../../";


	//get root dir
	$root_dir=$root_dir_getObj->root_dir_getter();


	if(isset($_POST["setup_admin_account_note"])){
		//set roles
		$roles=array("su_admin","admin");
		//$roles=array("su_admin","admin","customer"); FOR FUTURE UPDATES
		for ($i=0; $i <count($roles) ; $i++) { 
			//insert roles
				//check if role exist
				if(!($rowcountObj->rowcounter("user_role","*","user_role",$roles[$i])>0)){
					$insert_role_field=array("user_role");
					$insert_role_data=array($roles[$i]);

					$insert_role=$insertObj->inserter("user_role",$insert_role_field,$insert_role_data);
					if($insert_role!="1"){
						die(0);
					}
				}		
		}

		$get_role_id=$retrieveObj->retriever("user_role","*","user_role","su_admin","fetch");
		//check if there is already an admin
		$check_admin=$retrieveObj->retriever("users 
			JOIN user_roles ON user_roles.user_id=users.user_id
			JOIN user_role ON user_roles.role_id=user_role.role_id","*","user_roles.role_id",$get_role_id->role_id,"fetch");
		
		if($check_admin=="1020"){
			//VALIDATION
			if(empty($_POST["username"])){
				die("<p class='alert alert-warning'>Enter Username</p>");
			}else if(empty($_POST["email"])){
				die("<p class='alert alert-warning'>Enter email</p>");
			}else if(empty($_POST["password"])){
				die("<p class='alert alert-warning'>Enter Password</p>");
			}else if(empty($_POST["rpassword"])){
				die("<p class='alert alert-warning'>Re-enter password</p>");
			}else if($_POST["password"]!=$_POST["rpassword"]){
				die("<p class='alert alert-warning'>Passwords do not match</p>");
			}else if(strlen($_POST["password"])<8){
				die("<p class='alert alert-warning'>Your password is too short, make sure it is at least 8 characters long</p>");
			}

			$username=addslashes($_POST["username"]);
			$email=addslashes($_POST["email"]);
			$password=addslashes($_POST["password"]);

			$password=password_hash($password, PASSWORD_DEFAULT);
			$fields=array("username","email","password");
			$data=array($username,$email,$password);

			$create_account=$insertObj->inserter("users",$fields,$data);
			if($create_account=="1"){
				//set role
				
				$get_user_id=$retrieveObj->retriever("users","*","email",$email,"fetch");
				if( $get_user_id!="1020"){
					//insert role
					$fields2=array("user_id","role_id");
					$data2=array($get_user_id->user_id,$get_role_id->role_id);

					$create_account2=$insertObj->inserter("user_roles",$fields2,$data2);
					if($create_account2=="1"){
						echo 1;
					}else{
						//failed
						$deleteObj->deleter("users","email",$email);
						echo 0;
					}
				}else{
					//failed
					$deleteObj->deleter("users","email",$email);
					echo 0;
				}
			}else if($create_account=="entry_exists"){
				echo "<p class='alert alert-warning'>Another user is using the email you entered</p>";
			}else{
				echo 0;
			}

		}else{
			die("<p class='alert alert-warning'>The system already has at least an administrator</p>");
		}
	}

	//USER SIGNIN
	if(isset($_POST["user_signin_note"])){
	 	if(!empty($_POST["email"]) and !empty($_POST["password"])){
	 		$email=addslashes($_POST["email"]);
	 		$password=addslashes($_POST["password"]);
	 		
	 		//get user info
	 		$getUserInfo=$retrieveObj->retriever("users 
			JOIN user_roles ON user_roles.user_id=users.user_id
			JOIN user_role ON user_roles.role_id=user_role.role_id","*","(user_role.user_role='su_admin' or user_role.user_role='admin') and email",$email,"fetch");

	 		if($getUserInfo!="1020"){
	 			//get password
		 		$hash=$getUserInfo->password;

		 		if(password_verify($password, $hash)){
 					if (session_status() == PHP_SESSION_NONE) {
					  session_start();
					}
		 			$_SESSION["provama_admin_in_email"]=$getUserInfo->email;
		 			$_SESSION["provama_admin_in_id"]=$getUserInfo->user_id;
		 			$_SESSION["provama_admin_in_type"]=$getUserInfo->user_role;
		 			echo 1;
	 				
		 		}else{
		 			echo "<p class='alert alert-warning'>Password is wrong</p>";
		 		}
	 		}else{
	 			echo "<p class='alert alert-warning'>The email you entered is not registered</p>";
	 		}	
	 	}else{
	 		echo "<p class='alert alert-warning'>Email or Password is empty</p>";
	 	}
	 
	}

	
	//RESET PASSWORD send email
	if(isset($_POST["reset_password_email"])){
		if(empty($_POST["reset_password_email"])){
			die("<p class='alert alert-warning'>Enter your email</p>");
		}
		$email = $_POST["reset_password_email"];
		$email = filter_var($email, FILTER_SANITIZE_EMAIL);
		$email = filter_var($email, FILTER_VALIDATE_EMAIL);

		if (!$email) {
		   die("<p>Invalid email address please type a valid email address!</p>");
		}else{
		   if (!($rowcountObj->rowcounter("users","*","email",$email)>=1)){
		   		die("<p class='alert alert-warning'>No user is registered with this email address!</p>");
		   }
		}

	   $expFormat = mktime(
	   	date("H"), date("i"), date("s"), date("m") ,date("d")+1, date("Y")
	   );
		$expDate = date("Y-m-d H:i:s",$expFormat);
		$key = password_hash((string)(2418*2).$email, PASSWORD_DEFAULT);

		$fields=array("email","token","expdate");
		$data=array($email,$key,$expDate);
		$insert_token=$insertObj->inserter("password_reset",$fields,$data);

		if($insert_token!=1){
			die("<p class='alert alert-warning'>Something went wrong, try again later</p>");
		}
		 
		$output='<p>Dear '.$email.',</p>'
			;
		$output.='<p>Please click on the following button to reset your password.</p>';
		$output.='<p align="center">	
			<a href="'.$root_dir.'/admin/includes_/reset_password.php?email='.$email.'&key='.$key.'&reset_password_note="">KEY='.$key.'</a>
		</p>'; 
		$output.='<p>
		The reset session will expire after 1 day for security reason.</p>';
		$output.='<p>If you did not request this forgotten password email, no action 
		is needed, your password will not be reset. However, you may want to log into 
		your account and change your security password.</p>';   
		$output.='<p>Regards,</p>';
		$output.='<p><strong>PROVAMA TEAM</strong></p>';
		$body = $output; 
		$subject = "Password Recovery - PROVAMA";

		$email_to = $email;

		$send_email=$sendemailObj->phpmailer_send($mailer_r_path,$subject,$body,$email_to);

		if($send_email=="1"){
			echo "<p class='alert alert-success'>An email has been sent to you with instructions on how to reset your password.</p>";
		}else{
			echo 0;
		}
	   
	}


	if(isset($_POST["reset_password_note"]) and !empty($_POST["reset_password_note"]) and isset($_POST["email"]) and !empty($_POST["email"])){
		$key=$_POST["reset_password_note"];
		$email=$_POST["email"];

        //VALIDATION
		if(empty($_POST["password"])){
			die("<p class='alert alert-warning'>Enter new password</p>");
		}else if(empty($_POST["repeat_password"])){
			die("<p class='alert alert-warning'>Re-enter new password</p>");
		}else if($_POST["password"]!=$_POST["repeat_password"]){
			die("<p class='alert alert-warning'>Passwords do not match</p>");
		}else if(strlen($_POST["password"])<8){
			die("<p class='alert alert-warning'>Make sure your password length is not less than 8 characters long</p>");
		}

		$password=addslashes($_POST["password"]);
		$password_hash=password_hash($password, PASSWORD_DEFAULT);

		//check if the password entered is equal the current password
        $get_current_password=$retrieveObj->retriever("users","*","email",$email,"fetch");
        if($get_current_password=="1020"){
            die("<p class='alert alert-warning'>Something went wrong, Try restarting the password reset process</p>");
        }
        if(password_verify($password, $get_current_password->password)){
        	die("<p class='alert alert-warning text-center'>Password entered is equal to the current password</p>");
        }

		$update_password=$updateObj->updater("users","password='$password_hash'","email",$email);

		if($update_password==1){
			$deleteObj->deleter("password_reset","email",$email);
			die("<p class='alert alert-success'>Password reset successful, please login with the new password.</p>");
		}else{
			die("<p class='alert alert-warning'>Password reset failed try again later</p>");
		}
	}

	

?>