@extends('tutor.layouts.layout')
@section('title', 'My calender')
@section('content')
    <div class=" flex xl:flex-nowrap flex-wrap gap-4 w-full">

        <div
            class="flex sm:flex-nowrap flex-wrap border 2xl:w-[52%] xl:w-[70%] w-full border-[#D9D9D9] rounded-lg overflow-hidden bg-white">
            <div class="sm:w-[57%] w-full  border-r border-[#D9D9D9]">
                <div class="p-6 pb-2">
                    <h3 class="font-semibold text-[22px] mb-1 text-[#133754] Poppins-medium">Set your availability</h3>
                    <div class="flex items-center gap-2 mb-2 mt-5">
                        <i class="fa-regular fa-calendar-days text-lg"></i>
                        <p class="text-[#222222] Poppins-medium text-[16px] leading-none">
                            Weekly hours
                        </p>
                    </div>
                    <p class="Poppins text-sm text-[#626262]">Set when you are typically available for meetings</p>
                </div>

                <hr class="text-[#D9D9D9]">
                <form action="{{ route('tutor.set.availability') }}" method="post">
                    @csrf
                    <div class="space-y-4 p-6">
                        @foreach ($availability as $day => $data)
                            <div class="{{ $day }}">
                                <div class="flex items-center justify-between mb-2">
                                    <label
                                        class="flex items-center gap-4 text-[#222222] Poppins-medium text-[16px] cursor-pointer">
                                        {{-- <input type="checkbox" {{ $data['added'] ? 'checked' : '' }} class="hidden peer"> --}}
                                        <input type="checkbox" name="days[{{ $day }}]" value="1"
                                            {{ $data['added'] ? 'checked' : '' }} class="day-toggle hidden peer"
                                            data-day="{{ $day }}">

                                        @if ($data['added'] == true)
                                            <span
                                                class="w-[25px] h-[25px] flex items-center justify-center
                                                    rounded border border-[#1CD8C4]
                                                    bg-white
                                                    peer-checked:bg-[#1CD8C4]
                                                    peer-checked:[&amp;&gt;img]:block">

                                                <img src="{{asset('newsites/admin/images/tick-icon.png')}}"
                                                    class="hidden">
                                            </span>
                                        @else
                                            <span
                                                class="w-[25px] h-[25px] flex items-center justify-center
                                                    rounded border border-[#1CD8C4]
                                                    bg-white
                                                    peer-checked:bg-[#1CD8C4]
                                                    peer-checked:[&amp;&gt;img]:block">

                                                <img src="{{asset('newsites/admin/images/tick-icon.png')}}"
                                                    class="hidden">
                                            </span>
                                        @endif



                                        {{ ucFirst($day) }}
                                    </label>
                                    <span class="text-sm text-[#1CD8C4] Poppins-medium cursor-pointer add-slot"
                                        data-day="{{ $day }}">
                                        Add another Timeslot
                                    </span>

                                </div>

                                {{-- <div class="slots-wrapper mt-6 space-y-4"> --}}
                                <div class="slots-wrapper mt-6 space-y-4 {{ $data['added'] ? '' : 'hidden' }}">

                                    @if ($data['added'])
                                        @foreach ($data['slots'] as $index => $slot)
                                            <div class="flex gap-3 slot-row">

                                                <div class="relative w-1/2">
                                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                                        From
                                                    </label>

                                                    <select name="slots[{{ $day }}][{{ $index }}][start]"
                                                        class="from-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
                                                        px-3 pt-[18px] pb-[10px] pr-8 text-sm
                                                        focus:outline-none focus:border-teal-400">

                                                            @for ($i = 0; $i < 24; $i++)
                                                            <option
                                                                {{ $slot['start_time'] == sprintf('%02d:00:00', $i) ? 'selected' : '' }}
                                                                value="{{ sprintf('%02d:00:00', $i) }}">
                                                                {{ sprintf('%02d:00', $i) }}
                                                            </option>
                                                        @endfor
                                                    </select>
                                                    <div
                                                        class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                        <img src="{{asset('site/Sites/images/arrow-down.png')}}"
                                                            class=" text-gray-500">

                                                    </div>
                                                </div>

                                                <div class="relative w-1/2">
                                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                                        To
                                                    </label>

                                                    <select name="slots[{{ $day }}][{{ $index }}][end]"
                                                        class="to-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
                                                    px-3 pt-[18px] pb-[10px] pr-8 text-sm
                                                    focus:outline-none focus:border-teal-400"
                                                        readonly>
                                                        <option value="{{ sprintf('%02d:00', $slot['end_time']) }}">
                                                            {{ sprintf('%02d:00', $slot['end_time']) }}</option>
                                                    </select>
                                                    <div
                                                        class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                        <img src="{{asset('site/Sites/images/arrow-down.png')}}"
                                                            class=" text-gray-500">

                                                    </div>

                                                </div>
                                                <button type="button" class="text-[red] cursor-pointer remove-slot"><i
                                                        class="fa-solid fa-trash"></i></button>

                                            </div>
                                        @endforeach
                                        @else
                                          <div class="flex gap-3 slot-row">

                                                <div class="relative w-1/2">
                                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                                        From
                                                    </label>

                                                    <select name="slots[{{ $day }}][0][start]"
                                                        class="from-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
                                                        px-3 pt-[18px] pb-[10px] pr-8 text-sm
                                                        focus:outline-none focus:border-teal-400">

                                                            @for ($i = 0; $i < 24; $i++)
                                                            <option
                                                                value="{{ sprintf('%02d:00:00', $i) }}">
                                                                {{ sprintf('%02d:00', $i) }}
                                                            </option>
                                                        @endfor
                                                    </select>
                                                    <div
                                                        class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                        <img src="{{asset('site/Sites/images/arrow-down.png')}}"
                                                            class=" text-gray-500">

                                                    </div>
                                                </div>

                                                <div class="relative w-1/2">
                                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                                        To
                                                    </label>

                                                    <select name="slots[{{ $day }}][0][end]"
                                                        class="to-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
                                                    px-3 pt-[18px] pb-[10px] pr-8 text-sm
                                                    focus:outline-none focus:border-teal-400"
                                                        readonly>
                                                        <option value="01:00">
                                                            01:00</option>
                                                    </select>
                                                    <div
                                                        class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                        <img src="{{asset('site/Sites/images/arrow-down.png')}}"
                                                            class=" text-gray-500">

                                                    </div>

                                                </div>
                                                <button type="button" class="text-[red] cursor-pointer remove-slot"><i
                                                        class="fa-solid fa-trash"></i></button>

                                            </div>
                                    @endif
                                </div>



                            </div>
                        @endforeach




                    </div>
                    <button type="submit"
                        class="w-full bg-[#133754] cursor-pointer Poppins-medium text-[15px]  text-white py-3 rounded font-medium">
                        Save
                    </button>
                </form>

            </div>


            <div class="sm:w-[43%] w-full p-4 pt-1">
                <div class="flex items-center gap-2 mb-2 mt-5">
                    <i class="fa-regular fa-calendar-days text-xl"></i>
                    <p class="text-[#222222] Poppins-medium text-[16px] leading-none">
                        Date-specific hours
                    </p>
                </div>
                <p class="Poppins text-sm text-[#626262]">Adjust hours for specific days</p>


                <button onclick="duplicateDateSection()"
                    class="bg-[#F4C701] w-full text-center text-[#133754] text-[16px] Poppins-medium font-medium px-4 mt-3 py-[10px] rounded mb-4 cursor-pointer">
                    + Date
                </button>
                <form action="{{ route('tutor.unavailable.slots') }}" method="post">
                    @csrf
                    @if ($tutorOverRideDate->count() > 0)
                        @foreach ($tutorOverRideDate as $date)

                            <div id="date-wrapper" class="space-y-6 ">

                                <div class="date space-y-6">

                                    


                                    <div class="relative w-full">

                                        <label
                                            class="absolute -top-2 left-3 bg-white px-1
                                 text-sm text-[#49454F] Poppins z-10">
                                            Date
                                        </label>


                                        <select name="dates[0][date]"
                                            class="w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
                                px-3 pt-[18px] pb-[10px] pr-8 text-sm
                                focus:outline-none focus:border-teal-400">

                                            @php
                                                $today = \Carbon\Carbon::now();
                                                $startOfMonth = $today->copy()->startOfMonth();
                                                $endOfMonth = $today->copy()->endOfMonth();
                                                
                                                $slots = $date->slots;

                                                $dbDate = $date['date'];
                                                
                                               
                                                
                                            @endphp

                                            @for ($date = $startOfMonth->copy(); $date <= $endOfMonth; $date->addDay())
                                                <option value="{{ $date->format('Y-m-d') }}" {{ ($dbDate == $date->format('Y-m-d'))?"selected":"" }}>
                                                    {{ $date->format('d/m/Y') }}
                                                </option>
                                            @endfor

                                        </select>
                                

                                    
                                        <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                            <img src="{{ asset('tutor/images/arrow-down.png') }}" class=" text-gray-500" />

                                        </div>
                                    </div>


                                    <div id="time-wrapper" class="time space-y-6">
                                        @foreach($slots as $slot)
                                        <div class="slot-group relative w-full flex flex-col space-y-2">
                                            <!-- From -->
                                            <div class="relative w-full">
                                                <label
                                                    class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">
                                                    From
                                                </label>
                                                <select name="dates[0][slots][0][start]"
                                                    class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                                                    @for ($i = 0; $i < 24; $i++)
                                                        <option value="{{ sprintf('%02d:00:00', $i) }}" {{ ($slot->start_time == sprintf('%02d:00:00', $i))?"selected":"" }}>
                                                            {{ sprintf('%02d:00', $i) }}</option>
                                                    @endfor
                                                </select>
                                                <div
                                                    class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                    <img src="{{ asset('tutor/images/arrow-down.png') }}"
                                                        class="text-gray-500" />
                                                </div>
                                            </div>

                                            <!-- To -->
                                            <div class="relative w-full">
                                                <label
                                                    class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">
                                                    To
                                                </label>
                                                <select name="dates[0][slots][0][end]"
                                                    class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                                                    @for ($i = 0; $i < 24; $i++)
                                                        <option value="{{ sprintf('%02d:00:00', $i) }}" {{ ($slot->end_time == sprintf('%02d:00:00', $i))?"selected":"" }}>
                                                            {{ sprintf('%02d:00', $i) }}</option>
                                                    @endfor
                                                </select>
                                                <div
                                                    class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                                    <img src="{{ asset('tutor/images/arrow-down.png') }}"
                                                        class="text-gray-500" />
                                                </div>
                                            </div>

                                            <!-- Remove button for initial slot -->
                                            <span onclick="removeSlot(this)"
                                                class="text-red-500 text-sm cursor-pointer remove-slots">Remove slot</span>
                                        </div>
                                        @endforeach
                                        <span onclick="duplicateTimeSlot(this)"
                                            class="text-sm text-[#1CD8C4] Poppins-medium cursor-pointer float-right -mt-3">
                                            Add another Timeslot
                                        </span>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    @else
                        <div id="date-wrapper" class="space-y-6"></div>
                    @endif
                    <button type="submit"
                        class="w-full cursor-pointer bg-[#133754] Poppins-medium text-[15px] text-white py-4 mt-8 rounded font-medium">
                        Save
                    </button>
                </form>
            </div>


        </div>

        <div class=" border-[#E5E5E5] rounded-[10px] border  p-2 xl:w-[48%] md:w-[57%] w-full">
            <div class="flex items-center justify-between mb-4">


            </div>
            <div id="data"></div>

        </div>
    </div>


    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function() {

                // Auto set 1 hour end time
                // document.addEventListener('change', function(e) {
                //     if (e.target.classList.contains('from-time')) {

                //         let fromSelect = e.target;
                //         let row = fromSelect.closest('.slot-row');
                //         let wrapper = fromSelect.closest('.slots-wrapper');
                //         let selectedValue = fromSelect.value;

                //         // 🔴 Check for duplicate start time in same day
                //         let duplicate = false;

                //         wrapper.querySelectorAll('.from-time').forEach(select => {
                //             if (select !== fromSelect && select.value === selectedValue) {
                //                 duplicate = true;
                //             }
                //         });

                //         if (duplicate) {
                //             alert('This time is already selected for this day.');
                //             fromSelect.value = ''; // reset selection
                //             return;
                //         }

                //         // ✅ Auto set 1 hour end time
                //         let toSelect = row.querySelector('.to-time');

                //         let hour = parseInt(selectedValue.split(':')[0]);
                //         let nextHour = (hour + 1).toString().padStart(2, '0') + ':00:00';

                //         toSelect.innerHTML = `<option value="${nextHour}" selected>
        //                 ${nextHour.substring(0,5)}
        //               </option>`;
                //     }
                // });

                document.addEventListener('change', function(e) {
                    if (e.target.classList.contains('from-time')) {

                        let fromSelect = e.target;
                        let row = fromSelect.closest('.slot-row');
                        let wrapper = fromSelect.closest('.slots-wrapper');
                        let selectedValue = fromSelect.value;

                        // 🔴 Duplicate check
                        let duplicate = false;

                        wrapper.querySelectorAll('.from-time').forEach(select => {
                            if (select !== fromSelect && select.value === selectedValue) {
                                duplicate = true;
                            }
                        });

                        if (duplicate) {
                            alert('This time is already selected for this day.');
                            fromSelect.selectedIndex = 0;
                            return;
                        }

                        // ✅ Safe hour addition
                        let toSelect = row.querySelector('.to-time');
                        let nextHour = addOneHour(selectedValue);

                        toSelect.innerHTML = `
            <option value="${nextHour}" selected>
                ${nextHour.substring(0,5)}
            </option>
        `;
                    }
                });

                // Add new slot
                document.querySelectorAll('.add-slot').forEach(btn => {

                    btn.addEventListener('click', function() {

                        let day = this.dataset.day;
                        let parent = this.closest('.' + day);
                        let wrapper = parent.querySelector('.slots-wrapper');

                        let index = wrapper.querySelectorAll('.slot-row').length;

                        let slotHTML = `
                            <div class="flex gap-3 slot-row">

                                <div class="relative w-1/2">
                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                        From
                                    </label>

                                    <select name="slots[${day}][${index}][start]"
                                        class="from-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
               px-3 pt-[18px] pb-[10px] pr-8 text-sm
               focus:outline-none focus:border-teal-400">

                                        ${generateHours()}
                                    </select>
                                    <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                <img src="{{asset('site/Sites/images/arrow-down.png')}}" class=" text-gray-500">

                            </div>
                                </div>

                                <div class="relative w-1/2">
                                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm">
                                        To
                                    </label>

                                    <select name="slots[${day}][${index}][end]"
                                        class="to-time w-full appearance-none text-[#1D1B20] Poppins placeholder:text-[#1D1B20] text-[18px] border border-[#DBDBDB] rounded
               px-3 pt-[18px] pb-[10px] pr-8 text-sm
               focus:outline-none focus:border-teal-400"
                                        readonly>
                                    </select>
                                    <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                                <img src="{{asset('site/Sites/images/arrow-down.png')}}" class=" text-gray-500">

                            </div>
                                </div>
<button type="button" class="text-[red] cursor-pointer remove-slot"><i class="fa-solid fa-trash"></i></button>
                            </div>
                        `;

                        wrapper.insertAdjacentHTML('beforeend', slotHTML);
                    });

                });


                function generateHours() {
                    let options = `<option value="" selected>--:--</option>`; // Default blank option
                    for (let i = 0; i < 24; i++) {
                        let hour = i.toString().padStart(2, '0');
                        options += `<option value="${hour}:00:00">${hour}:00</option>`;
                    }
                    return options;
                }


            });
            // Show / Hide slots when checkbox toggled
            document.addEventListener('change', function(e) {

                if (e.target.classList.contains('day-toggle')) {

                    let day = e.target.dataset.day;
                    let parent = e.target.closest('.' + day);
                    let wrapper = parent.querySelector('.slots-wrapper');

                    if (e.target.checked) {
                        wrapper.classList.remove('hidden');
                    } else {
                        wrapper.classList.add('hidden');

                        // Optional: remove all slots when unchecked
                        wrapper.innerHTML = '';
                    }
                }
            });


            function fetchModalSlots(startDate = null) {
                let url = '{{url('/tutor/dashboard/week/slots')}}';

                if (startDate) url += '?start_date=' + startDate;

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

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

                    });
            }

            let total = 0;
            $(document).on('change', '.slot_check_box', function() {

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

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

            fetchModalSlots()


            // specific date section
            // function duplicateTimeSlot(button) {

            //     const dateSection = button.closest('.date');
            //     const wrapper = dateSection.querySelector('.time');

            //     const dateIndex = Array.from(
            //         document.querySelectorAll('#date-wrapper .date')
            //     ).indexOf(dateSection);

            //     const existingSlots = wrapper.querySelectorAll('[name*="[start]"]');
            //     const newSlotIndex = existingSlots.length;

            //     const blocks = wrapper.querySelectorAll('.relative.w-full');

            //     const fromClone = blocks[0].cloneNode(true);
            //     const toClone = blocks[1].cloneNode(true);

            //     fromClone.querySelector('select').name =
            //         `dates[${dateIndex}][slots][${newSlotIndex}][start]`;

            //     toClone.querySelector('select').name =
            //         `dates[${dateIndex}][slots][${newSlotIndex}][end]`;

            //     fromClone.querySelector('select').selectedIndex = 0;
            //     toClone.querySelector('select').selectedIndex = 0;

            //     wrapper.insertBefore(fromClone, button);
            //     wrapper.insertBefore(toClone, button);
            // }

            function duplicateTimeSlot(button) {
                const dateSection = button.closest('.date');
                const wrapper = dateSection.querySelector('.time');

                const dateIndex = Array.from(
                    document.querySelectorAll('#date-wrapper .date')
                ).indexOf(dateSection);

                const existingSlots = wrapper.querySelectorAll('.slot-group');
                const newSlotIndex = existingSlots.length;

                let fromClone, toClone;

                if (existingSlots.length > 0) {
                    const blocks = existingSlots[0].querySelectorAll('.relative.w-full');
                    fromClone = blocks[0].cloneNode(true);
                    toClone = blocks[1].cloneNode(true);
                } else {
                    fromClone = document.createElement('div');
                    fromClone.className = 'relative w-full';
                    fromClone.innerHTML = `
            <label class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">From</label>
            <select name="" class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                ${[...Array(24).keys()].map(i => `<option value="${String(i).padStart(2,'0')}:00:00">${String(i).padStart(2,'0')}:00</option>`).join('')}
            </select>
        `;

                    toClone = document.createElement('div');
                    toClone.className = 'relative w-full';
                    toClone.innerHTML = `
            <label class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">To</label>
            <select name="" class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                ${[...Array(24).keys()].map(i => `<option value="${String(i).padStart(2,'0')}:00:00">${String(i).padStart(2,'0')}:00</option>`).join('')}
            </select>
        `;
                }

                fromClone.querySelector('select').name = `dates[${dateIndex}][slots][${newSlotIndex}][start]`;
                toClone.querySelector('select').name = `dates[${dateIndex}][slots][${newSlotIndex}][end]`;

                fromClone.querySelector('select').selectedIndex = 0;
                toClone.querySelector('select').selectedIndex = 0;

                const slotGroup = document.createElement('div');
                slotGroup.className = 'slot-group space-y-2';
                slotGroup.appendChild(fromClone);
                slotGroup.appendChild(toClone);

                // Add remove button that calls the global removeSlot function
                const removeBtn = document.createElement('span');
                removeBtn.className = 'text-red-500 text-sm cursor-pointer block';
                removeBtn.innerText = 'Remove slot';
                removeBtn.setAttribute('onclick', 'removeSlot(this)');

                slotGroup.appendChild(removeBtn);

                wrapper.insertBefore(slotGroup, button);
            }

            function duplicateDateSection() {
                const wrapper = document.getElementById('date-wrapper');
                const dateIndex = wrapper.querySelectorAll('.date').length;

                const html = `
    <div class="date space-y-6">

        <div class="relative w-full">
            <label class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">
                Date
            </label>

            <select name="dates[${dateIndex}][date]"
                class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded
                px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                
                ${generateDateOptions()}
            </select>

            <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                <img src="{{ asset('tutor/images/arrow-down.png') }}" class="text-gray-500" />
            </div>
        </div>

        <div class="time space-y-6">

            <div class="slot-group space-y-2">

                <div class="relative w-full">
                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">
                        From
                    </label>

                    <select name="dates[${dateIndex}][slots][0][start]"
                        class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded
                        px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                        ${generateHours()}
                    </select>

                    <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                        <img src="{{ asset('tutor/images/arrow-down.png') }}" class="text-gray-500" />
                    </div>
                </div>

                <div class="relative w-full">
                    <label class="absolute -top-2 left-3 bg-white px-1 text-sm text-[#49454F] Poppins z-10">
                        To
                    </label>

                    <select name="dates[${dateIndex}][slots][0][end]"
                        class="w-full appearance-none text-[#1D1B20] Poppins text-[18px] border border-[#DBDBDB] rounded
                        px-3 pt-[18px] pb-[10px] pr-8 text-sm focus:outline-none focus:border-teal-400">
                        ${generateHours()}
                    </select>

                    <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center">
                        <img src="{{ asset('tutor/images/arrow-down.png') }}" class="text-gray-500" />
                    </div>  
                </div>

                <span onclick="removeSlot(this)"
                    class="text-red-500 text-sm cursor-pointer block">
                    Remove slot
                </span>

            </div>

            <span onclick="duplicateTimeSlot(this)"
                class="text-sm text-[#1CD8C4] Poppins-medium cursor-pointer float-right -mt-3">
                Add another Timeslot
            </span>

        </div>
    </div>
    `;

                wrapper.insertAdjacentHTML('beforeend', html);
            }

            function generateDateOptions() {
                let options = '';
                let today = new Date();

                let start = new Date(today.getFullYear(), today.getMonth(), 1);
                let end = new Date(today.getFullYear(), today.getMonth() + 1, 0);

                for (let d = new Date(today); d <= end; d.setDate(d.getDate() + 1)) {
                    let yyyy = d.getFullYear();
                    let mm = String(d.getMonth() + 1).padStart(2, '0');
                    let dd = String(d.getDate()).padStart(2, '0');

                    options += `<option value="${yyyy}-${mm}-${dd}">${dd}/${mm}/${yyyy}</option>`;
                }

                return options;
            }

            function generateHours() {
                let options = '';

                for (let i = 0; i < 24; i++) {
                    let hour = i.toString().padStart(2, '0');
                    options += `<option value="${hour}:00:00">${hour}:00</option>`;
                }

                return options;
            }

            function addOneHour(timeString) {
                // timeString format: "HH:MM:SS"
                let [hours, minutes, seconds] = timeString.split(':');
                let hourNum = parseInt(hours);

                // 1 hour add karo aur 24 hour ke baad 0 kar do (24h format)
                hourNum = (hourNum + 1) % 24;

                // Return format "HH:MM:SS"
                return `${hourNum.toString().padStart(2, '0')}:${minutes}:${seconds}`;
            }

            $(document).on('click', '.remove-slot', function() {
                $(this).closest('.slot-row').remove()

            })

            function removeSlot(button) {
                const slotGroup = button.closest('.slot-group');
                if (!slotGroup) return; // Safety check
                let date = button.closest('.date');

                slotGroup.remove();

                const dateSection =date; // <-- use closest, not querySelectorAll
                    if (dateSection) {
                    const remainingSlots = dateSection.querySelectorAll('.slot-group');
                    if (remainingSlots.length === 0) {
                        dateSection.remove(); // <-- this works now
                    }
                }
            }


            $('#unAvailableSlotsSubmitBtn').click(function() {
                let btn = $(this);

                let countTimes = $('.slot-group').length;
                if (countTimes > 0) {
                    btn.attr('type', 'submit')
                } else {
                    btn.attr('type', 'button')
                    toastr.error('Please select the slots to submit the form')
                }
            })
        </script>
    @endpush


@endsection
