{{-- d:\projects\digitalvocano\Modules\AuthorizeNetGateway\Resources\views\subscriptions\checkout.blade.php --}}
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Subscribe to :planName via Authorize.Net', ['planName' => $plan->name]) }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg p-6">
                <h3 class="text-lg font-medium text-gray-900">Plan: {{ $plan->name }}</h3>
                <p class="mt-1 text-sm text-gray-600">Price: ${{ number_format($plan->price, 2) }} / {{ $plan->interval }}</p>

                @if (session('error'))
                    <div class="mb-4 p-4 text-sm text-red-700 bg-red-100 rounded-lg" role="alert">
                        {{ session('error') }}
                    </div>
                @endif

                {{-- Div for displaying Accept.js errors --}}
                <div id="acceptJsErrorDiv" class="mb-4 p-4 text-sm text-red-700 bg-red-100 rounded-lg" role="alert" style="display: none;">
                    {{-- Errors will be inserted here by JavaScript --}}
                </div>

                {{-- The action should point to your processing route --}}
                <form id="paymentForm"
                      action="{{ route('subscription.authorizenet.processSubscription', ['subscriptionPlan' => $plan->slug]) }}"
                      method="POST">
                    @csrf
                    <input type="hidden" name="dataValue" id="dataValue" />
                    <input type="hidden" name="dataDescriptor" id="dataDescriptor" />

                    {{-- Card Information Fields for Accept.js --}}
                    <div class="mt-4">
                        <label for="cardNumber" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Card Number') }} <span class="text-red-500">*</span></label>
                        <input type="tel" id="cardNumber" inputmode="numeric" pattern="[0-9\s]{13,19}" autocomplete="cc-number" maxlength="19" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="•••• •••• •••• ••••" required>
                    </div>

                    <div class="grid grid-cols-2 gap-4 mt-4">
                        <div>
                            <label for="expMonth" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Expiration Month (MM)') }} <span class="text-red-500">*</span></label>
                            <input type="tel" id="expMonth" inputmode="numeric" autocomplete="cc-exp-month" maxlength="2" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" placeholder="MM" required>
                        </div>
                        <div>
                            <label for="expYear" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Expiration Year (YYYY)') }} <span class="text-red-500">*</span></label>
                            <input type="tel" id="expYear" inputmode="numeric" autocomplete="cc-exp-year" maxlength="4" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" placeholder="YYYY" required>
                        </div>
                    </div>

                    <div class="mt-4 mb-6">
                        <label for="cardCode" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('CVV') }} <span class="text-red-500">*</span></label>
                        <input type="tel" id="cardCode" inputmode="numeric" autocomplete="cc-csc" maxlength="4" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" placeholder="CVV" required>
                    </div>

                    {{-- Billing Address Fields (Recommended for AVS) --}}
                    <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mt-6 mb-2">Billing Address</h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="billToFirstName" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('First Name') }} <span class="text-red-500">*</span></label>
                            <input type="text" id="billToFirstName" name="billToFirstName" value="{{ old('billToFirstName', Auth::user()->first_name ?? (explode(' ', Auth::user()->name)[0] ?? '')) }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="given-name">
                        </div>
                        <div>
                            <label for="billToLastName" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Last Name') }} <span class="text-red-500">*</span></label>
                            <input type="text" id="billToLastName" name="billToLastName" value="{{ old('billToLastName', Auth::user()->last_name ?? (explode(' ', Auth::user()->name, 2)[1] ?? '')) }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="family-name">
                        </div>
                    </div>
                    <div class="mt-4">
                        <label for="billToAddress" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Street Address') }} <span class="text-red-500">*</span></label>
                        <input type="text" id="billToAddress" name="billToAddress" value="{{ old('billToAddress', Auth::user()->billing_address ?? '') }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="street-address">
                    </div>
                     <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
                        <div>
                            <label for="billToCity" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('City') }} <span class="text-red-500">*</span></label>
                            <input type="text" id="billToCity" name="billToCity" value="{{ old('billToCity', Auth::user()->billing_city ?? '') }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="address-level2">
                        </div>
                        <div>
                            <label for="billToState" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('State/Province') }} <span class="text-red-500">*</span></label>
                            <input type="text" id="billToState" name="billToState" value="{{ old('billToState', Auth::user()->billing_state ?? '') }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="address-level1">
                        </div>
                        <div>
                            <label for="billToZip" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Zip/Postal Code') }} <span class="text-red-500">*</span></label>
                            <input type="text" id="billToZip" name="billToZip" value="{{ old('billToZip', Auth::user()->billing_zip ?? '') }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="postal-code">
                        </div>
                    </div>
                    <div class="mt-4 mb-6">
                        <label for="billToCountry" class="block text-sm font-medium text-gray-700 dark:text-gray-300">{{ __('Country') }} <span class="text-red-500">*</span></label>
                        <input type="text" id="billToCountry" name="billToCountry" value="{{ old('billToCountry', Auth::user()->billing_country ?? 'USA') }}" class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md shadow-sm" required autocomplete="country">
                    </div>

                    <div class="mt-6">
                        {{-- Changed button to trigger Accept.js dispatch --}}
                        <button type="button" id="authorizePayButton"
                                class="inline-flex items-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-blue-500 active:bg-blue-700 focus:outline-none focus:border-blue-700 focus:ring focus:ring-blue-200 disabled:opacity-25 transition">
                                Pay ${{ number_format($plan->price, 2) }}
                        </button>
                        {{-- This hidden submit button is still useful for the form submission after getting the nonce --}}
                        <button type="submit" id="submitPayment" style="display:none;">Submit Payment Data</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{-- Changed to Accept.js --}}
    <script type="text/javascript"
        src="{{ setting('authorizenet_mode', 'sandbox') == 'live' ? 'https://js.authorize.net/v1/Accept.js' : 'https://jstest.authorize.net/v1/Accept.js' }}"
        charset="utf-8">
    </script>

    <script type="text/javascript">
        function responseHandler(response) {
            console.log("Authorize.Net responseHandler called with response:", response); // Add this line
            const errorDiv = document.getElementById("acceptJsErrorDiv");
            errorDiv.style.display = "none"; // Hide error div initially
            // alert("Response handler called!"); // Or use an alert for quick testing
            if (response.messages.resultCode === "Error") {
                var i = 0;
                let errorText = "";
                while (i < response.messages.message.length) {
                    console.log(
                        response.messages.message[i].code + ": " +
                        response.messages.message[i].text
                    );
                    errorText += response.messages.message[i].text + "<br/>";
                    i = i + 1;
                }
                // Display error to user in the dedicated div
                errorDiv.innerHTML = "<strong>Payment Error:</strong><br/>" + errorText;
                errorDiv.style.display = "block";

                // Re-enable the Pay button or allow retry
                document.getElementById("authorizePayButton").disabled = false;

            } else {
                // Opaque data has been generated, set it to your hidden form fields
                document.getElementById("dataDescriptor").value = response.opaqueData.dataDescriptor;
                document.getElementById("dataValue").value = response.opaqueData.dataValue;

                // Programmatically submit the form
                document.getElementById("paymentForm").submit();
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            const payButton = document.getElementById('authorizePayButton');
            if (payButton) {
                payButton.addEventListener('click', function () {
                    this.disabled = true; // Disable button on click

                    var authData = {};
                        authData.clientKey = "{{ $publicClientKey }}";
                        authData.apiLoginID = "{{ $apiLoginId }}";

                    var cardData = {};
                        cardData.cardNumber = document.getElementById('cardNumber').value.replace(/\D/g, ''); // Remove non-digits
                        cardData.month = document.getElementById('expMonth').value;
                        cardData.year = document.getElementById('expYear').value;
                        cardData.cardCode = document.getElementById('cardCode').value;
                    // Add billing data to cardData for AVS
                        cardData.billTo = {};
                        cardData.billTo.firstName = document.getElementById('billToFirstName').value;
                        cardData.billTo.lastName = document.getElementById('billToLastName').value;
                        cardData.billTo.address = document.getElementById('billToAddress').value;
                        cardData.billTo.city = document.getElementById('billToCity').value;
                        cardData.billTo.state = document.getElementById('billToState').value;
                        cardData.billTo.zip = document.getElementById('billToZip').value;
                        cardData.billTo.country = document.getElementById('billToCountry').value;

                    var secureData = {};
                        secureData.authData = authData;
                        secureData.cardData = cardData;

                    Accept.dispatchData(secureData, responseHandler);
                });
            }
        });
    </script>
</x-app-layout>
