<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" style="" id="user-create-name-input-group">
                <input type="text" id="name" class="form-control createuserinputfield" placeholder="Name" name="name">
            </div>

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


            
            <div class="input-group mb-3" style="" id="user-create-fullname-input-group">
                <input type="text" id="fullname" class="form-control createuserinputfield" placeholder="Fullname" name="fullname">
            </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="">
                <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.exists === true) {
                changeSpantoInvalid('mobile-number');
                usernumberallowed = false;
                return false;
            } else if (response.exists === false) {
                changeSpantoValid('mobile-number');
                usernumberallowed = true;
                return true;
            }
        }

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

    function checkifUsernameExists() {

        let username = $('#username').val();

        if (username === '') {
            changeSpantoValid('username');
            usernicknameallowed = true;
            SRegistrationValidateALLinputs();
            return;
        }

        function CheckUsername(response) {

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

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

        AjaxDo('/admin/user/username/exists', {
            username: username
        }, CheckUsername, 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(userhashkey) {
        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");

            response.forEach(element => {

                $("<option></option>")
                    .val(element.hashkey)
                    .text(`${element.name} (${element.mobile_number}) [${element.username}] ${element.fullname ?? ''}`)
                    .appendTo(selectElement);
            });


        }

        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 (typeof response.success !=='undefined' &&
                response.success) {
                UserRegistrationSuccessModal(response.hashkey);
            } else if (response === false) {
                UserRegistrationFailedModal();
            } 



        }




        AjaxDo('/admin/user/create', {
            mobile_number: $("#usernumber").val(),
            password: $("#userpassword").val(),
            nickname: $("#nickname").val(),
            type: $("#usertype").val(),
            parent: $("#userparent").val(),
            fullname: $("#fullname").val(),
            name: $("#name").val(),
            username: $("#username").val(),
        }, RegisterNow, null, reqtype = 'POST');


    }



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




    RePopulateUserTypeCreateUser();
    RePopulateParentList();
</script>