<div class="row">
    <!-- begin col-12 -->
    <div class="col-12 ui-sortable">
        <!-- begin panel -->
            <div class="panel panel-inverse" data-sortable-id="form-stuff-5">
                <div class="panel-heading">
                    <h4 class="panel-title p-heading" >Add New User</h4>
                </div>
                <br>
                <div class="panel-body">

                    <br><br>
                      <div class="row">
                        <div class="col-md-4">
                            <div style="display: flex;padding:0 20px;">
                                <div id="addUserLabel">User  : &nbsp;</div>
                                <div id="Validate">
                                <input type="text"  class="form-control"  id="user_email" >
                                </div>
                            </div>
                        
                        </div>
                    
                    <div class="col-md-4">
                        <div style="display: flex;padding:0 20px;">
                            <div >User Role : &nbsp;</div>
                            <select id="user_role" class="form-control">
                                <option value="" disabled hidden selected>Select Role</option>
                                <option value="admin" id="admin_opt" >Admin</option>
                                <option value="marketer">Marketer</option>
                                <option value="manager">Manager</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <button  id="save_user" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>	
            </div>
        </div>
    </div>	
    
    <script nonce="<%=nonce%>">

$(document).ready(function() {
    
	//Check isManager validator
	function isManager() {
		let role = localStorage.getItem('user_role')?JSON.parse(localStorage.getItem('user_role')):localStorage.getItem('user_role');
		if(role && role == 'manager') {		
			return true;
		}else{
			return false;
		}
		
	}
    if(isManager()) { 
        document.getElementById('admin_opt').style.display = 'none';
    }
});
$("#Validate").focusout(function(){
    validateEmail()
});
        function validateEmail() {
            let addUserLabel = $("#addUserLabel").text();
            let messageType = (addUserLabel === 'User Email :') ? 'Email' : 'SSO id'; // Determine message type dynamically
            let email = $("#user_email").val();
            if(email) {

                $.ajax({
                type:"GET",
                url:semusiCommon.API_PARTS.users.r + '/validateEmail',
                data:{
                    uniqueNumber : semusiCommon.randomNumber(),
					api_key: semusiCommon.getActiveUser.api_key,
					args: JSON.stringify({
						email:  email,
					})
                },
                dataType:"json",
                success:function (data) {
                    if(!data || data.result == 'User not Found') {
                       
                        showMessage(`${messageType} is not registered`);
				       $("#message").delay(3000).fadeOut(300); 
                        $("#user_email").val('');
                        return;
                    }
                    if(data && data.global_admin) {
                       showMessage("Cannot assign role to global admin");
				       $("#message").delay(3000).fadeOut(300); 
                        $("#user_email").val('');
                        return;
                    }
                    
                }

              })
            }
        }




        $("#save_user").on('click', () =>{
            let email = $("#user_email").val();
            let role = $("#user_role").val();
            let modified_by = "<%= member.user_id%>";
            let appid = JSON.parse(localStorage.getItem('semusi_active_app'));


            if(!email || email == undefined) {
                showMessage("Please enter user email");
                $("#message").delay(3000).fadeOut(300); 
                return;
            }
            if(!role || role == undefined) {
                showMessage("Please select user role");
                $("#message").delay(3000).fadeOut(300); 
                return;
            }

            //Saving role touser collection

            $.ajax({
                type:"POST",
                url:semusiCommon.API_PARTS.users.r + '/addUsersRole',
                data:{
                    uniqueNumber : semusiCommon.randomNumber(),
                    app_id: semusiCommon.ACTIVE_APP_ID,
					api_key: semusiCommon.getActiveUser.api_key,
					args: JSON.stringify({
                        modified_by : modified_by,
						email:  email,
						appid : appid,
						role: role
					})
                },
                headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
                },
                dataType:"json",
                success:function (data) {
                    semusiCommon.getCsrfToken();
                    showMessagesucess(`User Role Updated`);
										$("#messagesucess").delay(3000).fadeOut(300);
										$("#message").delay(3000).fadeOut(300);    
                             window.location.href = encodeURI("<%= cdnUrl %>/dashboard?action=allusers")		

                }

			});




        })

    </script>