@extends('layouts.self-paced-landing')

@section('title', 'Payment — ' . $course->title)
@section('meta-description', 'Complete your payment to enroll in ' . $course->title)

@section('content')
<div class="max-w-lg mx-auto px-4 sm:px-6 lg:px-8 py-12">

    {{-- Header --}}
    <div class="text-center mb-8">
        <div class="inline-flex items-center justify-center w-16 h-16 bg-indigo-100 rounded-2xl mb-4">
            <i class="fas fa-credit-card text-indigo-600 text-2xl"></i>
        </div>
        <h1 class="text-2xl font-bold text-gray-800">Complete Your Payment</h1>
        <p class="text-sm text-gray-500 mt-1">{{ $course->title }}</p>
    </div>

    {{-- Payment status card --}}
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-5"
         x-data="paymentPoller()"
         x-init="init()">

        {{-- Course + amount summary --}}
        <div class="flex items-center gap-4 pb-4 mb-4 border-b border-gray-100">
            <div class="w-12 h-12 rounded-xl overflow-hidden flex-shrink-0">
                @if($course->featured_image && file_exists(public_path('storage/' . $course->featured_image)))
                    <img src="{{ asset('storage/' . $course->featured_image) }}" alt="{{ $course->title }}" class="w-full h-full object-cover">
                @else
                    <div class="w-full h-full flex items-center justify-center bg-indigo-50">
                        <i class="{{ $course->category->icon ?? 'fas fa-book' }} text-indigo-400"></i>
                    </div>
                @endif
            </div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-bold text-gray-800 truncate">{{ $course->title }}</p>
                <p class="text-xs text-gray-500">Enrollment #{{ $enrollment->id }}</p>
            </div>
            <div class="text-right flex-shrink-0">
                <p class="text-lg font-extrabold text-gray-900">
                    {{ number_format((float)$enrollment->amount_paid, 2) }} {{ $enrollment->currency ?? 'KES' }}
                </p>
                <p class="text-xs text-gray-400">{{ ucfirst($enrollment->payment_method ?? 'Online') }}</p>
            </div>
        </div>

        {{-- Fee breakdown --}}
        @if((float)$course->registration_fee > 0 || (float)$course->application_fee > 0)
        <div class="bg-gray-50 rounded-lg p-3 mb-4 text-xs space-y-1">
            @if((float)$course->registration_fee > 0)
            <div class="flex justify-between text-gray-600">
                <span>Registration Fee:</span>
                <span class="font-medium">{{ number_format((float)$course->registration_fee, 2) }} KES</span>
            </div>
            @endif
            @if((float)$course->application_fee > 0)
            <div class="flex justify-between text-gray-600">
                <span>Application Fee:</span>
                <span class="font-medium">{{ number_format((float)$course->application_fee, 2) }} KES</span>
            </div>
            @endif
        </div>
        @endif

        {{-- Payment reference --}}
        @if($enrollment->payment_reference)
        <div class="flex items-center justify-between bg-gray-50 rounded-xl px-4 py-2.5 mb-4 text-xs">
            <span class="text-gray-500 flex items-center gap-1.5">
                <i class="fas fa-hashtag text-indigo-400"></i> Reference
            </span>
            <span class="font-mono font-semibold text-gray-700">{{ $enrollment->payment_reference }}</span>
        </div>
        @endif

        {{-- Status indicator --}}
        <div class="mb-5">
            @if($enrollment->status === 'pending_payment')
                <div class="flex items-center gap-3 p-4 bg-amber-50 border border-amber-200 rounded-xl">
                    <div class="flex-shrink-0">
                        <i class="fas fa-spinner fa-spin text-amber-500 text-xl" x-show="polling"></i>
                        <i class="fas fa-clock text-amber-500 text-xl" x-show="!polling" x-cloak></i>
                    </div>
                    <div>
                        <p class="text-sm font-semibold text-amber-800">Waiting for Payment Verification</p>
                        <p class="text-xs text-amber-600 mt-0.5">
                            @if($enrollment->payment_method === 'paystack')
                                Your payment is being processed. This page will update automatically.
                            @else
                                Your payment proof has been submitted and is pending manager verification.
                            @endif
                        </p>
                    </div>
                </div>
            @elseif($enrollment->status === 'payment_failed')
                <div class="flex items-center gap-3 p-4 bg-red-50 border border-red-200 rounded-xl">
                    <i class="fas fa-times-circle text-red-500 text-xl flex-shrink-0"></i>
                    <div>
                        <p class="text-sm font-semibold text-red-800">Payment Failed</p>
                        <p class="text-xs text-red-600 mt-0.5">
                            The payment was not completed. Please retry below.
                        </p>
                    </div>
                </div>
            @elseif($enrollment->status === 'pending_verification')
                <div class="flex items-center gap-3 p-4 bg-blue-50 border border-blue-200 rounded-xl">
                    <i class="fas fa-hourglass-half text-blue-500 text-xl flex-shrink-0"></i>
                    <div>
                        <p class="text-sm font-semibold text-blue-800">Payment Proof Submitted</p>
                        <p class="text-xs text-blue-600 mt-0.5">
                            Your payment proof has been received. You'll be notified once it's verified.
                        </p>
                    </div>
                </div>
            @elseif($enrollment->canAccess())
                <div class="flex items-center gap-3 p-4 bg-green-50 border border-green-200 rounded-xl">
                    <i class="fas fa-check-circle text-green-500 text-xl flex-shrink-0"></i>
                    <div>
                        <p class="text-sm font-semibold text-green-800">Payment Confirmed!</p>
                        <p class="text-xs text-green-600 mt-0.5">Redirecting you to the course...</p>
                    </div>
                </div>
            @endif
        </div>

        {{-- Instructions for online payment --}}
        @if($enrollment->status === 'pending_payment' && $enrollment->payment_method === 'paystack')
        <div class="bg-blue-50 border border-blue-100 rounded-xl p-4 mb-5">
            <p class="text-xs font-semibold text-blue-800 mb-2 flex items-center gap-1.5">
                <i class="fas fa-info-circle text-blue-500"></i> How to Pay
            </p>
            <ol class="list-decimal list-inside space-y-1 text-xs text-blue-700">
                <li>Click the "Pay Now" button below to open the secure payment popup.</li>
                <li>Enter your payment details to complete the transaction.</li>
                <li>This page will update automatically once payment is confirmed.</li>
            </ol>
        </div>
        @endif

        {{-- Instructions for cash payment --}}
        @if($enrollment->status === 'pending_verification' && $enrollment->payment_method === 'cash')
        <div class="bg-blue-50 border border-blue-100 rounded-xl p-4 mb-5">
            <p class="text-xs font-semibold text-blue-800 mb-2 flex items-center gap-1.5">
                <i class="fas fa-info-circle text-blue-500"></i> What's Next?
            </p>
            <ol class="list-decimal list-inside space-y-1 text-xs text-blue-700">
                <li>Your payment proof has been submitted successfully.</li>
                <li>A manager will verify your proof within 24 hours.</li>
                <li>You'll receive an email confirmation once approved.</li>
            </ol>
        </div>
        @endif

        {{-- Auto-polling status --}}
        <div class="text-center text-xs text-gray-400 mb-4" x-show="polling">
            <i class="fas fa-sync fa-spin mr-1"></i>
            Checking payment status automatically...
        </div>
        @endif

    </div>

    {{-- Retry payment form (shown when failed or pending) --}}
    @if(in_array($enrollment->status, ['payment_failed', 'pending_payment']))
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-5">
        <h3 class="text-sm font-bold text-gray-700 mb-3 flex items-center gap-2">
            <i class="fas fa-redo text-indigo-400"></i>
            {{ $enrollment->status === 'payment_failed' ? 'Retry Payment' : 'Complete Payment' }}
        </h3>

        {{-- Payment method selector based on payment_mode --}}
        <div class="space-y-3">
            @if($course->acceptsOnlinePayment())
            <button type="button"
                    @click="paymentMethod = 'online'; proceedOnlinePayment()"
                    class="w-full flex items-center justify-center gap-2 px-5 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm rounded-xl transition shadow-md shadow-indigo-200">
                <i class="fas fa-credit-card"></i>
                Pay via Paystack
            </button>
            @endif

            @if($course->acceptsCashPayment())
            <button type="button"
                    @click="paymentMethod = 'cash'; showCashProofForm()"
                    class="w-full flex items-center justify-center gap-2 px-5 py-3 bg-green-600 hover:bg-green-700 text-white font-bold text-sm rounded-xl transition shadow-md shadow-green-200">
                <i class="fas fa-receipt"></i>
                Pay with Proof Upload
            </button>
            @endif
        </div>
    </div>
    @endif

    {{-- Cash proof upload form (shown conditionally) --}}
    @if($course->acceptsCashPayment())
    <div id="cashProofForm" class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-5" style="display: none;">
        <h3 class="text-sm font-bold text-gray-700 mb-3 flex items-center gap-2">
            <i class="fas fa-receipt text-green-400"></i>
            Upload Payment Proof
        </h3>
        <p class="text-xs text-gray-600 mb-4">
            Upload a screenshot of your M-Pesa, bank slip, or institution receipt as proof of payment.
        </p>

        <form method="POST" action="{{ route('self-paced.public.payment.proof', [$course, $enrollment]) }}" enctype="multipart/form-data">
            @csrf

            <div class="mb-4">
                <label class="block text-xs font-semibold text-gray-600 mb-2">Proof Type</label>
                <select name="proof_type" class="w-full px-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-green-300">
                    <option value="">Select type...</option>
                    <option value="mpesa">M-Pesa Screenshot</option>
                    <option value="bank_slip">Bank Slip</option>
                    <option value="institution_receipt">Institution Receipt</option>
                </select>
            </div>

            <div class="mb-4">
                <label class="block text-xs font-semibold text-gray-600 mb-2">Upload File (JPEG, PNG, or PDF - Max 5MB)</label>
                <input type="file" name="file" accept=".jpg,.jpeg,.png,.pdf" class="w-full px-4 py-2.5 border border-gray-200 rounded-xl text-sm">
            </div>

            <button type="submit" class="w-full flex items-center justify-center gap-2 px-5 py-3 bg-green-600 hover:bg-green-700 text-white font-bold text-sm rounded-xl transition shadow-md">
                <i class="fas fa-upload"></i>
                Submit Proof
            </button>
        </form>
    </div>
    @endif

    {{-- Back link --}}
    <div class="text-center">
        <a href="{{ route('self-paced.public.courses.show', $course) }}"
           class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-indigo-600 transition">
            <i class="fas fa-arrow-left text-xs"></i>
            Back to Course
        </a>
    </div>

</div>
@endsection

@push('scripts')
<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
function paymentPoller() {
    return {
        polling: {{ $enrollment->status === 'pending_payment' ? 'true' : 'false' }},
        pollInterval: null,
        paymentMethod: '{{ $enrollment->payment_method }}',
        statusUrl: '{{ route("api.self-paced.payment.status", [$course, $enrollment]) }}',
        redirectUrl: '{{ route("self-paced.learn.overview", $course) }}',

        init() {
            if (this.polling && this.paymentMethod === 'paystack') {
                this.startPolling();
            }
        },

        startPolling() {
            this.pollInterval = setInterval(() => {
                this.checkStatus();
            }, 5000);
        },

        checkStatus() {
            axios.get(this.statusUrl)
                .then(response => {
                    if (response.data.can_access) {
                        clearInterval(this.pollInterval);
                        this.polling = false;
                        window.location.href = response.data.redirect_url || this.redirectUrl;
                    } else if (response.data.status === 'payment_failed') {
                        clearInterval(this.pollInterval);
                        this.polling = false;
                        window.location.reload();
                    }
                })
                .catch(() => {
                    // Silently continue polling
                });
        },

        proceedOnlinePayment() {
            // Initialize Paystack payment
            axios.post('{{ route("self-paced.public.payment.init", [$course, $enrollment]) }}')
                .then(response => {
                    const config = response.data;
                    const paystackPopup = PaystackPop.setup(config);
                    paystackPopup.openIframe();
                })
                .catch(error => {
                    alert('Error initializing payment. Please try again.');
                });
        },

        showCashProofForm() {
            document.getElementById('cashProofForm').style.display = 'block';
            document.getElementById('cashProofForm').scrollIntoView({ behavior: 'smooth' });
        }
    };
}
</script>
@endpush
