$ (document).ready (function () {
  $ ('#btn_login').click (function (e) {
    e.preventDefault ();

        // Get input field values
        var email = $('#email').val().trim();
        var password = $('#password').val();
    // Get input field values
   

    // Check if email and password are not empty
    if (email === '' || password === '') {
      $ ('.err-msg').html ('Both fields are required.');
      return;
    }

    // Check if the entered email is valid
    if (!isValidEmail (email)) {
      $ ('.err-msg').html ('Please enter a valid email address');
      return;
    }


        $.ajax({
            type: "POST",
            url: "classes/LoginController.php", // The URL to your PHP script
            data: {USER_LOGIN:1, email:email, password:password},
            success: function (response) {
                
                var res = $.parseJSON(response)

                if(res.status == '1'){
                    
                    if(res.data.user_role_id == '1'){ // Division Admin
                        location.replace("academic-admin/dashboard.php");
                    }
                    
                    if(res.data.user_role_id == '2'){ // Finance Admin
                        location.replace("finance-admin/dashboard.php");
                    }
                    
                    if(res.data.user_role_id == '3'){ // Center Function
                        location.replace("center_function/dashboard.php");
                    }
                    
                    if(res.data.user_role_id == '4'){ // Counselor
                        location.replace("counselor/dashboard.php");
                    }

                    if(res.data.user_role_id == '5'){ // Student
                        location.replace("student/dashboard.php");
                    }
                
                }else if(res.status == '0'){
                    $('.err-msg').html(res.message);
                }
            },
        });

    });


});


// FUNCTIONS

function isValidEmail (email) {
  // Regular expression for basic email validation
  const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  return emailRegex.test (email);
}
