@extends('site.layouts.auth')
@section('content')
    <div class="flex h-[100%]">
        <div class="2xl:w-[47%] lg:w-1/2 w-full flex flex-col  justify-center  bg-[#FFFFFF] bg-no-repeat"
            style="background-image: url('{{ asset('site/Sites/images/map.png') }}');">
            <div class="flex 2xl:ml-40  sm:ml-20 ml-8 mt-10  gap-2 mb-8 cursor-pointer"
                onclick="window.location.href='{{ url('/') }}'">
                <img src="{{ asset('site/Sites/images/logo-login.png') }}" />
            </div>
            <form action="{{ route('create.account') }}" method="post" id="registration_form">
                @csrf
                <input type="hidden" value="{{$plans->id}}" name="plan_id" id="hidden_plan_id">
                <div
                    class="2xl:w-[648px]  xl:w-[550px] desk:w-[600px] lg:w-[500px] sm:w-[90%] w-[95%] 2xl:ml-40 sm:ml-10 mb-20 h-full flex flex-col justify-center sm:mx-0 mx-auto">

                    <h2 class="md:text-[44px] text-[30px] font-medium mb-10 text-[#111827] syne-medium leading-none">Sign Up
                        to Get Started</h2>
                    <label class="text-[19px] fo-m text-[#111827]">Select Role:</label>
                    <div class="flex gap-6 mb-4 px-3 py-4  border-l ">
                        <label class="flex items-center gap-2 text-[16px] syne-medium text-[#111827]">

                            <input type="radio" name="role" value="student" class="strong-aggree" checked />
                            Student
                        </label>
                        <label class="flex items-center gap-2 text-[16px] syne-medium text-[#111827]">



                            <input type="radio" name="role" value="tutor" class="strong-aggree " />

                            Tutor
                        </label>
                        <br>

                    </div>
                    @error('role')
                        <span class="text-error">{{ $message }}</span>
                    @enderror
                    <label class="text-[19px] fo-m text-[#111827]">First Name*</label>
                    <input type="text" placeholder="Enter your First Name" value="{{ old('first_name') }}"
                        name="first_name"
                        class="w-full mt-1 mb-4 px-3 py-4 syne border-l font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('first_name')
                        <span class="text-error">{{ $message }}</span>
                    @enderror

                    <label class="text-[19px] fo-m text-[#111827]">Last Name*</label>
                    <input type="text" placeholder="Enter your Last Name" value="{{ old('last_name') }}" name="last_name"
                        class="w-full mt-1 mb-4 px-3 py-4 syne border-l font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('last_name')
                        <span class="text-error">{{ $message }}</span>
                    @enderror


                    <label class="text-[19px] fo-m text-[#111827]">Username*</label>
                    <input type="text" placeholder="Enter your Last Name" value="{{ old('username') }}" name="username"
                        class="w-full mt-1 mb-4 px-3 py-4 syne border-l font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('username')
                        <span class="text-error">{{ $message }}</span>
                    @enderror

                    <label class="text-[19px] fo-m text-[#111827]">Email*</label>
                    <input type="text" placeholder="Enter your Email" value="{{ old('email') }}" name="email"
                        class="w-full mt-1 mb-4 px-3 py-4 syne border-l font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('email')
                        <span class="text-error">{{ $message }}</span>
                    @enderror



                    <label class="text-[19px] fo-m text-[#111827]">Password*</label>
                    <input type="password" placeholder="Enter your Password" name="password"
                        class="w-full mt-1 mb-4 px-3 py-4 border-l syne font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('password')
                        <span class="text-error">{{ $message }}</span>
                    @enderror


                    <label class="text-[19px] fo-m text-[#111827]">Confirm Password*</label>
                    <input type="password" placeholder="Enter your Password" value="" name="password_confirmation"
                        class="w-full mt-1 mb-4 px-3 py-4 border-l syne font-medium text-[17px]  outline-none  text-[#111827]" />
                    @error('password_confirmation')
                        <span class="text-error">{{ $message }}</span>
                    @enderror



                    <button type="button" id="signupBtn"
                        class="w-full cursor-pointer text-[19px] bg-[#F4C701] text-[#000000] syne py-4 mt-10 rounded font-medium">
                        Sign up →
                    </button>


                    <div class="flex justify-between">

                        <p class="text-[17px] text-center font-medium syne text-[#9CA3AF] mt-4">
                            Already have an account?
                            <a href="{{ url('login') }}" class="text-[#111827] font-medium underline ">Login</a>
                        </p>
                    </div>

                </div>
            </form>
        </div>

        <div class="w-[53%]  lg:flex hidden items-center justify-center relative m-5 rounded-md bg-cover"
            style="background-image: url('{{ asset('site/Sites/images/auth-bg.png') }}');">


            <div class="relative text-center">
                <div class="flex justify-center mb-3">
                    <img src="{{ asset('site/Sites/images/login-logo.png') }}" class="desk:w-full w-60" />
                </div>

            </div>


            <a href="{{ url('login') }}" class="absolute syne font-normal top-10 right-[15%] text-white text-[18px]">
                Login >
            </a>

        </div>

    </div>



    <el-dialog>
        <dialog id="signuppop" aria-labelledby="dialog-title"
            class="fixed  modalShadow inset-0 size-auto max-h-none max-w-none overflow-y-auto bg-transparent backdrop:bg-transparent">
            <el-dialog-backdrop
                class="fixed inset-0 bg-gray-900/80 opacity-50 transition-opacity data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in"></el-dialog-backdrop>

            <div tabindex="0"
                class="m-auto  flex min-h-full items-end justify-center p-4 text-center focus:outline-none sm:items-center sm:p-0">
                <el-dialog-panel
                    class="m-auto relative transform overflow-hidden rounded-sm bg-gray-800 text-left shadow-xl outline -outline-offset-1 outline-white/10 transition-all data-closed:translate-y-4 data-closed:opacity-0 data-enter:duration-300 data-enter:ease-out data-leave:duration-200 data-leave:ease-in sm:my-8 sm:w-[585px]   data-closed:sm:translate-y-0 data-closed:sm:scale-95">
                    <div class="form bg-[#FFFFFF] px-4 pt-5 pb-4 sm:p-8 sm:pb-4">
                        <div class="flex justify-between sm:items-start">
                            <div>

                                <h1 class="text-[#181D27] fo-m sm:text-[23px] text-lg">Subscription</h1>
                            </div>
                            <button command="close" commandfor="signuppop" class="cursor-pointer">

                                <img src="{{ asset('site/Sites/images/cros-icon.png') }}" />
                            </button>
                        </div>
                        <div class="mt-3">
                            <h2 class="text-[16px] font-medium mb-2 text-[#414651] fo-m  mt-5">Membership pricing</h2>
                            <button 
                                class="bg-[#1CD8C4] px-3 cursor-pointer border-[#D5D7DA] border rounded-[10px] w-full py-2 text-start fo-n font-semibold text-[#FFFFFF] sm:text-[22px] text-[15px]">
                                ${{$plans->discounted_price}}/{{ucFirst(strtolower($plans->interval))}}
                            </button>

                            
                        </div>


                        <div class="mt-3">
                            <h2 class="text-[16px] font-medium mb-2 text-[#414651] fo-m  mt-5">Total Price</h2>
                            <button id="price"
                                class="bg-[#1CD8C4] px-3 cursor-pointer border-[#D5D7DA] border rounded-[10px] w-full py-2 text-start fo-n font-semibold text-[#FFFFFF] sm:text-[22px] text-[15px]">
                                ${{$plans->plan_price}}
                            </button>

                            <div class="mt-3">
                                <div id="paypal-button-container"></div>
                            </div>
                        </div>


                    </div>

                </el-dialog-panel>
            </div>
        </dialog>
    </el-dialog>
    
    @push('scripts')
        <script src="https://www.paypal.com/sdk/js?client-id={{ config('paypal.sandbox.client_id') }}&vault=true&intent=subscription"></script>

        <script>
          const form = document.getElementById('registration_form');

// const planSelect = document.getElementById('plan_id');
// const priceBtn = document.getElementById('price');
// const hiddenPlan = document.getElementById('hidden_plan_id');

// planSelect.addEventListener('change', function() {
//     const selectedOption = this.options[this.selectedIndex];
//     const price = selectedOption.dataset.price || 0; // default $0 if no plan selected
//     priceBtn.textContent = `$${price}`;
//     hiddenPlan.value = this.value; // keep the selected plan in hidden input
// });



paypal.Buttons({

    async createSubscription() {

        const planId = document.getElementById('hidden_plan_id').value;

        if (!planId) {
            toastr.error('Please select a subscription plan.');
            return;
        }

        // Validate form first
        const isValid = await validateTutorForm();
        if (!isValid) return;

        return fetch("{{ route('paypal.create-subscription') }}", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": "{{ csrf_token() }}"
            },
            body: JSON.stringify({ plan_id: planId })
        })
        .then(res => res.json())
        .then(data => {
            return data.subscription_id; // VERY IMPORTANT
        });
    },

    onApprove(data) {

        // data.subscriptionID (NOT orderID)

        const formData = Object.fromEntries(new FormData(form));

        return fetch("{{ route('paypal.subscription-success') }}", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": "{{ csrf_token() }}"
            },
            body: JSON.stringify({
                subscriptionID: data.subscriptionID,
                form: formData
            })
        })
        .then(res => res.json())
        .then(res => {

            if (res.redirect) {
                localStorage.setItem('toast_success', res.message);
                window.location.href = res.redirect;
            } else {
                toastr.error(res.error);
            }
        });
    },

    onError(err) {
        console.error(err);
        toastr.error('Subscription failed');
    }

}).render('#paypal-button-container');


 function validateTutorForm() {
    const formData = $('#registration_form').serialize();

    return new Promise((resolve) => {
        $.ajax({
            url: "{{ route('signup-validation') }}",
            method: "POST",
            data: formData,

            success: function (res) {
                resolve(true); // ✅ validation passed
            },

            error: function (xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors || xhr.responseJSON.message;

                    Object.values(errors).forEach(err => {
                        toastr.error(err[0]);
                    });
                }
                resolve(false); // ❌ validation failed
            }
        });
    });
}



document.getElementById('signupBtn').addEventListener('click', async function () {
    const role = document.querySelector('input[name="role"]:checked').value;
        
    if (role === 'student') {
        document.getElementById('registration_form').submit();
        return;
    }

    if (role === 'tutor') {
        const isValid = await validateTutorForm();

        if (!isValid) return; // ❌ modal nahi khulega

        document.getElementById('signuppop').showModal(); // ✅ only when valid
    }
});


</script>

    @endpush
@endsection
