@extends('layouts.user')

@section('title', __('subscriptions.processing'))
@section('page_title', __('subscriptions.processing'))
@section('breadcrumb', __('subscriptions.billing'))

@section('content')
<div class="min-h-[70vh] flex items-center justify-center px-4 py-10">
    <div class="w-full max-w-2xl rounded-3xl border border-slate-200 bg-white p-8 md:p-10 shadow-xl text-center">

        <div class="mx-auto flex h-24 w-24 items-center justify-center rounded-full bg-blue-50">
            <div class="h-14 w-14 animate-spin rounded-full border-4 border-blue-200 border-t-blue-600"></div>
        </div>

        <h1 class="mt-6 text-2xl md:text-3xl font-bold text-slate-800">{{ __('subscriptions.processing_your_request') }}</h1>
        <p class="mt-3 text-sm md:text-base text-slate-500" id="statusText">
            {{ __('subscriptions.please_wait_while_processing_request') }}
        </p>

        <div class="mt-8 rounded-3xl border border-blue-100 bg-gradient-to-r from-blue-50 to-indigo-50 p-6">
            <div class="text-sm text-slate-500">{{ __('subscriptions.checking_status_in') }}</div>
            <div id="countdown" class="mt-2 text-4xl font-extrabold text-blue-700">10</div>
            <p class="mt-2 text-sm text-slate-600">{{ __('subscriptions.request_under_review') }}</p>
        </div>

        <div id="resultBox" class="mt-6 hidden rounded-3xl p-5">
            <h3 id="resultTitle" class="text-lg font-bold"></h3>
            <p id="resultMessage" class="mt-2 text-sm"></p>
        </div>

        <div class="mt-6">
            <a href="{{ route('user.subscriptions.index') }}"
               class="inline-flex items-center justify-center rounded-2xl border border-slate-300 bg-white px-5 py-3 text-sm font-semibold text-slate-700 shadow-sm transition hover:bg-slate-50">
                {{ __('subscriptions.back_to_subscriptions') }}
            </a>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    let timeLeft = 10;
    let finished = false;

    const countdownEl = document.getElementById('countdown');
    const statusText = document.getElementById('statusText');
    const resultBox = document.getElementById('resultBox');
    const resultTitle = document.getElementById('resultTitle');
    const resultMessage = document.getElementById('resultMessage');

    async function checkSubscriptionStatusOnce() {
        if (finished) return;

        try {
            const response = await fetch("{{ route('user.subscriptions.check-status', $subscriptionRequest->id) }}", {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            });

            if (!response.ok) {
                window.location.href = "{{ route('user.subscriptions.index') }}";
                return;
            }

            const data = await response.json();

            if (data.status === 'approved' || data.has_active_subscription) {
                finished = true;

                resultBox.classList.remove('hidden');
                resultBox.className = 'mt-6 rounded-3xl border border-emerald-200 bg-emerald-50 p-5';
                resultTitle.className = 'text-lg font-bold text-emerald-800';
                resultMessage.className = 'mt-2 text-sm text-emerald-700';

                resultTitle.textContent = @json(__('subscriptions.subscription_approved'));
                resultMessage.textContent =
                    data.active_plan_name
                    ? @json(__('subscriptions.plan_now_active_prefix')) + data.active_plan_name + @json(__('subscriptions.plan_now_active_suffix')) + (data.active_end_date ? @json(__('subscriptions.expiry_prefix')) + data.active_end_date : '')
                    : @json(__('subscriptions.subscription_now_active'));

                statusText.textContent = @json(__('subscriptions.subscription_approved_successfully'));
                countdownEl.textContent = '0';

                Swal.fire({
                    icon: 'success',
                    title: @json(__('subscriptions.subscription_approved')),
                    text: data.active_plan_name
                        ? @json(__('subscriptions.plan_now_active_prefix')) + data.active_plan_name + @json(__('subscriptions.plan_now_active_short_suffix'))
                        : @json(__('subscriptions.subscription_now_active')),
                    confirmButtonColor: '#2563eb'
                }).then(() => {
                    window.location.href = "{{ route('user.dashboard') }}";
                });

                return;
            }

            if (data.status === 'cancelled') {
                finished = true;

                resultBox.classList.remove('hidden');
                resultBox.className = 'mt-6 rounded-3xl border border-red-200 bg-red-50 p-5';
                resultTitle.className = 'text-lg font-bold text-red-800';
                resultMessage.className = 'mt-2 text-sm text-red-700';

                resultTitle.textContent = @json(__('subscriptions.request_cancelled'));
                resultMessage.textContent = @json(__('subscriptions.subscription_request_cancelled_new_request_needed'));

                statusText.textContent = @json(__('subscriptions.request_no_longer_pending'));
                countdownEl.textContent = '0';

                Swal.fire({
                    icon: 'warning',
                    title: @json(__('subscriptions.request_cancelled')),
                    text: @json(__('subscriptions.subscription_request_cancelled_choose_plan_again')),
                    confirmButtonColor: '#2563eb'
                }).then(() => {
                    window.location.href = "{{ route('user.subscriptions.index') }}";
                });

                return;
            }

            // still pending -> redirect to subscriptions page
            finished = true;

            resultBox.classList.remove('hidden');
            resultBox.className = 'mt-6 rounded-3xl border border-amber-200 bg-amber-50 p-5';
            resultTitle.className = 'text-lg font-bold text-amber-800';
            resultMessage.className = 'mt-2 text-sm text-amber-700';

            resultTitle.textContent = @json(__('subscriptions.still_pending'));
            resultMessage.textContent = @json(__('subscriptions.request_still_pending_redirecting'));

            statusText.textContent = @json(__('subscriptions.request_still_under_review'));
            countdownEl.textContent = '0';

            setTimeout(() => {
                window.location.href = "{{ route('user.subscriptions.index') }}";
            }, 1500);

        } catch (error) {
            console.error('Polling failed:', error);
            window.location.href = "{{ route('user.subscriptions.index') }}";
        }
    }

    const interval = setInterval(() => {
        if (finished) {
            clearInterval(interval);
            return;
        }

        timeLeft--;
        if (countdownEl) countdownEl.textContent = timeLeft;

        if (timeLeft <= 0) {
            clearInterval(interval);
            checkSubscriptionStatusOnce();
        }
    }, 1000);
</script>
@endsection