<!-- resources/views/payment/form.blade.php -->
<!DOCTYPE html>
<html>

<head>
    <title>Payment Form</title>
    <!-- INCLUDE SESSION.JS JAVASCRIPT LIBRARY -->
    <script src="https://cbcmpgs.gateway.mastercard.com/form/version/61/merchant/TESTAMERIPLASLKR/session.js"></script>
    <!-- APPLY CLICK-JACKING STYLING AND HIDE CONTENTS OF THE PAGE -->
    <style id="antiClickjack">
        body {
            display: none !important;
        }
    </style>


</head>

<body>
    <div class="payment-container">
        <div>Please enter your payment details:</div>
        {{ $orderId }}
        {{ $transactionId }}
        {{ $version }}
        <h3>Credit Card</h3>
        <div class="input-group">Card Number: <input type="text" id="card-number" class="input-field" title="card number"
                aria-label="enter your card number" value="" tabindex="1" readonly></div>
        <div class="input-group">Expiry Month:<input type="text" id="expiry-month" class="input-field"
                title="expiry month" aria-label="two digit expiry month" value="" tabindex="2" readonly></div>
        <div class="input-group">Expiry Year:<input type="text" id="expiry-year" class="input-field"
                title="expiry year" aria-label="two digit expiry year" value="" tabindex="3" readonly></div>
        <div class="input-group">Security Code:<input type="text" id="security-code" class="input-field"
                title="security code" aria-label="three digit CCV security code" value="" tabindex="4" readonly>
        </div>
        <div class="input-group">Cardholder Name:<input type="text" id="cardholder-name" class="input-field"
                title="cardholder name" aria-label="enter name on card" value="" tabindex="5" readonly></div>
        <div class="button-group"><button id="payButton" onclick="pay('card');">Pay Now</button></div>
    </div>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .payment-container {
            background-color: #ffffff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 100%;
        }

        .payment-container h3 {
            margin-bottom: 20px;
            color: #333333;
            text-align: center;
        }

        .input-group {
            margin-bottom: 15px;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
            color: #666666;
        }

        .input-field {
            width: calc(100% - 2px);
            padding: 8px;
            border: 1px solid #cccccc;
            border-radius: 5px;
            font-size: 16px;
        }



        .button-group {
            text-align: center;
        }

        #payButton {
            background-color: #28a745;
            color: #ffffff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        #payButton:hover {
            background-color: #218838;
        }
    </style>
    <!-- JAVASCRIPT FRAME-BREAKER CODE TO PROVIDE PROTECTION AGAINST IFRAME CLICK-JACKING -->
    <script type="text/javascript">
        if (self === top) {
            var antiClickjack = document.getElementById("antiClickjack");
            antiClickjack.parentNode.removeChild(antiClickjack);
        } else {
            top.location = self.location;
        }

        PaymentSession.configure({
            session: "{{ $sessionId }}",
            fields: {
                // ATTACH HOSTED FIELDS TO YOUR PAYMENT PAGE FOR A CREDIT CARD
                card: {
                    number: "#card-number",
                    securityCode: "#security-code",
                    expiryMonth: "#expiry-month",
                    expiryYear: "#expiry-year",
                    nameOnCard: "#cardholder-name"
                }
            },
            //SPECIFY YOUR MITIGATION OPTION HERE
            frameEmbeddingMitigation: ["javascript"],
            callbacks: {
                initialized: function(response) {
                    // HANDLE INITIALIZATION RESPONSE
                },
                formSessionUpdate: function(response) {
                    // HANDLE RESPONSE FOR UPDATE SESSION
                    if (response.status) {
                        if ("ok" == response.status) {
                            console.log("Session updated with data: " + response.session.id);

                            //check if the security code was provided by the user
                            if (response.sourceOfFunds.provided.card.securityCode) {
                                console.log("Security code was provided.");
                            }

                            //check if the user entered a Mastercard credit card
                            if (response.sourceOfFunds.provided.card.scheme == 'MASTERCARD') {
                                console.log("The user entered a Mastercard credit card.")
                            }
                            initiateAuthentication(response.session.id);
                        } else if ("fields_in_error" == response.status) {

                            console.log("Session update failed with field errors.");
                            if (response.errors.cardNumber) {
                                console.log("Card number invalid or missing.");
                            }
                            if (response.errors.expiryYear) {
                                console.log("Expiry year invalid or missing.");
                            }
                            if (response.errors.expiryMonth) {
                                console.log("Expiry month invalid or missing.");
                            }
                            if (response.errors.securityCode) {
                                console.log("Security code invalid.");
                            }
                        } else if ("request_timeout" == response.status) {
                            console.log("Session update failed with request timeout: " + response.errors
                                .message);
                        } else if ("system_error" == response.status) {
                            console.log("Session update failed with system error: " + response.errors.message);
                        }
                    } else {
                        console.log("Session update failed: " + response);
                    }
                }
            },
            interaction: {
                displayControl: {
                    formatCard: "EMBOSSED",
                    invalidFieldCharacters: "REJECT"
                }
            }
        });

        function pay() {
            // UPDATE THE SESSION WITH THE INPUT FROM HOSTED FIELDS
            PaymentSession.updateSessionFromForm('card');
        }

        function initiateAuthentication(sessionId) {

            fetch('/initiate-authentication', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({
                        orderId: "{{ $orderId }}",
                        transactionId: "{{ $transactionId }}",
                        version: "{{ $version }}",
                        sessionId: sessionId,
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // document.body.innerHTML = data.data;
                        console.log("Authentication initiated successfully:", data.data);
                        if (data.data.response.gatewayRecommendation === 'PROCEED') {
                // If recommendation is to proceed, call the pay function
                paymentprocess(sessionId);
            } else {
                // Otherwise, initiate payer authentication
                authenticatePayer(sessionId);
            }

                    } else {
                        pay();
                        console.error("Failed to initiate authentication:", data.message);
                    }
                })
                .catch(error => console.error('Error:', error));
        }



        function authenticatePayer(sessionId) {
            // Perform AJAX request or form submission to initiate Payer Authentication (Step 4)
            fetch('/authenticate-payer', {
                    method: 'post',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({
                        orderId: "{{ $orderId }}",
                        transactionId: "{{ $transactionId }}",
                        version: "{{ $version }}",
                        sessionId: sessionId,
                        amount: "{{ $amount }}",

                    })
                })
                .then(response => response.json())
                .then(data => {

                    if (data.success) {
                        console.log("Payer authentication successful. Proceed to next step.", data);

                        var container = document.createElement('div');
                        container.style.width = '1300px'; // Set the width of the container
                        container.style.height = '1200px'; // Set the height of the container
                        container.style.border = '1px solid #ccc'; // Optional: Add a border for visibility

                        // Inject data into the container
                        container.innerHTML = data
                        .data; // Assuming data.data contains the HTML content you want to display

                        // Append the container to the body or another parent element
                        document.body.appendChild(container);


                        var form = document.getElementById('redirectTo3ds1Form');
                        if (form) {

                            form.submit();

                            form.parentNode.removeChild(form);

                        }




                    } else {
                        console.error("Payer authentication failed:", data.message);
                        alert("Payer authentication failed. Please try again.");
                    }
                })
                .catch(error => {
                    console.error("Error initiating Payer Authentication:", error);
                    alert("Error initiating Payer Authentication. Please try again.");
                });
        }

        function paymentprocess(sessionId) {
    fetch('/payment-process', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: JSON.stringify({
            orderId: "{{ $orderId }}",
            transactionId: "{{ $transactionId }}",
            amount: "{{ $amount }}",
            sessionId: sessionId,
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Payment initiated successfully:', data);
            // Handle success scenario as needed
        } else {
            console.error('Failed to initiate payment:', data.message);
            alert('Failed to initiate payment. Please try again.');
        }
    })
    .catch(error => {
        console.error('Error initiating payment:', error);
        alert('Error initiating payment. Please try again.');
    });
}

    </script>
</body>

</html>
