@extends('layouts.app')
@section('title', __('Calendar'))

@section('content')
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
    <h1 class="h4 fw-bold mb-0">{{ __('Calendar') }}</h1>
    <div class="d-flex gap-2">
        <select id="dentistFilter" class="form-select form-select-sm" style="width:auto">
            <option value="">{{ __('All dentists') }}</option>
            @foreach($dentists as $d)
                <option value="{{ $d->id }}">{{ $d->name }}</option>
            @endforeach
        </select>
        @can('create', App\Models\Appointment::class)
            <button class="btn mb-btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newAppt">
                + {{ __('New appointment') }}
            </button>
        @endcan
    </div>
</div>

<div class="mb-card p-3">
    <div id="calendar"></div>
</div>

{{-- New appointment modal --}}
<div class="modal fade" id="newAppt" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content mb-card" method="POST" action="{{ route('tenant.appointments.store') }}">
            @csrf
            <div class="modal-header" style="border-color:var(--mb-line)">
                <h2 class="h6 fw-bold mb-0">{{ __('New appointment') }}</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">{{ __('Dentist') }}</label>
                    <select name="dentist_id" id="apptDentist" class="form-select" required>
                        @foreach($dentists as $d)
                            <option value="{{ $d->id }}">{{ $d->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">{{ __('Patient') }}</label>
                    <select name="patient_id" class="form-select" required>
                        @foreach($patients as $p)
                            <option value="{{ $p->id }}">{{ $p->full_name }} — {{ $p->phone }}</option>
                        @endforeach
                    </select>
                    <p class="mb-muted small mt-1 mb-0">
                        <a href="{{ route('tenant.patients.create') }}">{{ __('Add patient') }}</a>
                    </p>
                </div>
                <div class="mb-3">
                    <label class="form-label">{{ __('Date') }}</label>
                    <input type="date" id="apptDate" class="form-control" min="{{ now(\App\Support\ClinicTime::timezone())->toDateString() }}" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">{{ __('Available times') }}</label>
                    <div id="slotGrid" class="d-flex flex-wrap gap-2">
                        <span class="mb-muted small">{{ __('Pick a dentist and date.') }}</span>
                    </div>
                    <input type="hidden" name="starts_at" id="apptStartsAt" required>
                </div>
                <div class="mb-2">
                    <input name="reason" class="form-control" placeholder="{{ __('Reason (optional)') }}">
                </div>
            </div>
            <div class="modal-footer" style="border-color:var(--mb-line)">
                <button class="btn mb-btn-primary w-100" id="apptSubmit" disabled>{{ __('Book appointment') }}</button>
            </div>
        </form>
    </div>
</div>

@push('page-scripts')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
<script>
const csrf = '{{ csrf_token() }}';
const isRtl = document.documentElement.dir === 'rtl';

// ---- Calendar ----
const calendarEl = document.getElementById('calendar');
const dentistFilter = document.getElementById('dentistFilter');

const calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'timeGridWeek',
    direction: isRtl ? 'rtl' : 'ltr',
    locale: isRtl ? 'ar' : 'en',
    headerToolbar: {
        left: isRtl ? 'timeGridDay,timeGridWeek,dayGridMonth' : 'prev,next today',
        center: 'title',
        right: isRtl ? 'prev,next today' : 'timeGridDay,timeGridWeek,dayGridMonth',
    },
    buttonText: isRtl
        ? { today: 'اليوم', day: 'يوم', week: 'أسبوع', month: 'شهر' }
        : { today: 'Today', day: 'Day', week: 'Week', month: 'Month' },
    height: 'auto',
    nowIndicator: true,
    slotMinTime: '07:00:00',
    slotMaxTime: '23:00:00',
    editable: @json(auth()->user()->can('appointments.manage')),
    eventDurationEditable: false,
    events: (info, ok, fail) => {
        const url = new URL('{{ route('tenant.appointments.feed') }}');
        url.searchParams.set('start', info.startStr);
        url.searchParams.set('end', info.endStr);
        if (dentistFilter.value) url.searchParams.set('dentist_id', dentistFilter.value);
        fetch(url, { headers: { Accept: 'application/json' } })
            .then(r => r.json()).then(ok).catch(fail);
    },
    eventDrop: async (info) => {
        // info.event.start is clinic-local (feed serves local ISO strings).
        const d = info.event.start;
        const pad = n => String(n).padStart(2, '0');
        const local = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
        const res = await fetch(`appointments/${info.event.id}`, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf, Accept: 'application/json' },
            body: JSON.stringify({ starts_at: local }),
        });
        if (!res.ok) {
            const body = await res.json().catch(() => null);
            alert(body?.errors?.[0]?.detail ?? '{{ __('That time was just booked. Please pick another slot.') }}');
            info.revert();
        }
    },
    eventClick: (info) => {
        const p = info.event.extendedProps;
        if (confirm(`${info.event.title} — ${p.dentist}\n${p.statusLabel}\n\n{{ __('Open patient profile?') }}`)) {
            window.location = `patients/${p.patientId}`;
        }
    },
});
calendar.render();
dentistFilter.addEventListener('change', () => calendar.refetchEvents());

// ---- New appointment modal: live availability ----
const apptDentist = document.getElementById('apptDentist');
const apptDate = document.getElementById('apptDate');
const slotGrid = document.getElementById('slotGrid');
const apptStartsAt = document.getElementById('apptStartsAt');
const apptSubmit = document.getElementById('apptSubmit');

async function loadSlots() {
    apptStartsAt.value = '';
    apptSubmit.disabled = true;
    if (!apptDentist.value || !apptDate.value) return;
    slotGrid.innerHTML = '<span class="mb-muted small">…</span>';
    const url = new URL('{{ route('tenant.availability') }}');
    url.searchParams.set('dentist_id', apptDentist.value);
    url.searchParams.set('date', apptDate.value);
    const { data } = await fetch(url, { headers: { Accept: 'application/json' } }).then(r => r.json());
    slotGrid.innerHTML = data.length
        ? ''
        : '<span class="mb-muted small">{{ __('No free slots on this day.') }}</span>';
    data.forEach(slot => {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'slot-chip';
        btn.textContent = slot.label;
        btn.onclick = () => {
            slotGrid.querySelectorAll('.slot-chip').forEach(b => b.classList.remove('selected'));
            btn.classList.add('selected');
            apptStartsAt.value = slot.starts_at_local;
            apptSubmit.disabled = false;
        };
        slotGrid.appendChild(btn);
    });
}
apptDentist.addEventListener('change', loadSlots);
apptDate.addEventListener('change', loadSlots);
</script>
@endpush
@endsection
