@extends('layouts.themed-app')

@section('content')
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4 py-6">
    <div class="w-full max-w-xl rounded-2xl bg-white p-6 shadow-xl">
        <div class="mb-6">
            <h2 class="text-2xl font-semibold text-slate-900">Complete Payment to Continue</h2>
            <p class="mt-2 text-sm text-slate-600">Your 7-day trial has ended. Please provide payment details to continue using TrueTrucker.</p>
        </div>

        @if ($errors->any())
            <div class="mb-4 rounded-lg border border-red-300 bg-red-50 p-3">
                @foreach ($errors->all() as $error)
                    <p class="text-sm text-red-700">{{ $error }}</p>
                @endforeach
            </div>
        @endif

        <form id="trial-payment-form" method="POST" action="{{ route('trial-payment.complete') }}">
            @csrf
            <div class="space-y-4">
                <div class="rounded-lg border border-blue-200 bg-blue-50 p-4">
                    <div class="flex justify-between items-center">
                        <span class="font-semibold text-slate-900">Amount Due</span>
                        <span class="text-lg font-bold text-blue-600">${{ number_format($amount, 2) }}</span>
                    </div>
                    <p class="text-sm text-slate-600 mt-2">{{ $subscription->package->name }} • {{ $subscription->last_driver_count }} driver(s)</p>
                </div>

                <div class="grid gap-4 md:grid-cols-2">
                    <label class="block text-sm font-medium text-slate-700">
                        Cardholder Name
                        <span id="cardholder-required" class="text-red-600">*</span>
                        <input type="text" id="cardholder-name" name="payment[cardholder_name]" class="input mt-1 w-full" placeholder="Jane Doe">
                    </label>
                    <div class="block text-sm font-medium text-slate-700">
                        Card Details
                        <div id="card-element" class="mt-1 rounded-xl border border-slate-300 bg-white p-3"></div>
                    </div>
                </div>

                <fieldset class="space-y-2 rounded-lg border border-slate-200 bg-slate-50 p-4">
                    <legend class="text-sm font-semibold text-slate-900">Save card preference</legend>
                    <label class="flex items-center gap-3">
                        <input type="radio" name="payment[save_option]" value="save_auto_renew" checked="checked" onchange="updateSaveOption(true)">
                        <span><strong>Save card & auto-renew</strong><br><span class="text-sm text-slate-500">Use this card automatically for future renewals.</span></span>
                    </label>
                    <label class="flex items-center gap-3">
                        <input type="radio" name="payment[save_option]" value="no_save" onchange="updateSaveOption(false)">
                        <span><strong>Do not save card</strong><br><span class="text-sm text-slate-500">Use this card only for this payment and do not keep it on file.</span></span>
                    </label>
                </fieldset>

                <p id="payment-save-note" class="text-sm text-slate-500">Your card will be saved and used automatically for future renewals.</p>
                <div id="card-errors" class="text-sm text-rose-600"></div>

                <div class="flex items-center justify-end gap-3 border-t border-slate-200 pt-4">
                    <a href="{{ route('dashboard') }}" class="btn bg-gray-200 text-slate-700 px-4 py-2 rounded">Back to Dashboard</a>
                    <button id="pay-button" type="button" onclick="handlePaymentSubmit()" class="btn bg-green-600 text-white px-4 py-2 rounded">
                        <span class="pay-button-text">Pay ${{ number_format($amount, 2) }}</span>
                    </button>
                </div>
            </div>

            <input type="hidden" name="payment[stripe_payment_intent_id]" id="stripe-payment-intent-id">
        </form>
    </div>
</div>

<style>
.input { border: 2px solid #E5E7EB; border-radius: 0.5rem; padding: 0.75rem 1rem; font-size: 1rem; }
.input:focus { border-color: #003D7A; outline: none; }
.btn { transition: background 0.2s, color 0.2s; }
</style>

<script src="https://js.stripe.com/v3/"></script>
<script>
    let stripe = null;
    let elements = null;
    let cardElement = null;
    let currentClientSecret = null;

    function initStripe() {
        if (stripe) return;

        stripe = Stripe('{{ config('services.stripe.public') }}');
        elements = stripe.elements();
        cardElement = elements.create('card', {
            style: {
                base: {
                    color: '#0f172a',
                    fontSize: '16px',
                    fontFamily: 'Inter, system-ui, sans-serif',
                    '::placeholder': {
                        color: '#94a3b8',
                    },
                },
                invalid: {
                    color: '#b91c1c',
                },
            },
        });
        cardElement.mount('#card-element');
    }

    function updateSaveOption(isSave) {
        const note = document.getElementById('payment-save-note');
        const cardholderInput = document.getElementById('cardholder-name');
        const cardholderRequired = document.getElementById('cardholder-required');
        const cardErrors = document.getElementById('card-errors');
        
        note.textContent = isSave
            ? 'Your card will be saved and used automatically for future renewals.'
            : 'Your card will be used for this payment only and will not be saved for future billing.';

        cardholderInput.required = true;
        cardholderRequired.style.display = 'inline';
        cardErrors.textContent = ''; // Clear any validation errors
    }

    function showCardError(message) {
        document.getElementById('card-errors').textContent = message;
    }

    function setSubmitLoading(isLoading) {
        const payButton = document.getElementById('pay-button');
        if (!payButton) return;

        if (isLoading) {
            payButton.disabled = true;
            payButton.classList.add('opacity-70', 'cursor-not-allowed');
            payButton.innerHTML = '<span class="inline-block h-4 w-4 mr-2 animate-spin rounded-full border-2 border-white border-t-transparent"></span><span>Processing…</span>';
        } else {
            payButton.disabled = false;
            payButton.classList.remove('opacity-70', 'cursor-not-allowed');
            payButton.innerHTML = '<span class="pay-button-text">Pay ${{ number_format($amount, 2) }}</span>';
        }
    }

    async function createPaymentIntent() {
        const saveOption = document.querySelector('input[name="payment[save_option]"]:checked')?.value || 'save_auto_renew';
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        const response = await fetch('{{ route('trial-payment.intent') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': token,
                'Accept': 'application/json',
            },
            body: JSON.stringify({ save_option: saveOption }),
        });

        const data = await response.json();
        if (!response.ok) {
            throw new Error(data.error || 'Unable to create payment intent');
        }

        currentClientSecret = data.client_secret;
        return data;
    }

    async function handlePaymentSubmit() {
        const saveOption = document.querySelector('input[name="payment[save_option]"]:checked')?.value || 'save_auto_renew';
        const name = document.getElementById('cardholder-name').value.trim();

        showCardError('');

        if (!name) {
            showCardError('Please enter the cardholder name.');
            return;
        }

        setSubmitLoading(true);
        try {
            initStripe();
            const data = await createPaymentIntent();
            const clientSecret = data.client_secret;

            const result = await stripe.confirmCardPayment(clientSecret, {
                payment_method: {
                    card: cardElement,
                    billing_details: {
                        name,
                    },
                },
                setup_future_usage: saveOption === 'save_auto_renew' ? 'off_session' : undefined,
            });

            if (result.error) {
                showCardError(result.error.message || 'Payment failed.');
                setSubmitLoading(false);
                return;
            }

            if (!result.paymentIntent || result.paymentIntent.status !== 'succeeded') {
                showCardError('Payment was not completed.');
                setSubmitLoading(false);
                return;
            }

            document.getElementById('stripe-payment-intent-id').value = result.paymentIntent.id;
            document.getElementById('trial-payment-form').submit();
        } catch (error) {
            showCardError(error.message || 'Payment processing error.');
            setSubmitLoading(false);
        }
    }

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        initStripe();
        updateSaveOption(true); // Save card is default
        
        // Also clear errors when radio buttons change
        document.querySelectorAll('input[name="payment[save_option]"]').forEach(radio => {
            radio.addEventListener('change', function() {
                document.getElementById('card-errors').textContent = '';
            });
        });
    });
</script>
@endsection
