@extends('layouts.base')
@section('title', __('Book an appointment').' — '.$tenant->name)

@section('body')
<div class="container py-4" style="max-width:42rem">
    <div class="text-center mb-4">
        @if($tenant->logo_path)
            <img src="{{ asset('storage/'.$tenant->logo_path) }}" alt="" style="height:56px" class="mb-2">
        @endif
        <h1 class="h4 fw-bold">{{ $tenant->name }}</h1>
        <p class="mb-muted">{{ __('Book an appointment') }}</p>
        <a class="btn btn-sm mb-btn-ghost" href="?lang={{ app()->getLocale() === 'ar' ? 'en' : 'ar' }}">
            {{ app()->getLocale() === 'ar' ? 'EN' : 'عربي' }}
        </a>
    </div>

    @if(session('status'))<div class="alert alert-success">{{ session('status') }}</div>@endif
    @if(session('error'))<div class="alert alert-danger">{{ session('error') }}</div>@endif

    @if($dentists->isEmpty())
        <div class="mb-card p-4 text-center mb-muted">{{ __('Online booking is not available right now. Please contact the clinic.') }}</div>
    @else
    <form method="POST" action="{{ route('public.booking.store') }}" id="bookingForm">
        @csrf
        <div class="mb-card p-4 mb-3">
            <h2 class="h6 fw-semibold mb-3">1 · {{ __('Choose your dentist') }}</h2>
            <div class="d-flex flex-column gap-2">
                @foreach($dentists as $d)
                    <label class="mb-card p-3 d-flex align-items-center gap-3" style="cursor:pointer; box-shadow:none">
                        <input type="radio" name="dentist_id" value="{{ $d->id }}" class="form-check-input dentist-radio"
                               @checked(old('dentist_id') == $d->id) required>
                        <span class="status-chip" style="background: {{ $d->color }}">&nbsp;</span>
                        <span>
                            <strong>{{ $d->name }}</strong>
                            @if($d->specialty)<br><span class="mb-muted small">{{ $d->specialty }}</span>@endif
                        </span>
                    </label>
                @endforeach
            </div>
        </div>

        <div class="mb-card p-4 mb-3">
            <h2 class="h6 fw-semibold mb-3">2 · {{ __('Pick a date & time') }}</h2>
            <input type="date" id="pubDate" class="form-control mb-3"
                   min="{{ now($tenant->timezone)->toDateString() }}"
                   max="{{ now($tenant->timezone)->addDays(60)->toDateString() }}">
            <div id="pubSlots" class="d-flex flex-wrap gap-2">
                <span class="mb-muted small">{{ __('Choose a dentist and date to see available times.') }}</span>
            </div>
            <input type="hidden" name="starts_at" id="pubStartsAt" required>
            @error('starts_at')<div class="text-danger small mt-2">{{ $message }}</div>@enderror
        </div>

        <div class="mb-card p-4 mb-3">
            <h2 class="h6 fw-semibold mb-3">3 · {{ __('Your details') }}</h2>
            <div class="mb-3">
                <label class="form-label">{{ __('Full name') }}</label>
                <input name="full_name" value="{{ old('full_name') }}" class="form-control @error('full_name') is-invalid @enderror" required>
                @error('full_name')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>
            <div class="mb-3">
                <label class="form-label">{{ __('Phone (WhatsApp)') }}</label>
                <input name="phone" value="{{ old('phone') }}" dir="ltr" class="form-control @error('phone') is-invalid @enderror"
                       placeholder="07xx xxx xxxx" required>
                @error('phone')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>
            <div class="mb-1">
                <input name="reason" value="{{ old('reason') }}" class="form-control" placeholder="{{ __('Reason (optional)') }}">
            </div>
        </div>

        <button class="btn mb-btn-primary btn-lg w-100" id="pubSubmit" disabled>{{ __('Confirm booking') }}</button>
    </form>
    @endif
</div>

{{-- v2.1: floating WhatsApp contact button --}}
@if($tenant->whatsapp_number)
    <a class="wa-fab" target="_blank" rel="noopener" aria-label="WhatsApp"
       href="https://wa.me/{{ preg_replace('/\D+/', '', $tenant->whatsapp_number) }}?text={{ urlencode(__('Hello :clinic, I have a question.', ['clinic' => $tenant->name])) }}">💬</a>
@endif

@push('scripts')
<script>
const radios = document.querySelectorAll('.dentist-radio');
const dateEl = document.getElementById('pubDate');
const slotsEl = document.getElementById('pubSlots');
const startsAtEl = document.getElementById('pubStartsAt');
const submitEl = document.getElementById('pubSubmit');

function selectedDentist() {
    return [...radios].find(r => r.checked)?.value;
}
async function loadSlots() {
    startsAtEl.value = '';
    submitEl.disabled = true;
    const dentist = selectedDentist();
    if (!dentist || !dateEl.value) return;
    slotsEl.innerHTML = '<span class="mb-muted small">…</span>';
    const url = new URL('{{ route('public.booking.slots') }}');
    url.searchParams.set('dentist_id', dentist);
    url.searchParams.set('date', dateEl.value);
    const { data } = await fetch(url, { headers: { Accept: 'application/json' } }).then(r => r.json());
    slotsEl.innerHTML = data.length ? '' : '<span class="mb-muted small">{{ __('No free slots on this day.') }}</span>';
    data.forEach(slot => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = 'slot-chip';
        b.textContent = slot.label;
        b.onclick = () => {
            slotsEl.querySelectorAll('.slot-chip').forEach(x => x.classList.remove('selected'));
            b.classList.add('selected');
            startsAtEl.value = slot.starts_at_local;
            submitEl.disabled = false;
        };
        slotsEl.appendChild(b);
    });
}
radios.forEach(r => r.addEventListener('change', loadSlots));
dateEl.addEventListener('change', loadSlots);
</script>
@endpush
@endsection
