<!doctype html>
<html lang="en" class="color-sidebar sidebarcolor3">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="{{ asset('images/logo.png') }}" type="image/png" />
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!--plugins-->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js"></script>

    <link rel="stylesheet" href="{{ asset('assets/vendor/fonts/boxicons.css') }}" />
    <link rel="stylesheet" href="{{ asset('assets/vendor/fonts/fontawesome.css') }}" />
    <link rel="stylesheet" href="{{ asset('assets/vendor/fonts/flag-icons.css') }}" />

    <!-- Core CSS -->
    <link rel="stylesheet" href="{{ asset('assets/vendor/css/rtl/core.css') }}"
        class="template-customizer-core-css" />
    <link rel="stylesheet" href="{{ asset('assets/vendor/css/rtl/theme-default.css') }}"
        class="template-customizer-theme-css" />
    <link rel="stylesheet" href="{{ asset('assets/css/demo.css') }}" />

    <!-- Vendors CSS -->
    <link rel="stylesheet"
        href="{{ asset('assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css') }}" />
    <link rel="stylesheet"
        href="{{ asset('assets/vendor/libs/typeahead-js/typeahead.css') }}" />
    <link rel="stylesheet"
        href="{{ asset('assets/vendor/libs/apex-charts/apex-charts.css') }}" />
    <!-- Stripe Payment Sheet CSS -->
    <style>
        #payment-sheet-button {
            background: linear-gradient(135deg, #70c042 0%, #b6f45f 100%);
            border: none;
            color: white;
            padding: 12px 24px;
            font-size: 1rem;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
            margin-top: 20px;
        }

        #payment-element-container {
            margin: 20px 0;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        #payment-message {
            color: #d32f2f;
            font-size: 14px;
            margin-top: 15px;
            display: none;
        }

        .user-dropdown-container {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 1000;
        }

        .package-card {
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.2s ease;
            border-radius: 8px;
        }

        .package-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .package-card.selected {
            border-color: #70c042;
            box-shadow: 0 0 0 3px rgba(78, 115, 223, 0.2);
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, .3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            margin-right: 8px;
            vertical-align: middle;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        #payment-processing {
            display: none;
            align-items: center;
            justify-content: center;
        }
    </style>

    <title>Choose Your Subscription Plan | ROUTE MY PLAN</title>
    <!-- Stripe JS -->
</head>

<body>
    <div class="wrapper">
        <div class="container">
            <div class="row justify-content-center" style="scale: 0.9;">
                <div class="col-lg-10">
                    <div class=" shadow-sm">
                        <!-- Card Header with User Dropdown -->
                        <div class="card-header py-3 position-relative"
                            style="background-color: #f8f9fa; border-bottom: 1px solid #e1e5eb;">
                            <div class="d-flex justify-content-between align-items-center w-100 position-relative">


                                <!-- Center Title -->
                                <div class="position-absolute start-50 translate-middle-x text-center">
                                    <h2 class="mb-0" style="font-size: 1.5rem; font-weight: 600;">Select Your Plan</h2>
                                    <p class="text-muted mb-0" style="font-size: 0.85rem;">Choose the package that fits
                                        your needs</p>
                                </div>

                                <!-- User Dropdown -->
                                <div class="d-flex justify-content-end align-items-center px-3">
                                    <div class="user-box dropdown">
                                        <a class="d-flex align-items-center nav-link dropdown-toggle gap-2" href="#"
                                            role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                            <img src="{{ auth()->user()->picture }}"
                                                class="user-img rounded-circle p-1 bg-warning" alt="user avatar"
                                                style="width: 36px; height: 36px; object-fit: cover;">

                                            <div class="user-info d-none d-sm-block ms-2">
                                                <p class="user-name mb-0 fw-medium"
                                                    style="font-size: 0.9rem; line-height: 1.2;">
                                                    {{ auth()->user()->full_name }}
                                                </p>
                                                <p class="designation mb-0 text-muted"
                                                    style="font-size: 0.75rem; line-height: 1.2;">
                                                    {{ ucfirst(auth()->user()->user_type) }}
                                                </p>
                                            </div>
                                        </a>
                                        <ul class="dropdown-menu dropdown-menu-start shadow"
                                            style="min-width: 220px; border: none; margin-top: 8px;">
                                            <li>
                                                <a class="dropdown-item d-flex align-items-center py-2 px-3 text-danger"
                                                    href="{{ route('logout') }}"
                                                    onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                                                    <i class="bx bx-log-out-circle me-2" style="font-size: 1.1rem;"></i>
                                                    <span style="font-size: 0.9rem;">Logout</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                @csrf
                            </form>
                        </div>

                        <div class="card-body p-3 p-lg-4">
                            <!-- Package Selection -->
                            <div class="mb-4">
                                <div class="row justify-content-center g-3">
                                    @foreach($packages as $package)
                                    <div class="col-12 col-sm-6 col-md-4 col-lg-3 d-flex">
                                        <div class="card package-card h-100 w-100 {{ $loop->first ? 'selected' : '' }}"
                                            onclick="selectPackage(this, {{ $package->id }}, {{ $package->price }})">
                                            <div class="card-header py-2 text-center"
                                                style="background: linear-gradient(135deg, #70c042 0%, #b6f45f 100%); color: white;">
                                                <h4 class="mb-0" style="font-size: 1.1rem; font-weight: 500;">
                                                    {{ $package->name }}
                                                </h4>
                                                <p class="mb-0" style="font-size: 0.75rem; opacity: 0.9;">
                                                    {{ $package->type == 'unlimited' ? 'Unlimited' : 'Up to ' . $package->number_of_employees }}
                                                    employees
                                                </p>
                                            </div>
                                            <div class="card-body text-center p-2">
                                                <div class="price-display my-2"
                                                    style="font-size: 1.8rem; font-weight: 700; color: #224abe;">
                                                    ${{ number_format($package->price, 2) }}</div>
                                                <p class="text-muted mb-2" style="font-size: 0.75rem;">
                                                    {{ $package->duration_in_months }}
                                                    month{{ $package->duration_in_months > 1 ? 's' : '' }} access
                                                </p>

                                                <div class="px-2 text-center">
                                                    <h6 class="mb-2" style="font-size: 0.85rem; font-weight: 500;">Features:</h6>
                                                    <ul class="feature-list list-unstyled" style="font-size: 0.75rem;">
                                                        @if($package->description)
                                                        @foreach(explode("\n", $package->description) as $feature)
                                                        <li class="py-1">
                                                            <i class="fas fa-check-circle text-success me-1" style="font-size: 0.7rem;"></i>
                                                            {{ trim($feature) }}
                                                        </li>
                                                        @endforeach
                                                        @endif
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                                <input type="hidden" name="package_id" id="selected_package"
                                    value="{{ $packages->first()->id }}">
                            </div>

                            <!-- Payment Section with Stripe Elements -->
                            <div class="payment-section mt-4 p-4"
                                style="background-color: #f8f9fa; border-radius: 8px;">
                                <h3 class="mb-3 text-center" style="font-size: 1.3rem; font-weight: 600;">Payment
                                    Details</h3>
                                <p class="text-muted mb-4 text-center" style="font-size: 0.9rem;">Complete your
                                    subscription with secure payment</p>

                                <!-- Stripe Payment Element will be inserted here -->
                                <div id="payment-element-container">
                                    <div id="payment-element">
                                        <!-- Stripe.js will inject the Payment Element here -->
                                    </div>
                                    <div id="payment-message" class="hidden"></div>
                                </div>

                                <div class="text-center">
                                    <button id="submit-payment" class="btn"
                                        style="background: linear-gradient(135deg, #70c042 0%, #b6f45f 100%);">
                                        <i class="fas fa-lock me-2"></i>
                                        Subscribe for $<span
                                            id="payment-amount">{{ number_format($packages->first()->price, 2) }}</span>
                                    </button>
                                </div>

                                <div id="payment-processing" class="mt-3 text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <span class="ms-2">Processing payment...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
    <!--plugins-->
    <script src="{{ asset('js/jquery.min.js') }}"></script>
    <script src="{{ asset('plugins/simplebar/js/simplebar.min.js') }}"></script>
    <script src="{{ asset('plugins/metismenu/js/metisMenu.min.js') }}"></script>
    <script src="{{ asset('plugins/notifications/js/lobibox.min.js') }}"></script>
    <script src="{{ asset('plugins/notifications/js/notifications.min.js') }}"></script>
    <script src="https://js.stripe.com/v3/"></script>


    <script>
        // Package Selection Functionality
        function selectPackage(cardElement, packageId, packagePrice) {
            // Check if payment is being processed
            if (document.getElementById('submit-payment').disabled) {
                return; // Don't allow package changes during payment processing
            }

            // Remove selected class from all cards
            document.querySelectorAll('.package-card').forEach(card => {
                card.classList.remove('selected');
            });

            // Add selected class to clicked card
            cardElement.classList.add('selected');

            // Update hidden input with selected package ID
            document.getElementById('selected_package').value = packageId;

            // Update payment button with selected package price
            document.getElementById('payment-amount').textContent = packagePrice.toFixed(2);

            // Reinitialize Stripe with the new package
            initializeStripe();
        }

        const stripe = Stripe("{{ env('STRIPE_KEY') }}");
        let elements, paymentElement, clientSecret;

        async function initializeStripe() {
            const packageId = document.getElementById('selected_package').value;

            // Remove any existing payment element
            if (paymentElement) {
                paymentElement.unmount();
            }

            // Show loading state
            document.getElementById('payment-processing').style.display = 'flex';
            document.getElementById('submit-payment').disabled = true;

            try {
                const response = await fetch('{{ route("stripe.create-setup-intent") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({
                        package_id: packageId
                    })
                });

                const result = await response.json();
                clientSecret = result.client_secret;

                elements = stripe.elements({
                    clientSecret
                });

                paymentElement = elements.create("payment");
                paymentElement.mount("#payment-element");
            } catch (error) {
                console.error('Error initializing Stripe:', error);
            } finally {
                // Hide loading state
                document.getElementById('payment-processing').style.display = 'none';
                document.getElementById('submit-payment').disabled = false;
            }
        }

        async function handleSubmit(event) {
            event.preventDefault();

            // Disable all package selections and payment button
            document.querySelectorAll('.package-card').forEach(card => {
                card.style.pointerEvents = 'none';
                card.style.opacity = '0.7';
            });
            document.getElementById('submit-payment').disabled = true;
            document.getElementById('payment-processing').style.display = 'flex';

            const packageId = document.getElementById('selected_package').value;

            try {
                // Submit elements before confirming
                await elements.submit();

                const {
                    error
                } = await stripe.confirmSetup({
                    elements,
                    clientSecret,
                    confirmParams: {
                        return_url: `{{ route('stripe.card.saved') }}?package_id=${packageId}`
                    }
                });

                if (error) {
                    console.error(error.message);
                    document.getElementById('payment-message').textContent = error.message;
                    document.getElementById('payment-message').style.display = 'block';

                    // Re-enable package selections if error occurs
                    document.querySelectorAll('.package-card').forEach(card => {
                        card.style.pointerEvents = 'auto';
                        card.style.opacity = '1';
                    });
                }
            } catch (err) {
                console.error(err);
                document.getElementById('payment-message').textContent = 'Something went wrong. Please try again.';
                document.getElementById('payment-message').style.display = 'block';

                // Re-enable package selections if error occurs
                document.querySelectorAll('.package-card').forEach(card => {
                    card.style.pointerEvents = 'auto';
                    card.style.opacity = '1';
                });
            } finally {
                document.getElementById('submit-payment').disabled = false;
                document.getElementById('payment-processing').style.display = 'none';
            }
        }

        document.addEventListener("DOMContentLoaded", async () => {
            await initializeStripe();
            document.getElementById("submit-payment").addEventListener("click", handleSubmit);
        });
    </script>




</body>

</html>