@php
    $mode = app(\App\Settings\PaypalSetting::class)->mode;
    $baseUrl = $mode === 'sandbox' ? 'https://sandbox.paypal.com' : 'https://www.paypal.com';
    $clientId = app(\App\Settings\PaypalSetting::class)->client_id;
@endphp

<div class="page page-center">
    <div class="container container-tight py-4">
        <div class="card card-md">
            <div class="card-body text-center py-4 p-sm-5">
                <img src="/storage/{{ $campaign->data_attribute['logo'] }}" width="100%" height="auto" class="mb-4" alt="{{ $campaign->data_attribute['name'] }}">
                <h1>{{ $campaign->data_attribute['name'] }}</h1>
                <p style="text-align: center;">{!! $campaign->data_attribute['description'] !!}</p>

                @if (session('error'))
                    <div class="alert alert-danger alert-dismissible" role="alert">
                        {{ session('error') }}
                        <a class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
                    </div>
                @endif

                @error('payment')
                <div class="alert alert-danger alert-dismissible" role="alert">
                    {{ $message }}
                    <a class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
                </div>
                @enderror
            </div>
            <div class="hr-text hr-text-center hr-text-spaceless">
                @if($currentStep == 1)
                    <mark>Select your plan</mark>
                @endif
                @if($currentStep == 2)
                    <mark>Your Information</mark>
                @endif
                @if($currentStep == 3)
                    <mark>Check your order</mark>
                @endif
                @if($currentStep == $totalSteps)
                    <mark>Confirm payment</mark>
                @endif
            </div>
            <div class="card-body">
                @if($currentStep == 1)
                    <div class="form-selectgroup form-selectgroup-boxes d-flex flex-column">
                        @foreach($prices as $price)
                            <label class="form-selectgroup-item flex-fill">
                                <input type="radio"
                                       wire:model="selectedPriceId"
                                       value="{{ $price->id }}"
                                       class="form-selectgroup-input">
                                <div class="form-selectgroup-label d-flex align-items-center p-3">
                                    <div class="me-3">
                                        <span class="form-selectgroup-check"></span>
                                    </div>
                                    <div class="form-selectgroup-label-content d-flex align-items-center">
                                        <div>
                                            <h2 class="font-weight-medium mb-0">
                                                {{ \Illuminate\Support\Number::currency($price->amount) }}
                                            </h2>
                                            <div class="text-secondary">{{ $price->name }}</div>
                                        </div>
                                    </div>
                                </div>
                            </label>
                        @endforeach
                        @error('selectedPriceId') <span class="text-danger">{{ $message }}</span> @enderror
                    </div>
                @endif
                @if($currentStep == 2)
                    <div class="row">
                        <div class="col-md-6 mb-3 mb-md-0">
                            <div class="input-icon">
                            <span class="input-icon-addon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0"></path>
                                    <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path>
                                </svg>
                            </span>
                                <input type="text" wire:model="firstName" class="form-control @error('firstName') is-invalid @enderror" placeholder="First Name">
                                @error('firstName') <div class="text-danger mt-1">{{ $message }}</div> @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="input-icon">
                            <span class="input-icon-addon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0"></path>
                                    <path d="M6 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path>
                                </svg>
                            </span>
                                <input type="text" wire:model="lastName" class="form-control @error('lastName') is-invalid @enderror" placeholder="Last Name">
                                @error('lastName') <div class="text-danger mt-1">{{ $message }}</div> @enderror
                            </div>
                        </div>
                    </div>
                    <div class="input-icon mt-3">
                        <span class="input-icon-addon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10z">
                                </path>
                                <path d="M3 7l9 6l9 -6"></path>
                            </svg>
                        </span>
                        <input type="email" wire:model="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email address">
                        @error('email') <div class="text-danger mt-1">{{ $message }}</div> @enderror
                    </div>
                @endif
                @if($currentStep == 3)
                    <div class="card border-2 border-primary shadow-sm mb-4">
                        <div class="card-header bg-primary text-white">
                            <h4 class="card-title mb-0">
                                <i class="fas fa-receipt me-2"></i>Order Summary
                            </h4>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center border-bottom pb-2">
                                        <span class="text-muted">Plan Selected:</span>
                                        <span class="fw-bold">{{ $this->selectedPrice->name }}</span>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center border-bottom pb-2">
                                        <span class="text-muted">Amount:</span>
                                        <span class="fw-bold text-primary">{{ \Illuminate\Support\Number::currency($this->selectedPrice->amount) }}</span>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center border-bottom pb-2">
                                        <span class="text-muted">Name:</span>
                                        <span class="fw-bold">{{ $firstName ?? null }} {{ $lastName ?? null }}</span>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="text-muted">Email:</span>
                                        <span class="fw-bold text-break">{{ $email }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endif
                @if($currentStep == $totalSteps)
                    <div x-data="{
                        isProcessing: false,
                        paymentCompleted: false,
                    }" x-init="
                        paypal.Buttons({
                            createOrder: (data, actions) => {
                                return actions.order.create({
                                    purchase_units: [{
                                        amount: {
                                            value: '{{ $this->amount }}',
                                            currency_code: 'USD'
                                        },
                                        description: '{{ $this->selectedPrice->name }}'
                                    }],
                                    payer: {
                                        name: {
                                            given_name: '{{ $firstName }}',
                                            surname: '{{ $lastName }}'
                                        },
                                        email_address: '{{ $email }}'
                                    },
                                    application_context: {
                                        shipping_preference: 'NO_SHIPPING'
                                    }
                                });
                            },
                            onApprove: (data, actions) => {
                                isProcessing = true;

                                return actions.order.capture().then((details) => {
                                    isProcessing = false;
                                    paymentCompleted = true;

                                    Livewire.dispatch('capture-paypal-payment', {data: details});
                                }).catch(err => {
                                    console.error('Payment failed:', err);
                                    isProcessing = false;
                                    alert('Payment failed. Please try again.');
                                });
                            },
                            onError: (err) => {
                                console.error('PayPal Error:', err);
                                alert('An error occurred with PayPal. Please try another payment method.');
                            }
                        }).render('#paypal-button-container')
                    ">
                        <div x-show="!isProcessing && !paymentCompleted" class="text-center">
                            <div id="paypal-button-container" class="mb-3"></div>
                        </div>
                    </div>
                @endif

                @if($currentStep < $totalSteps)
                    <div class="mt-3">
                        <button wire:click="nextStep" class="btn btn-primary w-full">
                            Next
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M5 12l14 0"></path>
                                <path d="M13 18l6 -6"></path>
                                <path d="M13 6l6 6"></path>
                            </svg>
                        </button>
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script src="https://www.paypal.com/sdk/js?client-id={{ $clientId }}&currency=USD" async></script>
    <script>
        function paypalPayment() {
            return {
                isProcessing: false,
                paymentCompleted: false,

                init() {
                    if (typeof paypal === 'undefined') {
                        console.error('PayPal SDK failed to load');
                        return;
                    }

                    paypal.Buttons({
                        createOrder: (data, actions) => {
                            console.log('createOrder');

                            return actions.order.create({
                                purchase_units: [{
                                    amount: {
                                        value: '{{ $this->amount }}',
                                        currency_code: 'USD'
                                    },
                                    description: '{{ $this->selectedPrice->name }}'
                                }]
                            });
                        },
                        onApprove: (data, actions) => {
                            console.log('onApprove');
                            this.isProcessing = true;

                            return actions.order.capture().then((details) => {
                                this.isProcessing = false;
                                this.paymentCompleted = true;

                                // Kirim data pembayaran ke Livewire
                                Livewire.dispatch('capture-paypal-payment', {data: details});
                            }).catch(err => {
                                console.error('Payment failed:', err);
                                this.isProcessing = false;
                                alert('Payment failed. Please try again.');
                            });
                        },
                        onError: (err) => {
                            console.error('PayPal Error:', err);
                            alert('An error occurred with PayPal. Please try another payment method.');
                        }
                    }).render('#paypal-button-container');
                }
            };
        }
    </script>
@endpush
