<?php $__env->startSection('title', __('Confirmación de compra').' | '.config('app.name')); ?>

<?php $__env->startPush('head'); ?>
    <?php if(($order->status->value ?? null) === 'pending' && ($showPaypalCheckout ?? false)): ?>
        <script src="https://www.paypal.com/sdk/js?client-id=<?php echo e(urlencode(config('services.paypal.client_id'))); ?>&currency=<?php echo e(urlencode($order->currency ?? 'USD')); ?>"></script>
    <?php endif; ?>
    <?php if(($order->status->value ?? null) === 'pending' && ($showStripeCheckout ?? false)): ?>
        <script src="https://js.stripe.com/v3/"></script>
    <?php endif; ?>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="rt-page-under-fixed-nav rt-checkout-confirmation">
    <section class="py-4 py-lg-5">
        <div class="container" style="max-width: 1080px;">
            <?php
                $status = $order->status->value ?? 'pending';
                $isPending = $status === 'pending';
                $isPaid = $status === \App\Enums\OrderStatus::Completed->value;
            ?>

            <header class="mb-4 mb-lg-5">
                <p class="rt-cc-breadcrumb mb-1"><?php echo e(__('Confirmación de compra')); ?></p>
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                    <h1 class="rt-cc-page-title mb-0"><?php echo e(__('Tu orden')); ?></h1>
                    <span class="rt-cc-order-ref"><?php echo e(__('Orden')); ?> #<?php echo e(str_pad((string) $order->id, 6, '0', STR_PAD_LEFT)); ?></span>
                </div>
            </header>

            <div class="row g-4 g-lg-5 align-items-start">
                
                <div class="col-lg-7">
                    <div class="rt-cc-status-card <?php echo e($isPaid ? 'rt-cc-status-card--success' : 'rt-cc-status-card--pending'); ?> mb-4">
                        <div class="d-flex gap-3 align-items-start">
                            <div class="rt-cc-status-icon <?php echo e($isPaid ? 'rt-cc-status-icon--ok' : 'rt-cc-status-icon--pay'); ?>" aria-hidden="true">
                                <?php if($isPaid): ?>
                                    <i class="bi bi-check-lg fs-4"></i>
                                <?php else: ?>
                                    <i class="bi bi-credit-card-2-front fs-4"></i>
                                <?php endif; ?>
                            </div>
                            <div class="flex-grow-1 min-w-0">
                                <h2 class="h5 fw-bold mb-2" style="color: <?php echo e($isPaid ? '#14532d' : '#991b1b'); ?>;">
                                    <?php echo e($isPaid ? __('Compra confirmada') : __('Completa el pago')); ?>

                                </h2>
                                <p class="mb-0 rt-cc-event-meta">
                                    <?php if($isPaid): ?>
                                        <?php echo e(__('Tu pago se procesó correctamente. Hemos registrado tu orden y enviado la confirmación al correo indicado.')); ?>

                                    <?php else: ?>
                                        <?php echo e(__('Tu orden está lista. Falta el pago para emitir las entradas y enviarte la confirmación por correo.')); ?>

                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <?php if($isPaid): ?>
                        <div class="rt-cc-email-hint mb-4">
                            <div class="d-flex gap-2 align-items-start">
                                <i class="bi bi-envelope-paper fs-5 flex-shrink-0 mt-1" aria-hidden="true"></i>
                                <div>
                                    <strong class="d-block text-dark mb-1"><?php echo e(__('Revisa tu correo')); ?></strong>
                                    <?php echo e(__('Ahí encontrarás el detalle de la compra y los códigos QR para el acceso al evento. Si no lo ves, revisa spam o promociones.')); ?>

                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="rt-cc-event-card p-3 p-md-4 mb-4">
                        <div class="d-flex gap-3 align-items-center">
                            <?php if($event->featured_image_path): ?>
                                <img src="<?php echo e(asset($event->featured_image_path)); ?>" class="rt-cc-event-card-thumb flex-shrink-0" alt="<?php echo e($event->title); ?>">
                            <?php else: ?>
                                <div class="rt-cc-event-card-thumb flex-shrink-0 bg-light d-flex align-items-center justify-content-center border">
                                    <i class="bi bi-calendar-event text-muted fs-3"></i>
                                </div>
                            <?php endif; ?>
                            <div class="min-w-0">
                                <h3 class="h6 fw-bold text-dark mb-2 text-truncate"><?php echo e($event->title); ?></h3>
                                <div class="rt-cc-event-meta">
                                    <span class="me-3 d-inline-block">
                                        <i class="bi bi-calendar3 me-1" aria-hidden="true"></i>
                                        <?php echo e(\Carbon\Carbon::parse($event->start_date)->setTimezone($event->timezone ?? 'America/Puerto_Rico')->locale(app()->getLocale())->translatedFormat('l, j F Y · g:i A')); ?>

                                    </span>
                                    <?php if($event->venue): ?>
                                        <span class="d-block d-sm-inline mt-1 mt-sm-0">
                                            <i class="bi bi-geo-alt me-1" aria-hidden="true"></i><?php echo e($event->venue->name); ?>

                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if(auth()->guard()->guest()): ?>
                        <?php if($isPaid): ?>
                            <p class="small text-secondary mb-0" style="max-width: 36rem;">
                                <?php echo e(__('Compraste como invitado. Guarda el correo de confirmación como comprobante; allí están tus códigos de acceso.')); ?>

                            </p>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if($isPending): ?>
                        <div class="rt-cc-pay-panel">
                            <div class="d-flex align-items-center justify-content-between mb-3 pb-2 border-bottom">
                                <span class="rt-cc-pay-panel-title">
                                    <i class="bi bi-shield-lock text-success me-1" aria-hidden="true"></i><?php echo e(__('Pago seguro')); ?>

                                </span>
                                <span class="text-muted small"><?php echo e(__('Stripe · PayPal')); ?></span>
                            </div>

                            <div class="d-flex flex-column gap-3">
                                <?php if($showStripeCheckout ?? false): ?>
                                    <div class="p-3 rounded-3 border bg-white">
                                        <div id="rt-stripe-payment-element" class="mb-2"></div>
                                        <div class="small text-danger mb-2 text-center" id="rt-stripe-error" style="display:none;"></div>
                                        <button type="button" class="btn btn-primary w-100 fw-bold py-2 rounded-3" id="rt-stripe-pay-btn" disabled style="background-color:#b91830;border-color:#b91830;">
                                            <span id="rt-stripe-btn-text"><?php echo e(__('Pagar con tarjeta')); ?></span>
                                        </button>
                                    </div>
                                <?php endif; ?>

                                <?php if($showPaypalCheckout ?? false): ?>
                                    <div id="rt-paypal-buttons"></div>
                                    <div class="small text-danger text-center" id="rt-paypal-error" style="display:none;"></div>
                                <?php endif; ?>

                                <?php if(! ($showStripeCheckout ?? false) && ! ($showPaypalCheckout ?? false)): ?>
                                    <p class="small text-muted mb-0 text-center"><?php echo e(__('El pago en línea no está disponible para este evento. Contacta al organizador.')); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                
                <div class="col-lg-5">
                    <div class="rt-cc-receipt sticky-lg-top" style="top: 6.5rem;">
                        <div class="rt-cc-receipt-header">
                            <span class="rt-cc-receipt-label"><?php echo e(__('Resumen')); ?></span>
                        </div>
                        <div class="px-3 px-md-4 pt-2 pb-0">
                            <?php $__currentLoopData = $order->attendees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attendee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $base = (float) ($attendee->ticketType?->sale_price ?? $attendee->ticketType?->price);
                                    $ticketTotal = \App\Services\FeeCalculator::calculateTotalForAttendee($base);
                                ?>
                                <div class="rt-cc-line">
                                    <div class="d-flex justify-content-between align-items-start gap-2">
                                        <div class="min-w-0">
                                            <div class="fw-semibold text-dark small"><?php echo e($attendee->holder_name ?: __('Asistente')); ?></div>
                                            <div class="text-muted" style="font-size: 0.8rem;"><?php echo e($attendee->ticketType?->name); ?></div>
                                        </div>
                                        <div class="fw-semibold text-dark text-nowrap">$<?php echo e(number_format($ticketTotal, 2)); ?></div>
                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>

                        <div class="rt-cc-total-strip">
                            <div class="d-flex justify-content-between align-items-end gap-2">
                                <span class="fw-bold text-dark"><?php echo e($isPaid ? __('Total pagado') : __('Total a pagar')); ?></span>
                                <div class="text-end">
                                    <div class="rt-cc-total-amount">$<?php echo e(number_format((float) $order->total_amount, 2)); ?></div>
                                    <div class="text-muted" style="font-size: 0.75rem;"><?php echo e($order->currency); ?> · <?php echo e(__('IVA incluido')); ?></div>
                                </div>
                            </div>
                        </div>

                        <div class="rt-cc-actions d-flex flex-wrap align-items-center justify-content-between gap-2">
                            <a href="<?php echo e(route('landing.event.show', ['event' => $event->slug])); ?>" class="btn btn-link text-secondary text-decoration-none p-0 small fw-semibold">
                                <i class="bi bi-arrow-left me-1" aria-hidden="true"></i><?php echo e(__('Volver al evento')); ?>

                            </a>
                            <a href="<?php echo e(route('landing.events')); ?>" class="btn rt-cc-btn-primary btn-sm text-white">
                                <?php echo e(__('Más eventos')); ?>

                            </a>
                        </div>
                    </div>

                    <p class="text-center rt-cc-trust mt-3 mb-0">
                        <i class="bi bi-lock-fill text-success me-1" aria-hidden="true"></i>
                        <?php echo e(__('Pago protegido con cifrado. No almacenamos los datos completos de tu tarjeta.')); ?>

                    </p>
                </div>
            </div>
        </div>
    </section>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <?php if(($order->status->value ?? null) === 'pending'): ?>
        <script>
            (function () {
                const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

                async function postJson(url, body) {
                    const res = await fetch(url, {
                        method: 'POST',
                        credentials: 'same-origin',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': csrf || '',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: JSON.stringify(body || {}),
                    });
                    const data = await res.json().catch(() => ({}));
                    if (!res.ok) throw new Error(data?.message || 'Request failed');
                    return data;
                }

                const stripeKey = <?php echo \Illuminate\Support\Js::from(config('services.stripe.key'))->toHtml() ?>;
                if (window.Stripe && stripeKey) {
                    const stripe    = Stripe(stripeKey);
                    const intentUrl = <?php echo \Illuminate\Support\Js::from(route('landing.event.checkout.stripe.intent', ['event' => $event->slug, 'checkoutOrder' => $order]))->toHtml() ?>;
                    const payBtn    = document.getElementById('rt-stripe-pay-btn');
                    const btnText   = document.getElementById('rt-stripe-btn-text');
                    const errorEl   = document.getElementById('rt-stripe-error');

                    (async () => {
                        try {
                            const data     = await postJson(intentUrl, {});
                            const elements = stripe.elements({ clientSecret: data.client_secret });
                            const payEl    = elements.create('payment');
                            payEl.mount('#rt-stripe-payment-element');

                            payEl.on('ready', () => {
                                payBtn.disabled = false;
                                btnText.textContent = <?php echo \Illuminate\Support\Js::from(__('Pagar con tarjeta'))->toHtml() ?>;
                            });

                            payBtn.addEventListener('click', async () => {
                                payBtn.disabled  = true;
                                btnText.textContent = <?php echo \Illuminate\Support\Js::from(__('Procesando…'))->toHtml() ?>;
                                errorEl.style.display = 'none';

                                const result = await stripe.confirmPayment({
                                    elements,
                                    confirmParams: { return_url: window.location.href },
                                });

                                if (result.error) {
                                    errorEl.textContent   = result.error.message || <?php echo \Illuminate\Support\Js::from(__('Pago fallido'))->toHtml() ?>;
                                    errorEl.style.display = 'block';
                                    payBtn.disabled  = false;
                                    btnText.textContent = <?php echo \Illuminate\Support\Js::from(__('Pagar con tarjeta'))->toHtml() ?>;
                                }
                            });
                        } catch (e) {
                            errorEl.textContent   = e.message || <?php echo \Illuminate\Support\Js::from(__('No se pudo iniciar Stripe'))->toHtml() ?>;
                            errorEl.style.display = 'block';
                        }
                    })();
                }

                if (window.paypal) {
                    const createUrl  = <?php echo \Illuminate\Support\Js::from(route('landing.event.checkout.paypal.order',   ['event' => $event->slug, 'checkoutOrder' => $order]))->toHtml() ?>;
                    const captureUrl = <?php echo \Illuminate\Support\Js::from(route('landing.event.checkout.paypal.capture', ['event' => $event->slug, 'checkoutOrder' => $order]))->toHtml() ?>;

                    window.paypal.Buttons({
                        createOrder: async () => {
                            const data = await postJson(createUrl, {});
                            return data.paypal_order_id;
                        },
                        onApprove: async (data) => {
                            await postJson(captureUrl, { paypal_order_id: data.orderID });
                            window.location.reload();
                        },
                        onError: () => {
                            const el = document.getElementById('rt-paypal-error');
                            el.textContent   = <?php echo \Illuminate\Support\Js::from(__('Error al procesar PayPal. Inténtalo de nuevo.'))->toHtml() ?>;
                            el.style.display = 'block';
                        },
                    }).render('#rt-paypal-buttons');
                }
            })();
        </script>
    <?php endif; ?>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.landing', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/resources/views/landing/checkout-confirmation.blade.php ENDPATH**/ ?>