

<?php $__env->startSection('title', 'Checkout - ' . $package->name); ?>

<?php $__env->startSection('content'); ?>
<div class="store-container">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 offset-lg-2">
                <div class="store-checkout">
                    <div class="store-checkout-header">
                        <h2>Checkout</h2>
                    </div>
                    
                    <div class="store-checkout-summary">
                        <div class="package-name"><?php echo e($package->name); ?></div>
                        
                        <?php if(isset($couponData)): ?>
                        <div class="package-price">
                            <span class="original-price"><?php echo e(currency_symbol(config_value('store_currency', 'GBP'))); ?><?php echo e(number_format($couponData['original_price'], 2)); ?></span>
                            <span class="final-price"><?php echo e(currency_symbol(config_value('store_currency', 'GBP'))); ?><?php echo e(number_format($couponData['final_price'], 2)); ?></span>
                        </div>
                        <div class="package-discount">
                            <span class="coupon-badge">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-tag" viewBox="0 0 16 16">
                                    <path d="M6 4.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm-1 0a.5.5 0 1 0-1 0 .5.5 0 0 0 1 0z"/>
                                    <path d="M2 1h4.586a1 1 0 0 1 .707.293l7 7a1 1 0 0 1 0 1.414l-4.586 4.586a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 1 6.586V2a1 1 0 0 1 1-1zm0 5.586 7 7L13.586 9l-7-7H2v4.586z"/>
                                </svg>
                                <?php echo e($couponData['code']); ?>

                            </span>
                            <span class="discount-amount">-<?php echo e(currency_symbol(config_value('store_currency', 'GBP'))); ?><?php echo e(number_format($couponData['discount_amount'], 2)); ?></span>
                            <button class="btn-remove-coupon" id="removeCoupon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-circle" viewBox="0 0 16 16">
                                    <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                    <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
                                </svg>
                            </button>
                        </div>
                        <?php else: ?>
                        <div class="package-price"><?php echo e(currency_symbol(config_value('store_currency', 'GBP'))); ?><?php echo e(number_format($package->price, 2)); ?></div>
                        <div class="coupon-form">
                            <div class="coupon-input-group">
                                <input type="text" id="couponCode" placeholder="Have a coupon code?" class="coupon-input">
                                <button type="button" id="applyCoupon" class="btn-apply-coupon">Apply</button>
                            </div>
                            <div class="coupon-message" id="couponMessage"></div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="package-description"><?php echo e($package->description); ?></div>
                    </div>
                    
                    <div class="store-checkout-features">
                        <h3>What's Included</h3>
                        <ul>
                            <?php $__currentLoopData = $package->features; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $feature): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <li><span class="check-icon">✓</span><?php echo e($feature); ?></li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </ul>
                    </div>
                    
                    <div class="store-checkout-user">
                        <h3>Account Details</h3>
                        <div class="user-info">
                            <p><strong>Username:</strong> <?php echo e(Auth::user()->name); ?></p>
                            <p><strong>SteamID64:</strong> <?php echo e(Auth::user()->steamid); ?></p>
                        </div>
                    </div>

                    <?php
                        $enabledMethods = array_filter($paymentMethods);
                        $hasMultipleMethods = count($enabledMethods) > 1;
                        $defaultMethod = $paymentMethods['stripe'] ? 'stripe' : 'paypal';
                        $finalAmount = isset($couponData) ? $couponData['final_price'] : $package->price;
                    ?>

                    <?php if($hasMultipleMethods): ?>
                    <div class="store-checkout-payment">
                        <h3>Choose Payment Method</h3>
                        <div class="payment-methods">
                            <?php if($paymentMethods['stripe']): ?>
                            <div class="payment-method-card" data-method="stripe">
                                <input type="radio" id="stripe" name="payment_method" value="stripe" <?php echo e($defaultMethod === 'stripe' ? 'checked' : ''); ?>>
                                <label for="stripe" class="payment-method-label">
                                    <div class="payment-method-content">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="currentColor" class="payment-icon" viewBox="0 0 16 16">
                                            <path d="M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm2 3.5A1.5 1.5 0 0 1 5.5 2h5A1.5 1.5 0 0 1 12 3.5v1A1.5 1.5 0 0 1 10.5 6h-5A1.5 1.5 0 0 1 4 4.5v-1zM5.5 3a.5.5 0 0 0-.5.5v1a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-1a.5.5 0 0 0-.5-.5h-5zM4 7.5A1.5 1.5 0 0 1 5.5 6h5A1.5 1.5 0 0 1 12 7.5v1A1.5 1.5 0 0 1 10.5 10h-5A1.5 1.5 0 0 1 4 8.5v-1zM5.5 7a.5.5 0 0 0-.5.5v1a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-1a.5.5 0 0 0-.5-.5h-5z"/>
                                        </svg>
                                        <div class="payment-method-info">
                                            <h4>Credit/Debit Card</h4>
                                            <p>Secure payment with Stripe</p>
                                        </div>
                                    </div>
                                </label>
                            </div>
                            <?php endif; ?>
                            
                            <?php if($paymentMethods['paypal']): ?>
                            <div class="payment-method-card" data-method="paypal">
                                <input type="radio" id="paypal" name="payment_method" value="paypal" <?php echo e($defaultMethod === 'paypal' ? 'checked' : ''); ?>>
                                <label for="paypal" class="payment-method-label">
                                    <div class="payment-method-content">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="currentColor" class="payment-icon" viewBox="0 0 16 16">
                                            <path d="M14.06 3.713c.12-1.071-.093-1.832-.702-2.526C12.628.356 11.312 0 9.626 0H4.734a.7.7 0 0 0-.691.59L2.005 13.509a.42.42 0 0 0 .415.486h2.756l-.202 1.28a.628.628 0 0 0 .62.726H8.14c.429 0 .793-.31.862-.731l.025-.13.48-3.043.016-.102.106-.1c.121-.124.328-.196.517-.196h.75c2.1 0 3.76-.48 4.244-1.871.164-.474.26-.94.28-1.372.12-1.244-.254-2.103-1.01-2.763-.32-.284-.71-.45-1.128-.571z"/>
                                        </svg>
                                        <div class="payment-method-info">
                                            <h4>PayPal</h4>
                                            <p>Pay with your PayPal account</p>
                                        </div>
                                    </div>
                                </label>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Terms of Service Acceptance -->
                    <div class="store-checkout-terms">
                        <div class="terms-acceptance">
                            <div class="terms-checkbox-container">
                                <input type="checkbox" id="acceptTerms" name="accept_terms" required disabled>
                                <label for="acceptTerms">I have read and agree to the <a href="<?php echo e(route('store.tos')); ?>" id="tosLink" target="_blank">Terms of Service</a></label>
                            </div>
                            <div class="terms-error" id="termsError"></div>
                        </div>
                    </div>
                    
                    <div class="store-checkout-actions">
                        <!-- Stripe Payment Form -->
                        <?php if($paymentMethods['stripe']): ?>
                        <form action="<?php echo e(route('payment.process', $package->slug)); ?>" method="POST" id="stripeForm" style="display: <?php echo e($defaultMethod === 'stripe' ? 'block' : 'none'); ?>;">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="payment_method" value="stripe">
                            <button type="submit" class="btn btn-primary" id="stripeBtn">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-credit-card" viewBox="0 0 16 16">
                                    <path d="M0 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V4zm2-1a1 1 0 0 0-1 1v1h14V4a1 1 0 0 0-1-1H2zM1 7v5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V7H1z"/>
                                </svg>
                                Pay with Card
                            </button>
                        </form>
                        <?php endif; ?>
                        
                        <!-- PayPal Payment -->
                        <?php if($paymentMethods['paypal']): ?>
                        <div id="paypalContainer" style="display: <?php echo e($defaultMethod === 'paypal' ? 'block' : 'none'); ?>;">
                            <form action="<?php echo e(route('payment.process', $package->slug)); ?>" method="POST" id="paypalForm" style="display: none;">
                                <?php echo csrf_field(); ?>
                                <input type="hidden" name="payment_method" value="paypal">
                            </form>
                            <div id="paypal-button-container"></div>
                        </div>
                        <?php endif; ?>
                        
                        <a href="<?php echo e(route('store.show', $package->slug)); ?>" class="btn btn-cancel">Cancel</a>
                    </div>
                    
                    <div class="store-checkout-notice">
                        <p id="paymentNotice">
                            <?php if($defaultMethod === 'stripe'): ?>
                                By clicking "Pay with Card", you will be redirected to Stripe to complete your purchase securely.
                            <?php else: ?>
                                Click the PayPal button above to complete your purchase securely through PayPal.
                            <?php endif; ?>
                        </p>
                        <p>Your purchase will be immediately processed after payment confirmation.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<?php if($paymentMethods['paypal']): ?>
<!-- PayPal SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=<?php echo e(config_value('store_paypal_client_id')); ?>&currency=<?php echo e(config_value('store_currency', 'GBP')); ?><?php echo e(config_value('store_sandbox', true) ? '&debug=true' : ''); ?>"></script>
<?php endif; ?>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        let tosViewed = false;
        const acceptTerms = document.getElementById('acceptTerms');
        const termsError = document.getElementById('termsError');
        
        <?php if($hasMultipleMethods): ?>
        // Payment method selection
        const paymentMethods = document.querySelectorAll('input[name="payment_method"]');
        const stripeForm = document.getElementById('stripeForm');
        const paypalContainer = document.getElementById('paypalContainer');
        const paymentNotice = document.getElementById('paymentNotice');
        
        // Update UI based on selected payment method
        function updatePaymentMethod(method) {
            if (method === 'stripe') {
                if (stripeForm) stripeForm.style.display = 'block';
                if (paypalContainer) paypalContainer.style.display = 'none';
                paymentNotice.textContent = 'By clicking "Pay with Card", you will be redirected to Stripe to complete your purchase securely.';
            } else if (method === 'paypal') {
                if (stripeForm) stripeForm.style.display = 'none';
                if (paypalContainer) paypalContainer.style.display = 'block';
                paymentNotice.textContent = 'Click the PayPal button above to complete your purchase securely through PayPal.';
            }
        }
        
        // Listen for payment method changes
        paymentMethods.forEach(radio => {
            radio.addEventListener('change', function() {
                updatePaymentMethod(this.value);
                
                // Update visual selection
                document.querySelectorAll('.payment-method-card').forEach(card => {
                    card.classList.remove('selected');
                });
                this.closest('.payment-method-card').classList.add('selected');
                
                <?php if($paymentMethods['paypal']): ?>
                // Try to load PayPal if this method is selected
                loadPayPalIfReady();
                <?php endif; ?>
            });
        });
        
        // Click on card to select payment method
        document.querySelectorAll('.payment-method-card').forEach(card => {
            card.addEventListener('click', function() {
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
                radio.dispatchEvent(new Event('change'));
            });
        });
        
        // Initialize with default selection
        const defaultMethod = document.querySelector('input[name="payment_method"]:checked');
        if (defaultMethod) {
            updatePaymentMethod(defaultMethod.value);
            defaultMethod.closest('.payment-method-card').classList.add('selected');
        }
        <?php endif; ?>
        
        <?php if($paymentMethods['paypal']): ?>
        // PayPal button initialization
        let paypalInitialized = false;
        
        function initPayPal() {
            if (!window.paypal || paypalInitialized) return;
            
            paypal.Buttons({
                style: {
                    color: 'blue',
                    shape: 'rect',
                    label: 'paypal',
                    height: 50
                },
                createOrder: function(data, actions) {
                    // Call our API to create the PayPal order
                    return fetch('/paypal/create-order', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            package_slug: '<?php echo e($package->slug); ?>',
                            <?php if($server): ?>
                            server_id: <?php echo e($server->id); ?>

                            <?php endif; ?>
                        })
                    })
                    .then(function(response) {
                        if (!response.ok) {
                            return response.json().then(err => Promise.reject(err));
                        }
                        return response.json();
                    })
                    .then(function(orderData) {
                        console.log('PayPal order created:', orderData);
                        return orderData.id;
                    })
                    .catch(function(error) {
                        console.error('PayPal order creation error:', error);
                        alert(error.message || error.error || 'Failed to create PayPal order. Please try again.');
                        return Promise.reject(error);
                    });
                },
                onApprove: function(data, actions) {
                    window.location.href = '<?php echo e(route('paypal.success', ':id')); ?>'.replace(':id', data.orderID) + '?token=' + data.orderID;
                },
                onError: function(err) {
                    console.error('PayPal SDK error:', err);
                    alert('An error occurred with PayPal. Please try again.');
                },
                onCancel: function(data) {
                    console.log('PayPal payment cancelled by user');
                }
            }).render('#paypal-button-container');
            
            paypalInitialized = true;
        }
        
        // Function to conditionally load PayPal
        function loadPayPalIfReady() {
            // Only load if PayPal is selected, TOS viewed, and TOS accepted
            const paypalSelected = <?php if($hasMultipleMethods): ?> document.querySelector('input[name="payment_method"]:checked')?.value === 'paypal' <?php else: ?> true <?php endif; ?>;
            
            if (paypalSelected && tosViewed && acceptTerms.checked && window.paypal && !paypalInitialized) {
                initPayPal();
            }
        }
        <?php endif; ?>
        
        // Apply coupon button
        const applyCouponBtn = document.getElementById('applyCoupon');
        if (applyCouponBtn) {
            applyCouponBtn.addEventListener('click', function() {
                const couponCode = document.getElementById('couponCode').value.trim();
                if (!couponCode) {
                    showCouponMessage('Please enter a coupon code.', 'error');
                    return;
                }
                
                // AJAX request to apply coupon
                fetch('<?php echo e(route('coupon.apply')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    },
                    body: JSON.stringify({
                        coupon_code: couponCode,
                        package_slug: '<?php echo e($package->slug); ?>'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Refresh the page to show applied coupon
                        window.location.reload();
                    } else {
                        showCouponMessage(data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showCouponMessage('An error occurred. Please try again.', 'error');
                });
            });
        }
        
        // Remove coupon button
        const removeCouponBtn = document.getElementById('removeCoupon');
        if (removeCouponBtn) {
            removeCouponBtn.addEventListener('click', function() {
                // AJAX request to remove coupon
                fetch('<?php echo e(route('coupon.remove')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Refresh the page to show removed coupon
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        }
        
        // Show coupon message
        function showCouponMessage(message, type) {
            const messageElement = document.getElementById('couponMessage');
            if (messageElement) {
                messageElement.textContent = message;
                messageElement.className = 'coupon-message';
                messageElement.classList.add(type);
                messageElement.style.display = 'block';
            }
        }
        
        // Terms of Service handling
        const tosLink = document.getElementById('tosLink');
        
        // Open TOS in new window and mark as viewed
        tosLink.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Open TOS in a new window
            const tosWindow = window.open(this.href, 'termsOfService', 'width=800,height=600,resizable=yes,scrollbars=yes');
            
            // Focus on the new window
            if (tosWindow) {
                tosWindow.focus();
            }
        });
        
        // Listen for message from TOS page
        window.addEventListener('message', function(event) {
            // Verify the message is from our TOS page
            if (event.data && event.data.type === 'tosRead' && event.data.status === true) {
                tosViewed = true;
                acceptTerms.disabled = false;
                
                // Show a confirmation message
                const confirmationMsg = document.createElement('div');
                confirmationMsg.className = 'terms-confirmation';
                confirmationMsg.innerHTML = `
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle" viewBox="0 0 16 16">
                        <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                        <path d="M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z"/>
                    </svg>
                    Terms of Service have been read
                `;
                
                // Insert confirmation message after the checkbox container
                const checkboxContainer = acceptTerms.closest('.terms-checkbox-container');
                if (checkboxContainer && !document.querySelector('.terms-confirmation')) {
                    checkboxContainer.parentNode.insertBefore(confirmationMsg, checkboxContainer.nextSibling);
                }
                
                <?php if($paymentMethods['paypal']): ?>
                // Try to load PayPal now that TOS has been viewed
                loadPayPalIfReady();
                <?php endif; ?>
            }
        });
        
        // Validate Stripe form submission
        const stripeForm = document.getElementById('stripeForm');
        if (stripeForm) {
            stripeForm.addEventListener('submit', function(e) {
                // Check if terms are accepted
                if (!acceptTerms.checked) {
                    e.preventDefault();
                    termsError.textContent = 'You must accept the Terms of Service to continue.';
                    termsError.style.display = 'block';
                    return false;
                }
                
                // Check if terms were viewed
                if (!tosViewed) {
                    e.preventDefault();
                    termsError.textContent = 'You must read the Terms of Service before accepting.';
                    termsError.style.display = 'block';
                    return false;
                }
                
                // Clear any errors if all is good
                termsError.textContent = '';
                termsError.style.display = 'none';
                return true;
            });
        }
        
        // Clear error when checkbox is checked
        acceptTerms.addEventListener('change', function() {
            if (this.checked) {
                termsError.textContent = '';
                termsError.style.display = 'none';
                
                <?php if($paymentMethods['paypal']): ?>
                // Try to load PayPal now that terms are accepted
                loadPayPalIfReady();
                <?php endif; ?>
            }
        });
    });
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/siedestudios.co.uk/edge/resources/views/store/checkout.blade.php ENDPATH**/ ?>