@extends('layouts.frontend')

@section('title', 'Reschedule Booking - ' . $site->company_name)

@section('content')
    <div class="bg-primary-50 min-h-screen py-16">
        <div class="container mx-auto px-4">
            <div class="max-w-2xl mx-auto bg-white rounded-2xl shadow-xl overflow-hidden">

                <div class="bg-primary-600 p-8 text-center text-white">
                    <h1 class="text-3xl font-bold">Reschedule Booking</h1>
                    <p class="mt-2 opacity-90">
                        {{ $booking->service->name }} with {{ $booking->consultant->user->name }}
                    </p>
                </div>

                <div class="p-8 space-y-6">
                    <div class="bg-gray-50 p-4 rounded-xl border border-gray-200 text-sm text-gray-700">
                        <p>
                            <span class="font-bold">Current:</span>
                            {{ \Carbon\Carbon::parse($booking->scheduled_at)->format('M d, Y h:i A') }}
                        </p>
                    </div>

                    <form action="{{ route('booking.reschedule.update', $booking) }}" method="POST" class="space-y-6">
                        @csrf
                        @method('PATCH')

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-gray-700 font-bold mb-2">New Date</label>
                                <input type="date" name="booking_date" required min="{{ date('Y-m-d') }}"
                                    value="{{ old('booking_date', \Carbon\Carbon::parse($booking->scheduled_at)->format('Y-m-d')) }}"
                                    class="w-full border-gray-300 rounded-lg shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-200 p-3">
                                @error('booking_date') <p class="text-red-500 text-sm mt-1">{{ $message }}</p> @enderror
                            </div>
                            <div>
                                <label class="block text-gray-700 font-bold mb-2">New Time</label>
                                <select name="booking_time" id="booking_time" required
                                    class="w-full border-gray-300 rounded-lg shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-200 p-3 bg-white">
                                    <option value="">Loading available times...</option>
                                </select>
                                <p id="slot_help" class="text-xs text-gray-500 mt-1"></p>
                                @error('booking_time') <p class="text-red-500 text-sm mt-1">{{ $message }}</p> @enderror
                            </div>
                        </div>

                        <div class="flex justify-end gap-4 items-center">
                            <a href="{{ route('dashboard') }}" class="px-6 py-3 text-gray-600 hover:text-gray-900 font-bold transition">
                                Back
                            </a>
                            <x-primary-button class="px-8 py-3">
                                Save New Time
                            </x-primary-button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const dateEl = document.querySelector('input[name="booking_date"]');
            const timeEl = document.getElementById('booking_time');
            const helpEl = document.getElementById('slot_help');
            if (!dateEl || !timeEl) return;

            const slotsUrl = "{{ route('booking.slots') }}";
            const consultantId = @json($booking->consultant_id);
            const oldTime = @json(old('booking_time', \Carbon\Carbon::parse($booking->scheduled_at)->format('H:i')));

            const setLoading = (text) => {
                timeEl.innerHTML = `<option value="">${text}</option>`;
                helpEl.textContent = '';
            };

            const loadSlots = async () => {
                const date = dateEl.value;
                if (!consultantId || !date) {
                    setLoading('Select date to see times');
                    return;
                }

                setLoading('Loading available times...');

                const url = new URL(slotsUrl, window.location.origin);
                url.searchParams.set('consultant_id', consultantId);
                url.searchParams.set('date', date);

                try {
                    const res = await fetch(url.toString(), { headers: { 'Accept': 'application/json' } });
                    if (!res.ok) throw new Error('Failed to load slots');
                    const data = await res.json();

                    const slots = Array.isArray(data.slots) ? data.slots : [];
                    if (slots.length === 0) {
                        timeEl.innerHTML = `<option value="">No slots available</option>`;
                        helpEl.textContent = 'Try another date.';
                        return;
                    }

                    const options = ['<option value="">Select a time</option>']
                        .concat(slots.map(t => `<option value="${t}">${t}</option>`))
                        .join('');
                    timeEl.innerHTML = options;

                    if (oldTime) {
                        timeEl.value = oldTime;
                    }
                    helpEl.textContent = `${slots.length} slots available.`;
                } catch (e) {
                    timeEl.innerHTML = `<option value="">Unable to load slots</option>`;
                    helpEl.textContent = 'Please refresh the page.';
                }
            };

            dateEl.addEventListener('change', loadSlots);
            loadSlots();
        });
    </script>
@endpush

