<br><br>

<div class="card" id="secondary-card">
    <div class="card-header ui-sortable-handle" style="cursor: move; display: none;">
        <h3 class="card-title"></h3>
        <div class="card-tools"></div>
    </div>
    <div class="card-body">

        <div class="row card-body d-flex align-items-center w-100">



            <div class="input-group mb-3">
                <input type="number" id="usernumber" class="form-control createuserinputfield" placeholder="Mobile Number" name="usernumber">
            </div>

            <div class="input-group mb-3" style="" id="user-create-nickname-input-group">
                <input type="text" id="nickname" class="form-control createuserinputfield" placeholder="Nick Name" name="nickname">
            </div>

            <div class="input-group mb-3" id="usertypecontrol" style="">
                <select class="form-control" id="usertype">

                </select>
            </div>

            <div class="input-group mb-3" id="userparentcontrol" style="display:none;">
                <select class="form-control" id="userparent">
            </select>
            </div>

            <div class="input-group mb-3">
                <input type="password" class="form-control  createuserinputfield" placeholder="Password" id="userpassword" name="userpassword">

            </div>


            <div class="input-group mb-3">
                <input type="password" class="form-control  createuserinputfield" placeholder="ConfirmPassword" id="userpasswordconfirm" name="userpasswordconfirm">

            </div>

            <div class="input-group mb-3">
                <button class="form-control btn-primary" id="RegisterNowButton" onclick="RegisterConfirmationPrompt();" style="display:none;">Register Now</button>
            </div>



        </div>
    </div>
</div>

<script>
    var usernumberallowed = false;
    var usernicknameallowed = false;
    var normalpasswordallowed = false;
    var confirmpasswordallowed = false;


    window.hasValidMobileNumberFormat =  function hasValidFormat(usernumber) {

        const pattern = /^09\d{9}$/;
        return pattern.test(usernumber);
    }

    function VerifyInitialPassword() {
        const userPassword = document.getElementById("userpassword").value;
        if (userPassword.length < 6) {
            changeSpantoInvalid('user-password');
            normalpasswordallowed = false;
            return false;
        }
        changeSpantoValid('user-password');
        normalpasswordallowed = true;
        return true;

    }

    function VerifyConfirmPassword() {
        const userPassword = document.getElementById("userpassword").value;
        const userPasswordConfirm = document.getElementById("userpasswordconfirm").value;

        if (userPassword.length < 6 || userPasswordConfirm.length < 6) {
            changeSpantoInvalid('user-password-confirm');
            confirmpasswordallowed = false;
            return false;
        }
        if (userPassword !== userPasswordConfirm) {
            changeSpantoInvalid('user-password-confirm');
            confirmpasswordallowed = false;
            return false;
        }
        changeSpantoValid('user-password-confirm');
        changeSpantoValid('user-password');
        confirmpasswordallowed = true;
        return true;
    }

    function changeSpantoInvalid(idtext) {
        $("#" + idtext + "-span").attr("class", "fas fa-times-circle");
        $("#" + idtext + "-input-group-text").attr("class", "input-group-text  bg-danger");
    }

    function changeSpantoValid(idtext) {
        $("#" + idtext + "-span").attr("class", "fas fa-check");
        $("#" + idtext + "-input-group-text").attr("class", "input-group-text  bg-primary");
    }



    function checkifUserExists() {

        let usernumber = $('#usernumber').val();
        if (!window.hasValidMobileNumberFormat(usernumber)) {
            changeSpantoInvalid('mobile-number');
            usernumberallowed = false;
            return false;
        }

        function CheckUser(response) {

            if (response === true) {
                changeSpantoInvalid('mobile-number');
                usernumberallowed = false;
                return false;
            } else if (response === false) {
                changeSpantoValid('mobile-number');
                usernumberallowed = true;
                return true;
            }
        }

        AjaxDo('/admin/user/exists', {
            user_target: usernumber
        }, CheckUser, null, reqtype = 'POST');
    }

    function checkifUserNickExists() {

        let usernick = $('#nickname').val();
    
if (usernick===''){
    changeSpantoValid('nick-name');
                usernicknameallowed = true;
                SRegistrationValidateALLinputs();
                return;
}

        function CheckUserNick(response) {

            if (response === true) {
                changeSpantoInvalid('nick-name');
                usernicknameallowed = false;
                SRegistrationValidateALLinputs();
                return false;
            } else if (response === false) {

                changeSpantoValid('nick-name');
                usernicknameallowed = true;
                SRegistrationValidateALLinputs();
                return true;
            }
        }

        AjaxDo('/admin/user/nick/exists', {
            user_nick: usernick
        }, CheckUserNick, null, reqtype = 'POST');
    }



    function SRegistrationValidateALLinputs() {
        if (usernumberallowed && normalpasswordallowed && confirmpasswordallowed && usernicknameallowed) {
            $('#RegisterNowButton').show();
            return true;
        } else {
            $('#RegisterNowButton').hide();
            return false;
        }
    }



    function RegisterConfirmationPrompt() {
        let modalid = "CreateUserConfirmationDialog";
        let modaltitle = 'Create New User?';
        let modalbody = 'Are you sure you want to Create a New User?';

        let modalfooter = `<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-danger" onclick="SregisterNow()" id="request-credit-now">Continue</button>`;

        CreateAndShowModal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose = false, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header');

    }

    function UserRegistrationSuccessModal() {
        let modalid = "CreateUserSuccessModal";
        let modaltitle = 'Success';
        let modalbody = 'User Created Successfully';

        let modalfooter = `<button type="button" class="btn btn-primary" onclick="$('#CreateUserSuccessModal').modal('hide');ButtonGo('user_list',0);" id="request-credit-now">Ok</button>`;
        CreateAndShowModal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose = false, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header');
    }

    function UserRegistrationFailedModal() {
        let modalid = "CreateUserFailedModal";
        let modaltitle = 'Failed';
        let modalbody = 'Error Creating User. User was not created.';

        let modalfooter = `<button type="button" class="btn btn-warning" data-dismiss="modal">Ok</button>`;
        CreateAndShowModal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose = false, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header');
    }


    function UserRegistrationFailedModalErrorMessage(Message) {
        let modalid = "CreateUserFailedModalErrorMessage";
        let modaltitle = 'Failed';
        let modalbody = Message;

        let modalfooter = `<button type="button" class="btn btn-warning" data-dismiss="modal">Ok</button>`;
        CreateAndShowModal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose = false, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header');
    }


    function RePopulateParentList() {
        function UpdateSelectParentList(response) {
            const selectElement = $("#userparent"); // Select the element using jQuery

            response.forEach(element => {

                $("<option></option>")
                    .val(element.hashkey)
                    .text(element.mnumber)
                    .appendTo(selectElement); // Create and append option with values
            });


        }

        AjaxDo('/admin/user/list/numbers/hash', {}, UpdateSelectParentList, null, reqtype = 'POST');

    }

    function RePopulateUserTypeCreateUser() {
        function UpdateSelectUserTypeList(response) {
            const selectElement = $("#usertype"); // Select the element using jQuery
            selectElement.html('');
            response.forEach(element => {

                $("<option></option>")
                    .val(element[0])
                    .text(element[1])
                    .appendTo(selectElement); // Create and append option with values
            });


        }

        AjaxDo('/admin/list/usertype/create', {}, UpdateSelectUserTypeList, null, reqtype = 'POST');

    }


    function SregisterNow() {
        $('#CreateUserConfirmationDialog').modal('hide');

        function RegisterNow(response) {
            console.log(response);
            if (response === true) {
                UserRegistrationSuccessModal();

            } else if (response === false) {
                UserRegistrationFailedModal();
            } else {
                UserRegistrationFailedModalErrorMessage(response);
            }




        }




        AjaxDo('/admin/user/create', {
            user_number: $("#usernumber").val(),
            user_password: $("#userpassword").val(),
            user_nickname: $("#nickname").val(),
            user_type: $("#usertype").val(),
            user_parent: $("#userparent").val()
        }, RegisterNow, null, reqtype = 'POST');


    }



    $('#usernumber').keyup(function() {
        checkifUserExists();
        SRegistrationValidateALLinputs();
    });
    $('#nickname').keyup(function() {
         checkifUserNickExists();
    });
    $('#userpassword').keyup(function() {
        VerifyInitialPassword();
        SRegistrationValidateALLinputs();
    });
    $('#userpasswordconfirm').keyup(function() {
        VerifyConfirmPassword();
        SRegistrationValidateALLinputs();
    });
    $('.createuserinputfield').keyup(function() {
        SRegistrationValidateALLinputs();
    });



    RePopulateUserTypeCreateUser();
</script>