@extends('layouts.app') {{-- Or your main app layout --}}

@section('title', __('Deposit Funds with Authorize.Net'))

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="max-w-lg mx-auto bg-white dark:bg-gray-800 shadow-md rounded-lg p-6">
        <h1 class="text-2xl font-semibold text-gray-700 dark:text-gray-200 mb-6">{{ __('Deposit Funds') }}</h1>

        <div class="mb-4 p-4 border border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900 rounded">
            <p class="text-lg font-medium text-blue-700 dark:text-blue-300">{{ __('Amount to Deposit:') }} {{ setting('currency_symbol', '$') }}{{ number_format($amount, 2) }}</p>
        </div>

        @if(session('error'))
            <div class="mb-4 p-4 text-sm text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" 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 dark:bg-red-200 dark:text-red-800" role="alert" style="display: none;">
            {{-- Errors will be inserted here by JavaScript --}}
        </div>

        <form id="paymentForm"
            action="{{ route('wallet.authorizenet.processDeposit') }}"
            method="POST">
            @csrf
            <input type="hidden" name="amount" value="{{ $amount }}">

            {{-- Accept.js will populate these --}}
            <input type="hidden" name="authorizenet_data_descriptor" id="dataDescriptor" value="">
            <input type="hidden" name="authorizenet_data_value" id="dataValue" value="">

            {{-- Card Information Fields for Accept.js --}}
            <div class="mb-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 mb-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="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="flex justify-end">
                <button type="button" id="authorizePayButton"
                        class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition ease-in-out duration-150">
                    {{ __('Pay') }} {{ setting('currency_symbol', '$') }}{{ number_format($amount, 2) }}
                </button>
            </div>
        </form>
    </div>
</div>

<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">
    document.addEventListener('DOMContentLoaded', function () {
        const payButton = document.getElementById('authorizePayButton');
        if (payButton) {
            payButton.addEventListener('click', function () {
                this.disabled = true; // Disable button on click
                const errorDiv = document.getElementById("acceptJsErrorDiv");
                errorDiv.style.display = "none"; // Hide error div initially

                var secureData = {};
                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;

                secureData.cardData = cardData;
                secureData.authData = authData;

                Accept.dispatchData(secureData, function(response) { // responseHandler
                    if (response.messages.resultCode === "Error") {
                        var i = 0;
                        let errorText = "<strong>Payment Error:</strong><br/>";
                        while (i < response.messages.message.length) {
                            errorText += response.messages.message[i].code + ": " + response.messages.message[i].text + "<br/>";
                            i = i + 1;
                        }
                        // Display error to user in the dedicated div
                        errorDiv.innerHTML = errorText;
                        errorDiv.style.display = "block";
                        payButton.disabled = false; // Re-enable button
                    } else {
                        document.getElementById('dataDescriptor').value = response.opaqueData.dataDescriptor;
                        document.getElementById('dataValue').value = response.opaqueData.dataValue;
                        document.getElementById('paymentForm').submit();
                    }
                });
            });
        }
    });
</script>
@endsection