@extends('site.layouts.layout')

@section('title', 'Tutor Profile')

@section('content')

    <div id="paypal-loader" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white p-6 rounded-lg text-center">
            <div class="animate-spin rounded-full h-10 w-10 border-4 border-blue-500 border-t-transparent mx-auto mb-3">
            </div>
            <p class="text-sm font-medium">Processing Payment... Please wait</p>
        </div>
    </div>

    <style>
        .star {
            font-size: 32px;
            cursor: pointer;
            color: #D1D5DB;
            transition: color 0.2s;
        }

        .star.active {
            color: #FACC15;
        }
    </style>




    <section class="w-full sm:py-16 mb-10">
        <div class="max-w-[1700px] mx-auto sm:px-6 lg:px-10 grid grid-cols-1 lg:grid-cols-3 gap-8">

            <div class="lg:col-span-2 space-y-8">

                <div class="flex flex-wrap  gap-6">
                    <img src="{{ asset($tutor->profile ?? $tutor->tutorDefaultImage) }}"
                        class=" rounded-xl object-cover mx-auto w-[309px] h-[289px]" alt="Teacher">

                    <div class="flex-1 p-6">
                        <h2 class="text-[28px] font-semibold text-[#143453] fo-n">
                            {{ ucFirst($tutor->name) }}</h2>
                        <p class="text-[22px] text-[#171717] roboto font-normal ">{!! $tutor->qualification !!}</p>

                        <p class="text-[16px] text-[#1D1B20] poppins mt-3">
                            {!! $tutor->headline !!}
                        </p>
                        <p class="text-[#171717] roboto text-[20px] mt-3">Subjects:</p>
                        <div class="flex flex-wrap gap-2 mt-2">
                            @foreach ($tutor->subjects as $subject)
                                <span
                                    class="px-8 py-2 text-[18px] roboto bg-[#EFEFEF] text-[#171717] rounded-full">{{ $subject->subject_name }}</span>
                            @endforeach
                        </div>
                    </div>
                </div>


                <div class="border-[#E5E5E5] rounded-[10px] border  p-6">
                    <h2 class="text-[28px] font-semibold text-[#143453] fo-n">About The Teacher</h2>
                    <p class="text-[15px] text-[#171717] roboto ">
                        {!! $tutor->introduction !!}
                    </p>

                    <div class="border-t  mx-auto border-[#d1cdcd] mt-10"></div>
                    <h2 class="text-[22px]  text-[#143453] mt-3 fo-m">Languages</h2>
                    <div class="mt-4 flex flex-wrap gap-2 px-4">
                        @foreach ($tutor->tutorLanguages as $lang)
                            <span
                                class="px-8 py-2 text-[18px] roboto bg-[#EFEFEF] text-[#171717] rounded-full">{{ $lang->language->language_name }}</span>
                        @endforeach


                    </div>
                    <div class="border-t  mx-auto border-[#d1cdcd] mt-10"></div>
                    <h2 class="text-[22px]  text-[#143453] mt-3 fo-m">Level of Teaching</h2>
                    <div class="mt-4 flex flex-wrap gap-2 px-4">
                        @foreach ($tutor->teachingLevels as $level)
                            <span
                                class="px-8 py-2 text-[18px] roboto bg-[#EFEFEF] text-[#171717] rounded-full">{{ $level->level_name }}</span>
                        @endforeach


                    </div>

                </div>


                <div class=" border-[#E5E5E5] rounded-[10px] border  p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h2 class="text-[28px] font-semibold text-[#143453] fo-n">
                            Tutor Availability
                        </h2>
                    </div>
                    <div id="calenderData"></div>
                </div>

            </div>

            <div class="space-y-6 mb-25">

                <div class="     text-center"
                    style="background-image: url('{{ asset('site/Sites/images/tutor-profile-right-bg.png') }}');">
                    <button class="w-full cursor-pointer  text-[#121212] font-medium mt-4 text-[22px] rounded-xl poppins">
                        Book a Session
                    </button>

                    <div id="tutor_hourly_rate" data-price="{{ $tutor->tutor_hourly_rate }}"
                        class="text-[34px]  mt-4 bg-[#FFFFFF] text-[#1AD6C2] h-[60px]  flex items-center justify-center poppins font-medium">
                        $ {{ $tutor->tutor_hourly_rate }}/<sub class="text-[19px] font-normal"> hr</sub></div>
                    @if (auth()->check() && auth()->id() == $tutor->id)
                        <button type="button" disabled
                            class=" cursor-pointer  mt-4 mb-3 w-[90%] mx-auto bg-[#000000] text-[#1AD6C2] poppins font-medium text-[16px] py-5 rounded-[5px]">
                            Book Now
                        </button>
                    @elseif (auth()->check())
                        
                         <button command="show-modal" onclick="fetchModalSlots()" commandfor="dialog"
                            class=" cursor-pointer  mt-4 mb-3 w-[90%] mx-auto bg-[#000000] text-[#1AD6C2] poppins font-medium text-[16px] py-5 rounded-[5px]">
                            Book Now
                        </button>
                    @else
                        <button onclick="window.location.href='{{ url('login') }}'"
                            class=" cursor-pointer  mt-4 mb-3 w-[90%] mx-auto bg-[#000000] text-[#1AD6C2] poppins font-medium text-[16px] py-5 rounded-[5px]">
                            Book Now
                        </button>
                    @endif

                </div>

                <div class=" rounded-[5px] border border-[#E5E5E5]  p-6">
                    <h3 class="text-[22px] text-[#143453] fo-m font-medium">Certificates</h3>
                    <div class="border-t  mx-auto border-[#d1cdcd] mb-2 mt-2"></div>
                    <div class="grid sm:grid-cols-3 grid-cols-2 gap-3">

                        @foreach ($tutor->certificates as $certificate)
                            <div class="border rounded-[5px] border-[#F24646] p-1 text-center text-wrap">
                                <img src="{{ asset('site/Sites/images/pdf-image.png') }}" class="mx-auto p-5">

                                <div class="border-t mx-auto border-[#d1cdcd]"></div>

                                <p class="text-sm text-[#171717] roboto mt-2 font-normal">
    {{ \Illuminate\Support\Str::limit($certificate->certificate_name, 10) }}
</p>

                                <a href="{{ asset($certificate->document) }}" download
                                    class="text-xs cursor-pointer rounded-sm w-full block p-2 bg-[#F24646] text-white mt-3 text-center">
                                    Download
                                </a>
                            </div>
                        @endforeach

                    </div>
                </div>

                <div id="ratings"
                    class=" rounded-[10px] border h-[50%] max-h-[822px] overflow-auto hide-scrollbar border-[#E5E5E5] shadow-sm p-6">
                    <div class="flex justify-between w-full  border-b border-[#E5E5E5]">
                        <div class="xl:w-[20%] lg:w-[10%] w-[20%] ">
                            <h3
                                class="xl:text-[24px] lg:text-[20px] sm:text-[24px] text-lg mb-4 text-[#143453] fo-m font-medium">
                                Reviews</h3>
                        </div>
                        <div class="flex  w-[50%]  justify-end">
                            <div class="text-[#F4C701] xl:text-[24px] lg:text-[17px] sm:text-[24px] text-lg"><i
                                    class="fa-solid fa-star"></i> </div>
                            <div class="text-[#F4C701] xl:text-[24px] lg:text-[17px] sm:text-[24px] text-lg"><i
                                    class="fa-solid fa-star"></i> </div>
                            <div class="text-[#F4C701] xl:text-[24px] lg:text-[17px] sm:text-[24px] text-lg"><i
                                    class="fa-solid fa-star"></i> </div>
                            <div class="text-[#F4C701] xl:text-[24px] lg:text-[17px] sm:text-[24px] text-lg"><i
                                    class="fa-solid fa-star"></i> </div>
                            <div class="text-[#C3C3C3] xl:text-[24px] lg:text-[17px] sm:text-[24px] text-lg"><i
                                    class="fa-solid fa-star"></i> </div>
                        </div>
                        <div class="xl:w-[30%] lg:w-[40%] sm:w-[30%] w-[50%] p-2 flex justify-end">

                            <h3 class="text-[#6E6E6E] poppins xl:text-[14px] text-[13px] font-medium">
                                {{ $tutor->average_rating }} / 5 ({{ $tutor->tutorReviews()->count() }}
                                reviews)
                            </h3>
                        </div>
                    </div>

                    @foreach ($reviews as $review)
                        <div class="border border-[#CACACA] cardShadow rounded-[10px] mt-4 p-5 mb-4">

                            <div class="flex items-center gap-2 mb-1">
                                <div class="w-[50%] flex gap-2">
                                    <img src="{{ asset($review->user->profile ?? $review->user->studentDefaultImage) }}"
                                        class="w-8 h-8 rounded-full">

                                    <p
                                        class="font-medium fo-m xl:text-lg lg:text-[16px] sm:text-lg text-[13px] text-[#143453] mt-1">
                                        {{ $review->user->first_name . ' ' . $review->user->last_name ?? 'Anonymous' }}
                                    </p>
                                </div>

                                <div class="flex sm:w-[50%] justify-end">
                                    @for ($i = 1; $i <= 5; $i++)
                                        <div
                                            class="{{ $i <= $review->rating ? 'text-[#F4C701]' : 'text-[#C3C3C3]' }} text-[18px]">
                                            <i class="fa-solid fa-star"></i>
                                        </div>
                                    @endfor
                                </div>
                            </div>

                            <p class="text-[15px] roboto text-[#171717] mt-3">
                                {{ $review->review }}
                            </p>
                        </div>
                    @endforeach

                    <div class="w-full flex justify-center mt-12">
                        {!! $reviews->links('site.partials.ajax-pagination') !!}

                    </div>
                </div>
                                            @if(($tutor->id != auth()->id()))

                            <button command="show-modal" commandfor="review"
                                class="w-full cursor-pointer bg-[#F4C701] py-4 rounded-[5px] text-[#000000] text-[17px] poppins font-medium mb-5">
                                Add Review
                            </button>
                            @endif
                
            </div>
        </div>
    </section>

    <el-dialog>
        <dialog id="dialog" 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="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="relative transform overflow-hidden rounded-sm bg-gray-800 text-left shadow-xl
                        transition-all
                        w-full
                        sm:w-[90vw]
                        max-w-[1100px]
                        max-h-[90vh]
                        overflow-y-auto
                        sm:my-8
                        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
                        data-closed:sm:translate-y-0 data-closed:sm:scale-95">

                    <div class="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">Book a Session</h1>
                            </div>
                            <button command="close" commandfor="dialog" class="cursor-pointer">

                                <i class="fa-solid fa-x" class="text-[#717680]"></i>
                            </button>
                        </div>
                        <div class="mt-3">

                            <p class="fo-m text-[16px] text-[#414651] font-medium">Select Subject(s)*</p>

                            <div class="relative w-full mt-3">
                                <select id="courseApplyModal" multiple name="subjects[]"
                                    class="select2 subjects  w-full appearance-none text-[#717680] fo-n text-sm border-[#D5D7DA] border-[1.29px] p-3 pr-10 rounded-[10px] bg-white">
                                    
                                    @foreach ($tutor->subjects as $subject)
                                        <option value="{{ $subject->id }}">{{ $subject->subject_name }}</option>
                                    @endforeach
                                </select>

                            </div>
                            <div class="mt-3">
                                <div class="flex items-center justify-between mb-4">
                                    <h2 class="text-[15px] font-medium text-[#414651] fo-m">Choose Timeslots</h2>

                                </div>
                                <div id="modalCalender">

                                </div>
                                <p id="selectionError" class="text-red-600 text-sm mt-2 hidden"></p>

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

                                    <button type="button" id="continueToPayment"
                                        class="bg-[#F4C701] px-3 cursor-pointer border-[#D5D7DA] border rounded-[10px] w-full sm:py-5 py-3 text-[#000000] fm-xb mt-3 text-[16px]">
                                        Continue
                                    </button>

                                    <p class="text-[#717680] fo-n text-sm text-center px-10 mt-2">
                                        Payment for the lesson will be charged 24 hours before the lesson. Lesson
                                        cancellation will be available before the payment is made. If payment for the lesson
                                        is unsuccessful, the lesson will be automatically cancelled.
                                    </p>
                                </div>
                            </div>


                        </div>
                    </div>

                </el-dialog-panel>
            </div>

        </dialog>
    </el-dialog>

    {{-- payment modal --}}
    <el-dialog>
        <dialog id="calenderModal" 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">

                    <form id="payment-form">

                        <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">Book Session</h1>
                                </div>
                                <button type="button" command="close" commandfor="calenderModal"
                                    class="cursor-pointer">

                                    <img src="{{ asset('site/Sites/images/cros-icon.png') }}" />
                                </button>
                            </div>
                            <div class="mt-3">
                                <p class="fo-m text-[18px] text-[#414651] font-medium">Number of sessions</p>
                                <div class="field w-full">

                                    <input name="total_sessions" id="total_sessions" readonly
                                        class="w-full text-[#717680] mt-3 fo-n text-[17px] border-[#D5D7DA] border-[1.29px] sm:p-5 p-3 rounded-[10px] bg-white"
                                        type="number" placeholder="Number of sessions">
                                </div>
                            </div>




                            <div class="mt-3">
                                <h2 class="text-[16px] font-medium mb-2 text-[#414651] fo-m  mt-5">Total Price</h2>
                                <button
                                    class="totalPrice 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]">
                                    $0
                                </button>
                                <div class="mt-3">
                                    <div id="paypal-button-container"></div>

                                </div>
                            </div>


                        </div>
                    </form>

                </el-dialog-panel>
            </div>
        </dialog>
    </el-dialog>

    {{-- review modal --}}
    <el-dialog>
        <dialog id="review"
            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">
            </el-dialog-backdrop>

            <div class="m-auto flex min-h-full items-center justify-center p-4">
                <el-dialog-panel class="relative sm:w-[585px] rounded-sm bg-white shadow-xl transition-all">

                    <div class="px-6 py-5">
                        <!-- Header -->
                        <form action="{{ route('add.review', encrypt($tutor->id)) }}" method="post">
                            @csrf
                            <div class="flex justify-between items-center mb-4">
                                <h1 class="text-[#181D27] fo-m text-[22px]">Leave a Review</h1>
                                <button type="button" command="close" commandfor="review">
                                    <img src="{{ asset('site/Sites/images/cros-icon.png') }}" />
                                </button>
                            </div>

                            <!-- Rating -->
                            <p class="text-[16px] font-medium text-[#414651] mb-2">Your Rating</p>

                            <div class="flex gap-2 mb-4" id="starRating">
                                <span class="star" data-value="1">★</span>
                                <span class="star" data-value="2">★</span>
                                <span class="star" data-value="3">★</span>
                                <span class="star" data-value="4">★</span>
                                <span class="star" data-value="5">★</span>
                            </div>

                            <input type="hidden" id="rating_value" name="rating">

                            <!-- Review -->
                            <label class="text-[16px] font-medium text-[#414651]">Your Review</label>
                            <textarea name="review" class="w-full mt-2 border border-[#D5D7DA] rounded-md p-3 focus:outline-none" rows="4"
                                placeholder="Write your review here..." required></textarea>
                            @error('review')
                            <span class="text-red-600">{{ $message }}</span>
                            @enderror
                            <!-- Submit -->
                                
                            <button type="submit"
                            class="w-full mt-5 bg-[#1CD8C4] text-white py-3 rounded-md font-medium">
                            Submit Review 
                        </button>
                        
                    </form>
                    </div>

                </el-dialog-panel>
            </div>
        </dialog>
    </el-dialog>




    @push('script')
        <script
            src="https://www.paypal.com/sdk/js?client-id=AYm821KSWjcTTZDmB4CAmF9z37Wnf__7TsgU8xK6dH2ph9WygPQgWWgixRBVpLo1pr0SrFdANYrz37O6&currency=USD">
        </script>

        <script>
            $('.select2').select2({
                                    placeholder: "Select subjects",
                                    allowClear: true
                                });
            function fetchWeek(startDate = null) {

                let url = '{{ url('week') }}?tutorId={{ $tutor->id }}';

                if (startDate) {
                    url += '&start_date=' + startDate;
                }

                fetch(url)
                    .then(res => res.text())
                    .then(data => {

                        document.getElementById('calenderData').innerHTML = data;


                    });
            }

            function fetchModalSlots(startDate = null) {

                let url = '{{ url('week/slots') }}?tutorId={{ $tutor->id }}';

                if (startDate) {
                    url += '&start_date=' + startDate;
                }

                fetch(url)
                    .then(res => res.text())
                    .then(data => {
                        document.getElementById('modalCalender').innerHTML = data;
                    });
            }

            let total = 0;
            $(document).on('change', '.slot_check_box', function() {
                total = 0;
                // Loop through all checked checkboxes
                var totalSlots = 0;
                $('.slot_check_box:checked').each(function() {
                    totalSlots++;
                    total += parseFloat($('#tutor_hourly_rate').data('price')) || 0;
                });

                $('#total_sessions').val(totalSlots)

                // Update total
                $('.totalPrice').text('$' + total.toFixed(2));
            });


            let subjects = [];
            let slots = [];
            $('#continueToPayment').on('click', function() {

                let selectedSubjects = $('.subjects').val(); // select2
                let selectedSlots = $('.slot_check_box:checked').length;

                $('#selectionError').addClass('hidden').text('');

                if (!selectedSubjects || selectedSubjects.length === 0) {

                    $('#selectionError')
                        .removeClass('hidden')
                        .text('Please select at least one subject.');
                    return;
                }


                if (selectedSlots === 0) {
                    $('#selectionError')
                        .removeClass('hidden')
                        .text('Please select at least one time slot.');
                    return;
                }

                $('.slot_check_box:checked').each(function() {
                    slots.push($(this).val());
                });

                subjects = selectedSubjects;

                document.getElementById('calenderModal').showModal();

            });


      
            paypal.Buttons({
                style: {
                    layout: 'vertical',
                    color: 'blue',
                    shape: 'rect',
                    label: 'paypal'
                },

                createOrder: function(data, actions) {
                    return actions.order.create({
                        purchase_units: [{
                            amount: {
                                value: total.toFixed(2)
                            }
                        }]
                    });
                },

                onApprove: function(data, actions) {

                    // 🔹 Show Loader
                    document.getElementById('paypal-loader').classList.remove('hidden');

                    return actions.order.capture().then(function(details) {

                        return $.post('{{ url('payment/success') }}', {
                            order_id: data.orderID,
                            slots: slots,
                            subjects: subjects,
                            tutor_id: {{ $tutor->id }}
                        }).done(function(response) {


                            if (response.status) {
                              resetBookingForm()
                                fetchWeek();
                                toastr.success(response.message);
                            } else {
                              
                                toastr.error(response.message);
                            }

                        }).fail(function() {
                            toastr.error("Something went wrong. Please try again.");
                        }).always(function() {

                            // 🔹 Hide Loader after complete response
                            document.getElementById('paypal-loader').classList.add('hidden');

                            document.getElementById('dialog').close();
                            document.getElementById('calenderModal').close();
                        });

                    });
                },

                onError: function(err) {
                    document.getElementById('paypal-loader').classList.add('hidden');
                    console.log('Error', err);
                    toastr.error("Payment failed.");
                }

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

            fetchWeek();

            const stars = document.querySelectorAll('#starRating .star');
            const ratingInput = document.getElementById('rating_value');

            stars.forEach(star => {
                star.addEventListener('click', function() {
                    const value = this.dataset.value;
                    ratingInput.value = value;

                    stars.forEach(s => {
                        s.classList.toggle('active', s.dataset.value <= value);
                    });
                });
            });


            function resetBookingForm() {
    // Reset total
    total = 0;
    $('.totalPrice').text('$0');

    // Reset sessions count
    $('#total_sessions').val('');

    // Reset subjects (IMPORTANT)
    $('.subjects').val(null).trigger('change');

    // Reset slots
    $('.slot_check_box').prop('checked', false);

    // Clear arrays
    subjects = [];
    slots = [];
}

            function checkPastSlots() {

                const now = new Date();

                document.querySelectorAll('.slot_time').forEach(function(slotEl) {

                    let text = slotEl.innerText.trim();

                    if (text.includes('--')) return;

                    let parts = text.split('~');
                    let startTime = parts[0].trim();

                    let parentColumn = slotEl.closest('[data-date]');
                    let slotDate = parentColumn ? parentColumn.dataset.date : null;

                    if (!slotDate) return;

                    let slotDateTime = new Date(slotDate + 'T' + startTime);

                    if (now >= slotDateTime) {

                        let label = slotEl.closest('label');
                        let checkbox = label.querySelector('.slot_check_box');

                        if (checkbox) {
                            checkbox.checked = false;
                            checkbox.disabled = true;
                        }

                        slotEl.classList.remove('text-green-600');
                        slotEl.classList.add('text-gray-400');
                    }

                });

            }

            checkPastSlots();

            setInterval(checkPastSlots, 30000);
        </script>
    @endpush
@endsection
