{{-- d:\projects\digitalvocano\resources\views\subscriptions\checkout.blade.php --}}
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Subscribe to') }} {{ $subscriptionPlan->name }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-xl sm:rounded-lg">
                <div class="p-6 lg:p-8">
                    <h3 class="text-2xl font-semibold text-gray-900 dark:text-gray-100 mb-6">
                        Confirm Your Subscription
                    </h3>

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


                    <div class="mb-6 p-4 border border-gray-200 dark:border-gray-700 rounded-md">
                        <h4 class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ $subscriptionPlan->name }}</h4>
                        <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                            ${{ number_format($subscriptionPlan->price, 2) }}
                            <span class="text-sm font-normal text-gray-500 dark:text-gray-400">/ {{ $subscriptionPlan->interval_count > 1 ? $subscriptionPlan->interval_count : '' }} {{ Str::plural($subscriptionPlan->interval, $subscriptionPlan->interval_count) }}</span>
                        </p>
                        @if($subscriptionPlan->description)
                            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">{{ $subscriptionPlan->description }}</p>
                        @endif
                         @if($subscriptionPlan->trial_period_days > 0)
                            <p class="text-sm text-green-600 dark:text-green-400 mt-1">{{ $subscriptionPlan->trial_period_days }}-day free trial included.</p>
                        @endif
                    </div>

                    {{--
                        This is where your payment form will go.
                        It will depend on the payment gateways you integrate (Stripe, PayPal, etc.).
                        For now, it's a placeholder.

                        The form action should point to the route that handles the subscription processing.
                    --}}
                    <form action="{{ route('subscription.process', $subscriptionPlan) }}" method="POST" id="payment-form">
                    {{-- <form id="payment-form" method="POST" action="YOUR_SERVER_SIDE_SCRIPT_URL"> --}}
                        @csrf
                        <input type="hidden" name="authorizenet_data_value" id="authorizenet_data_value">
                        <input type="hidden" name="authorizenet_data_descriptor" id="authorizenet_data_descriptor">

                        @if(count($paymentGateways) > 0)
                            <div class="mb-4">
                                <label for="payment_method" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Payment Method</label>
                                <select name="payment_method" id="payment_method" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
                                    @foreach($paymentGateways as $key => $gateway)
                                        <option value="{{ $key }}">
                                            {{ $gateway['name'] }}
                                            @if($key === 'wallet' && isset($gateway['balance']))
                                                (Balance: ${{ number_format($gateway['balance'], 2) }})
                                            @endif
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- Authorize.Net Specific Fields (Show when Authorize.Net is selected) --}}
                            <div id="authorizenet-fields" class="hidden mt-6 border-t border-gray-200 dark:border-gray-700 pt-6">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-3">Authorize.Net Payment Details</h4>
                                <div class="space-y-4">
                                    <div>
                                        <label for="authorizenet_card_number" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Card Number</label>
                                        {{-- This input will be replaced or hidden by Accept.js. Style the div if needed. --}}
                                        <div id="authorizenet_card_number_div" class="mt-1 block w-full h-10 p-2 rounded-md border-gray-300 shadow-sm focus-within:border-indigo-300 focus-within:ring focus-within:ring-indigo-200 focus-within:ring-opacity-50 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                                            {{-- Accept.js will mount its secure field here --}}
                                        </div>
                                        {{-- Keep a hidden input for validation or other purposes if absolutely necessary, but Accept.js handles the actual data --}}
                                        {{-- <input type="text" name="authorizenet_card_number" id="authorizenet_card_number" class="sr-only"> --}}
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label for="authorizenet_expiration_date" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Expiration Date (YYYY-MM)</label>
                                            <div id="authorizenet_expiration_date_div" class="mt-1 block w-full h-10 p-2 rounded-md border-gray-300 shadow-sm focus-within:border-indigo-300 focus-within:ring focus-within:ring-indigo-200 focus-within:ring-opacity-50 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                                                {{-- Accept.js will mount its secure field here --}}
                                            </div>
                                            {{-- <input type="text" name="authorizenet_expiration_date" id="authorizenet_expiration_date" class="sr-only"> --}}
                                        </div>
                                        <div>
                                            <label for="authorizenet_cvv" class="block text-sm font-medium text-gray-700 dark:text-gray-300">CVV</label>
                                            <div id="authorizenet_cvv_div" class="mt-1 block w-full h-10 p-2 rounded-md border-gray-300 shadow-sm focus-within:border-indigo-300 focus-within:ring focus-within:ring-indigo-200 focus-within:ring-opacity-50 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200">
                                                {{-- Accept.js will mount its secure field here --}}
                                            </div>
                                            {{-- <input type="text" name="authorizenet_cvv" id="authorizenet_cvv" class="sr-only"> --}}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {{-- End Authorize.Net Fields --}}

                            {{-- Placeholder for other payment gateway specific fields (e.g., Stripe Elements, PayPal button) --}}
                            <div id="other-gateway-fields-container" class="my-4 hidden">
                                {{-- Content for other gateways will be dynamically shown here if needed --}}
                            </div>

                            <button type="button" id="submit-payment-button" {{-- Changed type to button for Accept.js --}}
                                    class="w-full bg-green-600 hover:bg-green-700 text-white font-semibold py-3 px-4 rounded-lg text-center transition duration-150 ease-in-out">
                                <span id="button-text">Subscribe Now</span>
                                <span id="loading-indicator" class="hidden">Processing...</span>
                                Subscribe Now
                            </button>
                        @else
                             <p class="text-center text-red-500 dark:text-red-400">
                                No payment gateways are currently configured for this plan. Please contact support.
                            </p>
                        @endif


                    </form>

                    <div class="mt-6 text-center">
                        <a href="{{ route('subscription.plans') }}" class="text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                            &larr; Back to Plans
                        </a>
                    </div>

                </div>
            </div>
        </div>
    </div>
    {{-- Determine environment for Accept.js --}}
    @php
        $authorizeNetMode = setting('authorizenet_mode', 'sandbox');
        $acceptJsUrl = ($authorizeNetMode === 'live')
            ? 'https://js.authorize.net/v1/Accept.js'
            : 'https://jstest.authorize.net/v1/Accept.js';
    @endphp
    <script type="text/javascript" src="{{ $acceptJsUrl }}" charset="utf-8"></script>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const paymentMethodSelect = document.getElementById('payment_method');
            const authorizeNetFields = document.getElementById('authorizenet-fields');
            const paymentForm = document.getElementById('payment-form');
            const submitButton = document.getElementById('submit-payment-button');
            const buttonText = document.getElementById('button-text');
            const loadingIndicator = document.getElementById('loading-indicator');

            // Will be populated if Authorize.Net is selected and configured
            let authorizeNetApiLoginId = null;
            let authorizeNetPublicClientKey = null;

            function togglePaymentFields() {
                const selectedMethod = paymentMethodSelect.value;

                // Hide all specific field sections first
                if(authorizeNetFieldsDiv) authorizeNetFieldsDiv.classList.add('hidden');

                if (selectedMethod === 'authorizenetgateway') {
                    const selectedOption = paymentMethodSelect.options[paymentMethodSelect.selectedIndex];
                    // Retrieve keys from data attributes if you embed them, or from a JS object passed from PHP
                    // For this example, we assume $paymentGateways[$key] in PHP has apiLoginId and publicClientKey
                    @if(isset($paymentGateways['authorizenetgateway']))
                        authorizeNetApiLoginId = "{{ $paymentGateways['authorizenetgateway']['apiLoginId'] ?? '' }}";
                        authorizeNetPublicClientKey = "{{ $paymentGateways['authorizenetgateway']['publicClientKey'] ?? '' }}";
                    @endif

                    if (!authorizeNetApiLoginId || !authorizeNetPublicClientKey) {
                        console.error('Authorize.Net API Login ID or Public Client Key is missing.');
                        // Optionally display an error to the user
                        if(authorizeNetFieldsDiv) authorizeNetFieldsDiv.classList.remove('hidden'); // Show the section to display an error
                        authorizeNetFieldsDiv.innerHTML = '<p class="text-red-500">Authorize.Net configuration is incomplete. Please contact support.</p>';
                        submitButton.disabled = true;
                        return;
                    }
                    submitButton.disabled = false;
                    if(authorizeNetFieldsDiv) authorizeNetFieldsDiv.classList.remove('hidden');
                } // else if (selectedMethod === 'other_gateway_key') { ... }
            }

            if (submitButton) {
                submitButton.addEventListener('click', function() {
                    const selectedMethod = paymentMethodSelect.value;
                    if (selectedMethod === 'authorizenetgateway') {
                        if (!authorizeNetApiLoginId || !authorizeNetPublicClientKey) {
                            alert('Authorize.Net is not configured correctly.');
                            return;
                        }
                        setLoadingState(true);
                        sendPaymentDataToAnet();
                    } else {
                        // For other payment methods, submit the form directly
                        paymentForm.submit();
                    }
                });
            }

            function setLoadingState(isLoading) {
                if (isLoading) {
                    submitButton.disabled = true;
                    buttonText.classList.add('hidden');
                    loadingIndicator.classList.remove('hidden');
                } else {
                    submitButton.disabled = false;
                    buttonText.classList.remove('hidden');
                    loadingIndicator.classList.add('hidden');
                }
            }

            function sendPaymentDataToAnet() {
                var authData = {};
                authData.clientKey = authorizeNetPublicClientKey;
                authData.apiLoginID = authorizeNetApiLoginId;

                var cardData = {};
                // These are IDs of the divs where Accept.js mounts its fields
                cardData.cardNumber = document.getElementById('authorizenet_card_number_div').querySelector('iframe') ? undefined : document.getElementById('authorizenet_card_number_div').innerText; // Fallback for testing if iframe not loaded
                cardData.month = document.getElementById('authorizenet_expiration_date_div').querySelector('iframe') ? undefined : document.getElementById('authorizenet_expiration_date_div').innerText.split('-')[1]; // Fallback
                cardData.year = document.getElementById('authorizenet_expiration_date_div').querySelector('iframe') ? undefined : document.getElementById('authorizenet_expiration_date_div').innerText.split('-')[0]; // Fallback
                cardData.cardCode = document.getElementById('authorizenet_cvv_div').querySelector('iframe') ? undefined : document.getElementById('authorizenet_cvv_div').innerText; // Fallback

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

                Accept.dispatchData(secureData, responseHandler);
            }

            function responseHandler(response) {
                setLoadingState(false);
                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 + "\n";
                        i = i + 1;
                    }
                    alert("Payment Error: " + errorText.trim());
                } else {
                    document.getElementById("authorizenet_data_descriptor").value = response.opaqueData.dataDescriptor;
                    document.getElementById("authorizenet_data_value").value = response.opaqueData.dataValue;
                    paymentForm.submit();
                }
            }


            if (paymentMethodSelect) {
                paymentMethodSelect.addEventListener('change', togglePaymentFields);
                togglePaymentFields(); // Call on page load to set initial state
            }
        });
    </script>
    @endpush
</x-app-layout>
