<?php
	if(!isset($_SESSION)) session_start();

require_once("demosettings.php");
require_once("userCake/models/config.php");
require_once 'Authentication/JWT.php';
require_once 'Exceptions/SignatureInvalidException.php';
require_once 'Exceptions/BeforeValidException.php';
require_once 'Exceptions/ExpiredException.php';
require_once 'sqlUtils.php';
require_once 'authorizations.php';
include_once 'systemCheckup.php';

if(!empty($_POST))
{
		$errors = array();
		$username = trim($_POST["username"]);
		$password = trim($_POST["password"]);
		$newPassword = trim($_POST["newPassword"] ?? "");
		
		//1 - Do first DB checkup
		$system_checkup = new systemCheckup();
		$is_db_conn = $system_checkup::db_stats(); // run db checkup
		//only database will return an error
		if(key($is_db_conn)=="ERROR"){
		    $errors[] = "Error connection to the DB";
		} 
		
		//2 - start the input validation 
		if(count($errors) == 0)
		{
    		if($newPassword && minMaxRange(8,50,$newPassword))
    		{
    			$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
    		}
    		//Perform some validation
    		//Feel free to edit / change as required
    		if($username == "")
    		{
    			$errors[] = lang("ACCOUNT_SPECIFY_USERNAME");
    		}
    		if($password == "")
    		{
    			$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
    		}
		}

		//3 - validate the data
		if(count($errors) == 0)
		{
			//A security note here, never tell the user which credential was incorrect
			if(!usernameExists($username))
			{
				$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
			}
			else
			{
				$userdetails = fetchUserDetails($username);

				//See if the user's account is activation
				if($userdetails["Active"]==0)
				{
					$errors[] = lang("ACCOUNT_INACTIVE");
				}
				else
				{
					//Hash the password and use the salt from the database to compare the password.
					$entered_pass = generateHash($password,$userdetails["Password"]);

					if($entered_pass != $userdetails["Password"])
					{
						//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
						$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
					}
					else
					{
						//Passwords match! we're good to go'

						//Construct a new logged in user object
						//Transfer some db data to the session object
						$loggedInUser = new loggedInUser();
						$loggedInUser->email = $userdetails["Email"];
						$loggedInUser->user_id = $userdetails["User_ID"];
						$loggedInUser->hash_pw = $userdetails["Password"];
						$loggedInUser->display_username = $userdetails["Username"];
						$loggedInUser->clean_username = $userdetails["Username_Clean"];                                  
    
						//Update last sign in
						$loggedInUser->updateLastSignIn();
						
						if ($newPassword && $newPassword != $password)
							$loggedInUser->updatePassword($newPassword);
								
						//$_SESSION["userCakeUser"] = $loggedInUser;
						//echo $_SESSION["userCakeUser"]->email;
						$_SESSION["loggedIn"] = "yes";
						$_SESSION["username"] = $userdetails["Username"];
						$jwtToken = JWT::encode(
								array("username" => $_SESSION["username"],
										"time" => date(DATE_ATOM)), $jwtKey);
								
						//check if files table exsist, if not clean all data and go to register
						global $databaseHost;
						global $databaseUser;
						global $databasePass;
						global $databaseName;
						$mysqli = sqlCreateConnection("login");
						$res = sqlQuery($mysqli, "SHOW TABLES LIKE 'files'");
						if($res !== false){
							if ($res->num_rows > 0){
								//Redirect to user account page
								$redirectPage = "home";
							}else{
								include_once("sqlTable.php");
								createDB($mysqli);
								$redirectPage = "register";
							}
						}else{
							$errors[] = "Problem to connect DB";
						}
						
						
						//die();
					}
				}
			}
		}
	}
$response = array();
$response["errors"] = $errors;
$response["redirectPage"] = $redirectPage;
$response["userToken"] = $jwtToken;
$response["userAuth"] = getUserAuth($username);
ob_clean();
echo json_encode($response);

?>
