<?php
use Livewire\Component;
?>

<div>
    <div class="pay-modal">
        <a href="{{ url('paypal/checkout') }}" class="btn bj_theme_btn strock_btn w-100 " style="width: 100%;margin-bottom: 15px;text-align: center;border-radius: unset;">
            <svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="#fff" viewBox="0 0 24 24" data-testid="svg_IconSecureOutlined"><path fill="#fff" d="M12 12a2 2 0 0 0-1 3.732V17a1 1 0 0 0 2 0v-1.268A2 2 0 0 0 12 12"></path><path fill="#fff" fill-rule="evenodd" d="M7 8V6a5 5 0 1 1 10 0v2h2a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-8a3 3 0 0 1 3-3zm2-2a3 3 0 0 1 6 0v2H9zm-4 4a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg> Finalizar compra
        </a>
        <div id="google-button-container"></div>
        <div id="paypal-button-container"></div>
    </div>
</div>
@script
@section('js')
    <script src="{{ generateJs() }}&components=buttons,googlepay,applepay&enable-funding=card,credit,venmo&vault=true"></script>
    <script src="https://pay.google.com/gp/p/js/pay.js"></script>
    <script src="/static/js/sweetalert2.min.js"></script>
    <script>
        function payment() {
            paypal.Buttons({
                style: {
                    layout: 'vertical',
                    color: 'gold',
                    shape: 'rect',
                    label: 'paypal',
                    tagline: false,
                    height: 41
                }, createOrder: function (data, actions) {
                    return fetch('{{ url('api/create-order') }}', {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({type: 'paypal'})
                    }).then((response) => response.json()).then((order) => order.id);
                }, onApprove: (data, actions) => {
                    return fetch(`{{ url('api/capture-order') }}`, {
                        method: "post",
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({order_id: data.orderID, type: 'paypal'})
                    })
                        .then((response) => response.json())
                        .then((orderData) => {
                            let id= orderData['purchase_units'][0]['payments']['captures'][0]['id'];
                            window.location.href = `/paypal/success?trans_id=${id}`;
                            // When ready to go live, remove the alert and show a success message within this page. For example:
                        });
                }

            }).render('#paypal-button-container');
        }

        payment();
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", (event) => {
            if (google && paypal.Googlepay) {
                onGooglePayLoaded().catch(console.log);
            }
        });

        /*
        * Define the version of the Google Pay API referenced when creating your
        * configuration
        */
        const baseRequest = {
            apiVersion: 2,
            apiVersionMinor: 0,
        };
        let paymentsClient = null,
            allowedPaymentMethods = null,
            merchantInfo = null;

        let token = document.querySelector("meta[name='csrf-token']").content;


        /* Configure your site's support for payment methods supported by the Google Pay */
        function getGoogleIsReadyToPayRequest(allowedPaymentMethods) {
            return Object.assign({}, baseRequest, {
                allowedPaymentMethods: allowedPaymentMethods,
            });
        }

        /* Fetch Default Config from PayPal via PayPal SDK */
        async function getGooglePayConfig() {
            if (allowedPaymentMethods == null || merchantInfo == null) {
                const googlePayConfig = await paypal.Googlepay().config();
                allowedPaymentMethods = googlePayConfig.allowedPaymentMethods;
                merchantInfo = googlePayConfig.merchantInfo;
            }
            return {
                allowedPaymentMethods,
                merchantInfo,
            };
        }

        /* Configure support for the Google Pay API */
        async function getGooglePaymentDataRequest() {
            const paymentDataRequest = Object.assign({}, baseRequest);
            const {allowedPaymentMethods, merchantInfo} = await getGooglePayConfig();
            paymentDataRequest.allowedPaymentMethods = allowedPaymentMethods;
            paymentDataRequest.transactionInfo = await getGoogleTransactionInfo();
            paymentDataRequest.merchantInfo = merchantInfo;
            // SHIPPING_ADDRESS
            // OFFER
            // PAYMENT_AUTHORIZATION
            // SHIPPING_OPTION
            paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
            paymentDataRequest.shippingAddressRequired = true;
            paymentDataRequest.emailRequired = true;
            paymentDataRequest.shippingAddressParameters = {
                phoneNumberRequired: true
            };
            // paymentDataRequest.ShippingOptionParameters={
            //     defaultSelectedOptionId: "shipping-001",
            //     shippingOptions: [
            //         {
            //             "id": "shipping-001",
            //             "label": "€0.00: Free shipping",
            //             "description": "Free Shipping delivered in 5 business days."
            //         }
            //     ]
            // };
            return paymentDataRequest;
        }

        function onPaymentAuthorized(paymentData) {
            return new Promise(function (resolve, reject) {
                processPayment(paymentData)
                    .then(function (data) {
                        resolve({transactionState: "SUCCESS"});
                    })
                    .catch(function (errDetails) {
                        resolve({transactionState: "ERROR"});
                    });
            });
        }

        function getGooglePaymentsClient() {
            if (paymentsClient === null) {
                paymentsClient = new google.payments.api.PaymentsClient({
                    environment: "TEST", // or "PRODUCTION"
                    paymentDataCallbacks: {
                        onPaymentAuthorized: onPaymentAuthorized,
                    },
                });
            }
            return paymentsClient;
        }

        async function onGooglePayLoaded() {
            const paymentsClient = getGooglePaymentsClient();
            const {allowedPaymentMethods} = await getGooglePayConfig();
            paymentsClient
                .isReadyToPay(getGoogleIsReadyToPayRequest(allowedPaymentMethods))
                .then(function (response) {
                    if (response.result) {
                        addGooglePayButton();
                    }
                })
                .catch(function (err) {
                    console.error(err);
                });
        }

        function addGooglePayButton() {
            const paymentsClient = getGooglePaymentsClient();
            const button = paymentsClient.createButton({
                buttonSizeMode: 'fill',
                onClick: onGooglePaymentButtonClicked,
            });
            document.getElementById("google-button-container").appendChild(button);
        }


        async function getGoogleTransactionInfo() {
            const {data} = await fetch('{{ url('api/carts') }}', {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                    'X-CSRF-TOKEN': document.querySelector("meta[name='csrf-token']").content,
                },
            }).then((res) => res.json());
            ;
            return {
                displayItems: [
                    {
                        label: "Subtotal",
                        type: "SUBTOTAL",
                        price: data.subtotal,
                    },
                    {
                        label: "Tax",
                        type: "TAX",
                        price: data.tax,
                    },
                ],
                countryCode: data.cuntryCode,
                currencyCode: data.currencyCode,
                totalPriceStatus: "ESTIMATED",
                totalPrice: data.total,
                totalPriceLabel: "Total",
            };
        }

        async function onGooglePaymentButtonClicked() {
            const paymentDataRequest = await getGooglePaymentDataRequest();
            paymentDataRequest.transactionInfo = await getGoogleTransactionInfo();
            const paymentsClient = getGooglePaymentsClient();
            paymentsClient.loadPaymentData(paymentDataRequest);
        }

        async function processPayment(paymentData) {
            try {
                const {currencyCode, totalPrice} = await getGoogleTransactionInfo();
                const order = {
                    type: "google",

                };
                /* Create Order */
                const {id} = await fetch(`{{ url('api/create-order') }}`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        'X-CSRF-TOKEN': token,
                    },
                    body: JSON.stringify(order),
                }).then((res) => res.json());

                const {status} = await paypal.Googlepay().confirmOrder({
                    orderId: id,
                    paymentMethodData: paymentData.paymentMethodData,
                });

                if (status === "APPROVED") {
                    /* Capture the Order */
                    let body = paymentData;
                    body['type'] = 'google';
                    body['order_id'] = id;
                    const captureResponse = await fetch(`{{ url('api/capture-order') }}`, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            'X-CSRF-TOKEN': token,
                        }, body: JSON.stringify(body)
                    }).then((res) => res.json());
                    return {transactionState: "SUCCESS"};
                } else {
                    return {transactionState: "ERROR"};
                }
            } catch (err) {
                return {
                    transactionState: "ERROR",
                    error: {
                        message: err.message,
                    },
                };
            }
        }

    </script>
@stop
@endscript