<?php

/**
* User Class for account creation and login pupose
*/
class User
{
	
	private $con;

	function __construct()
	{
		include_once("../config/connection.php");
		$db = new Database();
		$this->con = $db->connect();
	}
	public function userRegister($username,$password,$confirm_password,$email)
	{
		$username_err = $password_err = $confirm_password_err = "";
		
		if($username==''){
        	$username_err = "Username cannot be blank";
        	return $username_err;
		    }
		    else{
		    	//echo "else";
		        $sql = "SELECT login FROM db_users WHERE login = ?";
		        $stmt = mysqli_prepare($this->con, $sql);
		        $param_username = $username;
		        
				if($stmt)
		        {//echo "stmt";
		            mysqli_stmt_bind_param($stmt, "s", $param_username);
		            if(mysqli_stmt_execute($stmt)){
		            	//echo "execute";
		                mysqli_stmt_store_result($stmt);
		                if(mysqli_stmt_num_rows($stmt) >0)
		                {
		                    $username_err = "This username is already taken"; 
		                    return $username_err;
		                }
		                else{
		                    $username = trim($username);
		                    
		                }
		            }
		            else{
		                return "Something went wrong";
		            }
		        }mysqli_stmt_close($stmt);
		    }
		// Check for password
		if(trim($_POST['password'])==''){
		    $password_err = "Password cannot be blank";
		    return $password_err;
		}
		elseif(strlen(trim($password)) < 5){
		    $password_err = "Password cannot be less than 5 characters";
		    return $password_err;

		}
		else{
		    $password = trim($password);
		   
		}

		// Check for confirm password field
		if(trim($password) !=  trim($confirm_password)){
		    $password_err = "Passwords should match";
		    return $password_err;
		}


		// If there were no errors, go ahead and insert into the database
		if(empty($username_err) && empty($password_err) && empty($confirm_password_err))
		{
		    $sql = "INSERT INTO db_users (id,password,login,user_name,email,db_role_type,allowed_login) VALUES (?,?,?,?,?,?,?)";
		    $stmt =  $this->con->prepare( $sql);
		    if ($stmt)
		    {
		        $stmt->bind_param( "issssii",$id,$param_password,$param_username,$param_username,$email,$role,$allowed_login);

		        // Set these parameters
		        $query = "SELECT MAX(id) FROM db_users";
				$result = mysqli_query($this->con,  $query);
				$row = mysqli_fetch_row($result);
				//echo $row[0], var_dump(intval($row[0]));
				$id=intval($row[0]) +1;
		        $param_username = trim($username);
		        $role =2;
				$allowed_login =1;

		        $param_password = password_hash($password, PASSWORD_DEFAULT);
				$bp = $stmt->execute();
				if ( false===$bp ) {
					die('Error with execute: ' . htmlspecialchars($stmt->error));
				}
				return 1;
		    }
		    mysqli_stmt_close($stmt);
		}
		mysqli_close($this->con);

	}
	

	public function userLogin($user,$password,$financial_year){

		$pre_stmt = $this->con->prepare("SELECT int_user_id, txt_name, txt_password,int_role_type FROM tbl_users WHERE txt_name = ?");
		$pre_stmt->bind_param("s",$user);
		$pre_stmt->execute() or die($this->con->error);
		$pre_stmt->store_result();
		 $num_of_rows = $pre_stmt->num_rows;
        if($num_of_rows>0){
        	$pre_stmt->bind_result( $id, $username, $hashed_password,$db_role_type);
                if($pre_stmt->fetch())
                {
                	//$query="Call sp_receive('2021-02-22','4','6','good','900','700','200','','88','0','0','1','0','1',@return)";
        			//$result=mysqli_query($this->con,  $query);
                
        			if(password_verify($password, $hashed_password)){
        				
        				$_SESSION["username_demo"] = $username;
                        $_SESSION["userid_demo"] = $id;
                        $_SESSION["int_role_type_demo"] =$db_role_type;
                        $_SESSION["financial_year_demo"] =$financial_year;
                        $pre_stmt->close();
        				return 1;
        
        			}else{
						
        				return "PASSWORD_NOT_MATCHED";
        			}
        		}
        	}else{
			return "USERNAME_NOT_MATCHED";
		}
					
				
	}
	
	public function runQuery($query) {
    $result = mysqli_query($this->con, $query);
    if($result){
    while($row=mysqli_fetch_assoc($result)) {
        $resultset[] = $row;
    }
    if(!empty($resultset))
        return $resultset;
	}
	}
	

}

if (isset($_POST["log_user"]) AND isset($_POST["log_password"])) {

	$user = new User();
	$result = $user->userLogin($_POST["log_user"],$_POST["log_password"],$_POST["log_year"]);
	echo $result;
	exit();
}

if (isset($_POST["username"])) {
	$user = new User();
	$username 			= 		$_POST["username"]	;
	$password 			=		$_POST["password"]	;
	$confirm_password 	=		$_POST["confirm_password"]	;
	$email 				=		$_POST["email"];
	$result = $user->userRegister($username,$password,$confirm_password,$email);
	echo $result;
	exit();
}
/*if (isset($_GET["getCompany"])) {
	$m = new User();
	$result = $m->runQuery("SELECT `int_organisation_id`, `txt_name`, `txt_short_name`, `txt_contact_person`, `txt_address`, `txt_mobile`, `txt_mobile_whatsapp`, `txt_email`, `txt_gstn`, `txt_pan`, `blb_logo` FROM `tbl_organisation`");
	foreach ($result as $row) {

		$_SESSION['company_name'] = $row['txt_name'];
	}
	echo json_encode($result);
	exit();
}*/
if (isset($_GET["getCurrentFinancialYearId"])) {
	$m = new User();
	$result = $m->runQuery("SELECT `int_financial_year_id`, `dat_start`, `dat_end`, `ysn_current`, `int_reactor_count`, `int_coulumn_count`, `int_drum_count`, `int_purchase_count`, `int_sale_count`, `int_batch_no_count` FROM `tbl_financial_years`");
	foreach ($result as $row) {
		echo "<option value='".$row["int_financial_year_id"]."'>".date_format(date_create($row['dat_start']),'Y').'-'.date_format(date_create($row['dat_end']),'Y')."</option>";
		//$_SESSION['intCurrentFinancialYear'] = $row['int_financial_year_id'];
	}
	exit();
}

?>