<?php
	session_start();
	require('includes/config.php');

	$username = mysqli_real_escape_string($con,$_POST['username']);
	$password = mysqli_real_escape_string($con,$_POST['password']);	
	$password = sha1($password);

	$query = "select U.user_id, U.user_name, ur.role_id, U.last_logged_on, r.role_name,ud.image FROM users U JOIN user_details ud ON U.user_id = ud.user_id JOIN user_roles ur ON U.user_id = ur.user_id JOIN roles r ON ur.role_id = r.role_id WHERE U.active = 1 AND (U.user_name = '". $username ."' OR ud.email = '". $username ."') AND U.password = '". $password ."' and ur.role_id IN(1,2)";	
	$exe = mysqli_query( $con, $query );	
	$cnt = mysqli_num_rows( $exe );
	if( $exe ) {
		if( $cnt > 0 ) {
			
			$_SESSION['access_token']   = sha1( $_SESSION['id'] );		

			while( $rows = mysqli_fetch_assoc($exe) ){

				/* user details into session */
				$_SESSION['userid']         = $rows['user_id'];						
				$_SESSION['username']       = $rows['user_name'];			
				$_SESSION['role_id']        = $rows['role_id'];				
				$_SESSION['role_name']      = $rows['role_name'];				
				$_SESSION['last_logged_on'] = $rows['last_logged_on'];
				$_SESSION['profile_image'] =  $rows['image'];
						
			}

			/* updating access_token for a user currently logged in */
	        $uSql = "update users SET access_token = '".$_SESSION['access_token']."' WHERE user_id = ".$_SESSION['userid'];
	        $uExe = mysqli_query( $con, $uSql );
			
			echo json_encode( ['code' => 200, 'data' => 'Login success. Redirecting...', 'url' => 'dashboard' ] );exit;
			
		}else{
			echo json_encode(['code' => 404, 'data' => 'Invalid credentials'] );exit;
		}
	}else{
		echo json_encode(['code' => 405, 'data' => 'Error occured'] );exit;
	}
?>   