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

}
	
	
	$out  = array();
	$Validator = array('is_success'=>false, 'data'=>array());

	date_default_timezone_set('Asia/Baghdad');

	$LogTime = date('Y-m-d H:i:s');

	if(empty($_POST['username']) || empty($_POST['password'])){

		$error=" Please Fill User Name and Password!";
        $State=false;
        $out  = array(
					'status'  => 'false',
					'data'  => $error
					);
	}
	else
	{
			require_once "db_connect.php";

			$username=$_POST['username'];
			$password=$_POST['password'];


			$username = stripslashes($username);
			$username = mysqli_real_escape_string($db,$username);


			$password=hash('sha256',$password);
	    	$password= stripslashes($password);
	    	$password=mysqli_real_escape_string($db,$password);

			$sql = "SELECT * FROM staff WHERE username = '" . $username ."'  AND password= '" . $password . "' AND is_deleted=0 ";

	    	$query = $db->query($sql);

			if (!$query) {

		        $error= "Some thing went wrong. Please try again";
		        $State=false;

		        

		  	}else{
		        $Records = $query->fetch_assoc();

		        $LogTime = date('Y-m-d H:i:s');

				if($Records){

					$_SESSION['fail_count'] 	= 0;
					
					$UserID 					= $Records['staff_id'];
					$_SESSION['is_login'] 		= true;
					$_SESSION['user_id'] 		= $Records['staff_id'];
					$_SESSION['profile_type'] 	= $Records['profile_type'];
					$_SESSION['access_token'] 	= md5(uniqid(rand(), true));
					$_SESSION['image_path'] 	= 'image/profile/';
					$_SESSION['username'] 		= $Records['username'];
					$_SESSION['full_name'] 		= $Records['full_name'];
					$_SESSION['email'] 			= $Records['email'];
					$_SESSION['profile_image'] 	= $Records['profile_img'];
					$_SESSION['cover_image'] 	= $Records['cover_img'];
					$_SESSION['phone_number'] 	= $Records['phone_number'];
					$_SESSION['created_at'] 	= date('F-Y',strtotime($Records['created_at'])) ;
					$_SESSION['updated_at'] 	= $Records['updated_at'];
					$_SESSION['language_id'] 	= $Records['language_id_fk'];
					$_SESSION['branch_id'] 		= $Records['branch_id_fk'];
					$_SESSION['is_view'] 		= $Records['is_view'];


					// get role name
					$sql = "SELECT * FROM staff_role LEFT JOIN role ON (role_id = role_id_fk AND role.is_deleted =0 ) WHERE staff_id_fk = '".$UserID."'   AND staff_role.is_deleted=0 ";

			    	$res = $db->query($sql);
					
					$Permission    = "";
					$Permission_id = "";
					$sub_permission_id 	= "";
					
					while ($row = $res->fetch_assoc()) {
						$Permission 	 = $row['role'].','.$Permission ;
						$Permission_id 	 = $row['role_id'].','.$Permission_id ;
					}


					// get role name
					$sql = "SELECT * FROM staff_sub_role SSR WHERE SSR.staff_id_fk = '".$UserID."'   AND SSR.is_deleted=0 ";

			    	$res1 = $db->query($sql);
					
					

					while ($row1 = $res1->fetch_assoc()) {
						
						$sub_permission_id 	 	= $row1['sub_role_id_fk'].','.$sub_permission_id ;
					}

					$_SESSION['permission'] 	  	= $Permission;
					$_SESSION['permission_id'] 		= $Permission_id;
					$_SESSION['sub_permission_id'] 	= $sub_permission_id;

					
					// bring system setting

					$sys_res = $db->query("SELECT * FROM system_settings");
					$sysinfo = $sys_res->fetch_assoc();
							
					$_SESSION['USD_TO_IQD']      = $sysinfo['SYSUSDRATE'];
					$_SESSION['company_logo']    = $sysinfo['SYSCompanyLogo'];
					$_SESSION['company_name']    = $sysinfo['SYSCompanyName'];
					$_SESSION['company_mngr_en'] = $sysinfo['SYSCompanyManager_en'];
					$_SESSION['company_mngr_ku'] = $sysinfo['SYSCompanyManager_ku'];
					$_SESSION['company_mngr_ar'] = $sysinfo['SYSCompanyManager_ar'];
					$_SESSION['company_address'] = $sysinfo['SYSCompanyAddress'];
					$_SESSION['company_phone']   = $sysinfo['SYSCompanyPhone'];
					$_SESSION['company_email']   = $sysinfo['SYSCompanyEmail'];
					$_SESSION['notify_email']    = $sysinfo['notify_email'];
					$_SESSION['SYSName']   		 = $sysinfo['SYSName'];
					$_SESSION['SYSVersion']   	 = $sysinfo['SYSVersion']; 
					$_SESSION['SYSSetupDate']    = date('d-M-Y',strtotime($sysinfo['SYSSetupDate'])) ;
					$_SESSION['SYSTimezone']     = $sysinfo['SYSTimezone']; 

			        $error= "Login Success";
			        $State= true;

			        // Update User Information

			        $LastLoging = $LogTime;
			        $LoginCount = $Records['login_count'] +1;

			        $sql = "UPDATE staff SET login_count='$LoginCount',last_action='logged in', updated_at='$LastLoging' WHERE staff_id = '".$UserID."'";

			        $query = $db->query($sql);

				}else{
			        $error= " User Name or Password Invalid ";
			        $State=false;

			        $sql_chk = "SELECT * FROM staff WHERE username = '" . $username ."' AND is_deleted=0 ";

		    		$query_chk = $db->query($sql_chk);
		    		if ($query_chk) {
		    			$_SESSION['fail_count'] = $_SESSION['fail_count'] +1;
			        	
			        	$Records1 			= $query_chk->fetch_assoc();
						$UserID1 			= $Records1['staff_id'];

		    		}
			        
			        if($_SESSION['fail_count'] >= 25){
			        	$sql = "UPDATE staff SET is_deleted='1', updated_at='$LogTime' WHERE staff_id = '".$UserID1."'";

				        $query = $db->query($sql);

				        $error= "Your Account Have Been De-Activated Please Contact Administrator";
			        	$State=false;
			        }
				} // if records

			} // if query

		} // if empty


			$Validator['is_success'] = $State;
      		$Validator['data'] = $error;
			echo json_encode($Validator);



?>
