<?php session_start();

class LoginController
{

    private $con;

    function __construct()
    {
        include_once("../includes/DB/Connection.php");
        $db = new Connection();
        $this->con = $db->connect();
    }


    public function userLogin($request)
    {

        $user_email = trim($request['email']);
        $user_password = $request['password'];
        
        if(!empty($user_email) || !empty($user_password)){
                        
            $sql_login = $this->con->query("SELECT u.user_id, u.user_first_name, u.user_last_name, u.user_email, u.user_password, u.campus_id, u.branch_id, u.user_role_id, ur.user_role_name FROM user u INNER JOIN user_role ur ON u.user_role_id = ur.user_role_id WHERE u.user_email = '$user_email' AND u.user_status = 1");
            
            if($sql_login->num_rows == 1){
                
                $row = $sql_login->fetch_assoc();
                    
                // password_hash($user_password, PASSWORD_BCRYPT, ["COST"=> 8]);
                if(password_verify($user_password, $row['user_password'])){
                    $_SESSION['log_session']['user_id'] = $row['user_id'];
                    $_SESSION['log_session']['user_first_name'] = $row['user_first_name'];
                    $_SESSION['log_session']['user_last_name'] = $row['user_last_name'];
                    $_SESSION['log_session']['user_email'] = $row['user_email'];
                    $_SESSION['log_session']['campus_id'] = $row['campus_id'];
                    $_SESSION['log_session']['branch_id'] = $row['branch_id'];
                    $_SESSION['log_session']['user_role_id'] = $row['user_role_id'];
                    $_SESSION['log_session']['user_role_name'] = $row['user_role_name'];
                    
                    $data = [ 'user_role_id' => $row['user_role_id'], 'user_role_name' => $row['user_role_name'], 'message'=> 'Login Success!'];
                    return ['status'=> 1, 'data' => $data];
                    
                }else {
        
                    return ['status' => 0, 'message' => 'Incorrect password!'];
                }

            }else {
                return ['status' => 0, 'message' => 'Incorrect Email Address!'];
            }

            
        }else{
            return ['status' => 0, 'message' => 'Both Email and Password must be required!'];
        }
    }
}

if (isset($_POST['USER_LOGIN'])) {
    $lc = new LoginController();
    echo json_encode($lc->userLogin($_POST));
    exit();
}
