<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <loadingModal notFullScreen ref="loadingModal" />
        <div class="page-container-grouped-styles">
            <funnelHeader cmsWidgetName="FunnelHeaderWidget" v-if="!isPaypal" />
            <funnelSubHeader
                class="mb-5"
                cmsWidgetName="FunnelSubHeaderWidget"
                leftAlignHeader
                v-if="!isPaypal" />
            <hr class="mt-0" />
            <div id="card-container">
                <iframe
                    ref="paymentFrame"
                    class="hop-iframe payment-iframe"
                    name="card-frame"
                    id="card-frame"
                    seamless
                    scrolling="no">
                </iframe>
            </div>
            <div class="fade-on-route-transition sub-container make-tall">
                <navbar
                    cmsWidgetName="FunnelFooterWidget"
                    :isForwardActionDisabled="!meta.valid"
                    :isBackButtonHidden="shouldHideBackButton"
                    @back-clicked="backButtonAction"
                    @ForwardClicked="forwardButtonAction" />
            </div>
        </div>
    </Form>

    <form
        ref="myForm"
        id="card-data"
        :target="paypalPayment ? '_top' : 'card-frame'"
        method="POST"
        :action="checkoutUrl">
        <input type="hidden" name="paymentType" :value="paymentType" />
        <input type="hidden" name="sgSessionId" :value="authToken" />
        <input type="hidden" name="sgAuthToken" :value="authToken" />
        <input type="hidden" name="sgSignaturePublic" :value="authSignature" />
        <input type="hidden" name="sgSignatureStartDate" :value="authSignatureStart" />
        <input type="hidden" name="referralSeqNum" :value="referralSequenceNumber" />

        <input type="hidden" name="sge_commerce_indicator_isinternet" value="true" />
        <input type="hidden" name="sghopsource" value="Safelite.com" />
        <input type="hidden" name="sgHtmlStyle" value="ResourceSafeliteHtml" />
        <input type="hidden" name="sgErrorMessagesEmbedded" value="true" />

        <input type="hidden" name="sgNoKeystrokeProcessing" value="false" />

        <input type="hidden" name="maskCharacter" value="*" />
        <input
            type="hidden"
            name="styleSheetCode"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/css/experiments/site-2020Styling.css" />
        <input
            type="hidden"
            name="styleSheetCode2"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/css/experiments/SLHop-2020Styling.css" />

        <input
            type="hidden"
            name="sgReceiptResponseURL"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/Payment/Success.aspx" />
        <input
            type="hidden"
            name="sgDeclineResponseURL"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/Payment/Cancel.aspx" />
        <input
            type="hidden"
            name="sgErrorResponseURL"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/Payment/Error.aspx" />

        <input type="hidden" name="sgheaderline1" :value="sgHeaderline1" />
        <input type="hidden" name="sgHeader1subtitle" value="" />
        <input type="hidden" name="sgheaderline2" :value="sgHeaderline2" />
        <input type="hidden" name="sgheaderline3" value="" />
        <input type="hidden" name="sgheaderline4" value="" />
        <input type="hidden" name="sgheaderline5" value="*Required information" />

        <input type="hidden" name="billTo_firstName" :value="firstName" />
        <input type="hidden" name="billTo_firstNameShow" value="true" />
        <input type="hidden" name="sghopmiddleInitialShow" value="false" />
        <input type="hidden" name="billTo_lastName" :value="lastName" />
        <input type="hidden" name="billTo_lastNameShow" value="true" />

        <input type="hidden" name="billTo_street1" value="" />
        <input type="hidden" name="billTo_street2" value="" />
        <input type="hidden" name="billTo_city" value="" />
        <input type="hidden" name="billTo_state" value="" />

        <input type="hidden" name="billTo_postalCode" value="" />
        <input type="hidden" name="billTo_postalCodeShow" value="true" />
        <input type="hidden" name="billTo_postalCodeEnable" value="true" />
        <input type="hidden" name="sgLabelPostalCode" value="Billing ZIP" />

        <input type="hidden" name="sgtotalamount" :value="displayAmount" />
        <input type="hidden" name="totalAmountDecimal" :value="totalAmount" />
        <input type="hidden" name="lineItems" :value="lineItems" />

        <input type="hidden" name="sgdiscountstrikethruamount" value="" />

        <input type="hidden" name="callerDisplayText" value="" />

        <input
            type="hidden"
            name="sgtermsofusedisplaytext"
            value="By selecting submit, I agree to Safelite's" />
        <input type="hidden" name="sgtermsofuseurl" value="http://www.safelite.com/terms-of-use/" />
        <input type="hidden" name="sgtermsofuselinkdisplaytext" value="terms of use" />
        <input type="hidden" name="sgtermsofcancelrefunddisplaytext" value="and" />
        <input
            type="hidden"
            name="sgtermsofcancelrefundlinkdisplaytext"
            value="cancellation and refund policy" />
        <input
            type="hidden"
            name="sgtermsofcancelrefundurl"
            value="http://www.safelite.com/cancellation-refund-policy" />

        <input
            type="hidden"
            name="sgErrorMessageCardVerification"
            value="Credit card could not be processed" />
        <input
            type="hidden"
            name="sgErrorMessageTimeOut"
            value="For your security, this transaction has been timed out." />

        <input type="hidden" name="sgLabelCardNumber" value="" />
        <input type="hidden" name="sgLabelAddressLine1" :value="address1" />
        <input type="hidden" name="sgLabelAddressLine2" :value="address2" />
        <input type="hidden" name="sgLabelCity" :value="city" />
        <input type="hidden" name="sgLabelState" :value="state" />

        <input type="hidden" name="sgCtu" :value="ctu" />
        <input type="hidden" name="sgWorkOrder" :value="workOrderNumber" />
        <input type="hidden" name="sgEmailAddress" :value="emailAddress" />
        <input type="hidden" name="paypalInvoiceNumber" :value="invoiceNumber" />
        <input type="hidden" name="payPalSuccessUrl" :value="payPalSuccessUrl" />
        <input type="hidden" name="paypalCancelUrl" :value="payPalCancelUrl" />

        <input
            type="hidden"
            name="sgCCDeclineURL"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/Payment.aspx?error=ccDecline" />
        <input
            type="hidden"
            name="sgCCTimeoutURL"
            value="https://fixmyglasstest.safelite.com/FixMyGlass/Payment.aspx?error=ccTimeout" />

        <input type="hidden" name="sgTransactionType" value="authorization" />
        <input type="hidden" name="amount" :value="totalAmount" />
        <input type="hidden" name="ctu" :value="ctu" />
        <input type="hidden" name="orderNumber" :value="workOrderNumber" />

        <input type="hidden" name="billTo_email" :value="emailAddress" />
        <input type="hidden" name="useDecisionManager" value="True" />
        <input type="hidden" name="correlationId" :value="referralCorrelationId" />
        <input type="hidden" name="sgErrorMessageCard_CVN" value="Please enter a valid CVV" />

        <input type="hidden" name="ship_to_address_line1" :value="address1" />
        <input type="hidden" name="ship_to_address_line2" :value="address2" />
        <input type="hidden" name="ship_to_address_city" :value="city" />
        <input type="hidden" name="ship_to_address_state" :value="state" />
        <input type="hidden" name="ship_to_address_country" value="US" />
        <input type="hidden" name="ship_to_address_postal_code" :value="zipCode" />
        <input type="hidden" name="ship_to_phone" :value="phoneNumber" />

        <input type="hidden" name="calling_application" value="NextGen" />
    </form>
</template>

<script>
// Components
import funnelHeader from "@/fmg-components/funnel-header/funnel-header";
import navbar from "@/fmg-components/nav-bar/nav-bar";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";

import { storeActions } from "@/constants/store-actions";
import store from "@/store";
import { externalUrls } from "@/router/router-constants/externalUrl-values";
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";

// Validation
import { Form } from "vee-validate";

export default {
    name: "payment",
    data() {
        return {
            checkoutUrl: externalUrls.SAFELITE_HOP,
            payPalSuccessUrl: externalUrls.PAYPAL_SUCCESS_URL,
            payPalCancelUrl: externalUrls.PAYPAL_CANCEL_URL,
            paymentType: this.getPaymentType(),
            authToken: "",
            authSignature: "",
            authSignatureStart: "",
            referralSequenceNumber: store.getters.order.referralSequenceNumber,
            emailAddress: store.getters.order.customer.emailAddress,
            address1: this.getAddress1(),
            address2: this.getAddress2(),
            city: this.getCity(),
            state: this.getState(),
            zipCode: this.getZipCode(),
            firstName: store.getters.order.customer.firstName,
            lastName: store.getters.order.customer.lastName,
            phoneNumber: store.getters.order.customer.phoneNumber,
            ctu: store.getters.order.serviceLocation.zipCodeCtu,
            referralCorrelationId: store.getters.order.referralCorrelationId,
            // TODO: replace these
            workOrderNumber: Math.floor(Math.random() * 90000) + 10000,
            invoiceNumber: Math.floor(Math.random() * 90000) + 10000,
            totalAmount: "321.00", // TODO: get from cart?
            displayAmount: "$321.00", // TODO: get from cart?
            lineItems: "Labor|189.99|1||Repair supplies|7.99|1",
            sgHeaderline1: this.getHeaderLine1(),
            sgHeaderline2: this.getHeaderLine2(),
            paypalPayment: this.isPaypal(),
        };
    },
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
        // TODO: Data fetching Promise declarations

        const promiseResultMap = [
            {
                resultKey: "cmsContent",
                promise: cmsContentPromise,
            },
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        // Call the "next" function to complete the transition to this page.
        next(async (vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.fetchSignatureInfo();
        });
    },
    methods: {
        arePagePrerequisitesValid() {
            // TODO
            return true;
        },
        getAddress1() {
            return store.getters.order.serviceLocation.address
                ? store.getters.order.serviceLocation.address
                : store.getters.order.serviceLocation.provider.address.streetAddress;
        },
        getAddress2() {
            return store.getters.order.serviceLocation.address2
                ? store.getters.order.serviceLocation.address2
                : null;
        },
        getCity() {
            return store.getters.order.serviceLocation.city
                ? store.getters.order.serviceLocation.city
                : store.getters.order.serviceLocation.provider.address.city;
        },
        getState() {
            return store.getters.order.serviceLocation.state
                ? store.getters.order.serviceLocation.state
                : store.getters.order.serviceLocation.provider.address.state;
        },
        getZipCode() {
            return store.getters.order.serviceLocation.zipCode
                ? store.getters.order.serviceLocation.zipCode
                : store.getters.order.serviceLocation.provider.address.zipCode;
        },
        getPaymentType() {
            return store.getters.order.payment.payNowType;
        },
        getHeaderLine1() {
            if (!this.isPaypal()) {
                return "Submit payment information";
            }
            return "";
        },
        getHeaderLine2() {
            if (!this.isPaypal()) {
                return "Save time when you pay for your service today! Please select a payment option.";
            }
            return "";
        },
        isPaypal() {
            if (this.getPaymentType() == "pp") {
                return true;
            }
            return false;
        },
        backButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.CLICKED_BACK, this.$route);
        },
        forwardButtonAction() {},
        async fetchSignatureInfo() {
            if (this.isPaypal()) {
                this.$refs.loadingModal.showModal();
            }
            const signatureInfo = await this.dispatchStoreAction(storeActions.GET_SIGNATURE);
            this.authToken = signatureInfo.data.token;
            this.authSignature = signatureInfo.data.signature;
            this.authSignatureStart = signatureInfo.data.startDate;

            this.$nextTick(() => {
                this.$refs.myForm.submit();

                if (this.paymentType == "ap") {
                    const iframe = this.$refs.paymentFrame;
                    if (iframe) {
                        iframe.onload = () => {
                            if (iframe.contentWindow) {
                                iframe.contentWindow.postMessage("afterpay", "*");
                            }
                        };
                    }
                }
            });
        },
    },
    components: {
        funnelHeader,
        navbar,
        funnelSubHeader,
        Form,
        loadingModal,
    },
};
</script>

<style lang="scss">
.payment-iframe {
    height: 100%;
}

.hop-iframe {
    position: relative;
    min-height: 1300px;
    width: 100%;
    border: 0 none;
}
</style>
