@extends('layouts.app')
@section('title', __('clinicCore::lang.calendar'))

@section('css')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css">
<style>
/* ── Layout ───────────────────────────────────────────── */
.cal-layout { display: flex; gap: 0; align-items: flex-start; }
.cal-sidebar {
    width: 270px; flex-shrink: 0;
    margin-right: 16px;
}
.cal-main { flex: 1; min-width: 0; }

/* ── Sidebar Cards ────────────────────────────────────── */
.sb-card { background:#fff; border-radius:8px; box-shadow:0 1px 4px rgba(0,0,0,.08); margin-bottom:12px; overflow:hidden; }
.sb-card-header { padding:10px 14px; border-bottom:1px solid #f3f3f3; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#888; display:flex; align-items:center; gap:6px; }
.sb-card-body { padding:12px 14px; }

/* ── Date Display ─────────────────────────────────────── */
.today-display { text-align:center; padding:16px 14px 12px; }
.today-display .day-name { font-size:12px; text-transform:uppercase; letter-spacing:1px; color:#aaa; margin-bottom:2px; }
.today-display .day-num  { font-size:48px; font-weight:800; color:#2c3e50; line-height:1; }
.today-display .month-year { font-size:14px; color:#888; margin-top:4px; }

/* ── Stats ────────────────────────────────────────────── */
.stats-grid { display:grid; grid-template-columns:1fr 1fr; gap:8px; }
.stat-box { background:#f8fafc; border-radius:8px; padding:10px 8px; text-align:center; border:1px solid #e8ecf0; }
.stat-box .s-num  { font-size:22px; font-weight:800; line-height:1; }
.stat-box .s-lbl  { font-size:10px; text-transform:uppercase; letter-spacing:.4px; color:#94a3b8; margin-top:3px; }

/* ── Today's List ─────────────────────────────────────── */
.today-list { max-height:300px; overflow-y:auto; }
.today-apt {
    display:flex; align-items:center; gap:8px; padding:7px 0;
    border-bottom:1px solid #f5f5f5; text-decoration:none; color:#333;
    transition:background .12s; border-radius:4px; cursor:pointer;
}
.today-apt:last-child { border-bottom:none; }
.today-apt:hover { background:#f8f9fa; text-decoration:none; color:#333; }
.apt-time-badge { font-size:11px; font-weight:700; color:#64748b; width:38px; flex-shrink:0; text-align:right; }
.apt-status-dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.apt-info-col .pet { font-size:13px; font-weight:600; color:#1e293b; }
.apt-info-col .own { font-size:11px; color:#94a3b8; }
.apt-type-chip { font-size:10px; padding:2px 7px; border-radius:10px; font-weight:600; color:#fff; margin-left:auto; flex-shrink:0; }

/* ── Filters ──────────────────────────────────────────── */
.type-filter-grid { display:flex; flex-wrap:wrap; gap:5px; }
.type-chip {
    display:flex; align-items:center; gap:4px; padding:3px 9px;
    border-radius:12px; font-size:11px; font-weight:600; cursor:pointer;
    border:2px solid transparent; transition:opacity .15s, border-color .15s;
}
.type-chip.inactive { opacity:.35; }
.type-chip-dot { width:8px; height:8px; border-radius:50%; }

.legend-row { display:flex; align-items:center; gap:6px; font-size:12px; color:#555; margin-bottom:5px; }
.legend-dot { width:10px; height:10px; border-radius:50%; flex-shrink:0; }

/* ── FullCalendar Overrides ───────────────────────────── */
#clc_calendar {
    background:#fff; border-radius:8px; padding:14px;
    box-shadow:0 1px 4px rgba(0,0,0,.08);
}
.fc .fc-toolbar { margin-bottom:12px; flex-wrap:wrap; gap:8px; }
.fc .fc-toolbar-title { font-size:16px; font-weight:700; color:#2c3e50; }
.fc .fc-button { font-size:12px !important; padding:5px 10px !important; border-radius:5px !important; }
.fc .fc-button-primary { background:#2c3e50 !important; border-color:#2c3e50 !important; }
.fc .fc-button-primary:not(.fc-button-active):hover { background:#34495e !important; }
.fc .fc-button-active { background:#2980b9 !important; border-color:#2980b9 !important; }
.fc-event { border-radius:4px !important; border:none !important; cursor:pointer; }
.fc-event-custom { padding:3px 5px; line-height:1.3; position:relative; overflow:hidden; }
.fc-event-custom .ev-title { font-size:11px; font-weight:700; display:flex; align-items:center; gap:3px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; color:#fff; }
.fc-event-custom .ev-sub { font-size:10px; opacity:.92; display:flex; align-items:center; justify-content:space-between; gap:4px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; color:#fff; margin-top:1px; }
.fc-event-custom .ev-pet { overflow:hidden; text-overflow:ellipsis; flex:1; }
.fc-event-custom .ev-type-icon { font-size:9px; opacity:.85; }
.fc-event-custom .ev-status-dot {
    display:inline-block; width:8px; height:8px; border-radius:50%;
    box-shadow:0 0 0 1.5px rgba(255,255,255,.7);
    flex-shrink:0;
}
.fc-event-custom .ev-doc-badge {
    display:inline-flex; align-items:center; justify-content:center;
    width:15px; height:15px; border-radius:50%; font-size:7px; color:#fff;
    margin-left:auto; box-shadow:inset 0 0 0 1px rgba(255,255,255,.4);
    flex-shrink:0;
}
.fc-event-custom .ev-chips { display:inline-flex; gap:2px; flex-shrink:0; }
.fc-event-custom .ev-type-chip {
    display:inline-flex; align-items:center; justify-content:center;
    width:14px; height:14px; border-radius:3px; font-size:8px; color:#fff;
    box-shadow:inset 0 0 0 1px rgba(255,255,255,.35);
}
.fc-event-custom .ev-type-chip.ev-type-more {
    background:rgba(255,255,255,.25); color:#fff; font-weight:700; width:auto; padding:0 4px;
}
/* Hover: subtle lift */
.fc-event:hover .fc-event-custom { filter: brightness(1.07); }
.fc-timegrid-slot { height:28px !important; }
.fc-col-header-cell { background:#f8fafc; }

/* ── Quick View Modal ─────────────────────────────────── */
.qv-header { padding:18px 20px; border-radius:4px 4px 0 0; color:#fff; }
.qv-header .qv-type { font-size:12px; opacity:.8; text-transform:uppercase; letter-spacing:.5px; margin-bottom:4px; }
.qv-header .qv-pet { font-size:20px; font-weight:700; margin-bottom:2px; }
.qv-header .qv-owner { font-size:13px; opacity:.85; }
.qv-meta-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:14px; }
.qv-meta-item .qv-label { font-size:10px; text-transform:uppercase; letter-spacing:.5px; color:#aaa; margin-bottom:2px; }
.qv-meta-item .qv-value { font-size:13px; font-weight:600; color:#2c3e50; }
.status-pill { display:inline-flex; align-items:center; gap:4px; padding:3px 10px; border-radius:12px; font-size:12px; font-weight:600; color:#fff; }

/* ── Quick Create Modal ───────────────────────────────── */
.qc-section { background:#fff; border-radius:8px; padding:14px 16px; margin-bottom:14px; box-shadow:0 1px 3px rgba(0,0,0,.06); border:1px solid #e8ecf0; }
.qc-section-title { font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:.6px; color:#64748b; margin-bottom:10px; }
.qc-step-badge { display:inline-flex; align-items:center; justify-content:center; width:18px; height:18px; background:#3498db; color:#fff; border-radius:50%; font-size:10px; font-weight:700; margin-right:5px; flex-shrink:0; }
.qc-cascade-hint { font-size:10px; color:#94a3b8; margin-top:3px; min-height:13px; }
.qc-slot-grid { display:flex; flex-wrap:wrap; gap:5px; margin-top:6px; }
.qc-slot-btn { padding:5px 12px; border-radius:5px; border:1.5px solid #cbd5e1; background:#fff; font-size:11px; font-weight:600; cursor:pointer; transition:all .15s; color:#334155; min-width:90px; text-align:center; user-select:none; }
.qc-slot-btn:hover:not(.unavailable):not(.selected) { border-color:#3498db; color:#3498db; background:#eff6ff; }
.qc-slot-btn.selected { background:#3498db; color:#fff; border-color:#2471a3; }
.qc-slot-btn.booked-warn { background:#fff7ed; color:#c2410c; border-color:#fed7aa; }
.qc-slot-btn.unavailable { background:#fee2e2; color:#ef4444; border-color:#fca5a5; cursor:not-allowed; opacity:.7; text-decoration:line-through; }
.qc-overlap-alert { padding:7px 10px; background:#fff7ed; border:1px solid #fed7aa; border-radius:5px; color:#c2410c; font-size:11px; margin-top:6px; display:none; }
.qc-selection-summary { padding:7px 12px; background:#eff6ff; border:1px solid #bfdbfe; border-radius:5px; font-size:12px; margin-top:6px; display:none; }
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
@php
$typeColors = ['checkup'=>'#2980b9','vaccination'=>'#27ae60','surgery'=>'#c0392b','grooming'=>'#8e44ad','emergency'=>'#e67e22','other'=>'#7f8c8d'];
$typeIcons  = ['checkup'=>'fa-stethoscope','vaccination'=>'fa-syringe','surgery'=>'fa-procedures','grooming'=>'fa-cut','emergency'=>'fa-ambulance','other'=>'fa-notes-medical'];
$statusColors = ['pending'=>'#f39c12','waiting'=>'#0d9488','confirmed'=>'#3498db','in_progress'=>'#9b59b6','completed'=>'#27ae60','cancelled'=>'#e74c3c','no_show'=>'#95a5a6'];

$totalToday     = $todayAppointments->count();
$scheduledToday = $todayAppointments->whereIn('status', ['pending','confirmed'])->count();
$waitingToday   = $todayAppointments->where('status', 'waiting')->count();
$inProgToday    = $todayAppointments->where('status','in_progress')->count();
$doneToday      = $todayAppointments->where('status','completed')->count();
$calTimeFormat  = session('business.time_format', 24) == 12 ? 'h:i A' : 'H:i';
@endphp

<section class="content-header">
    <h1><i class="fas fa-calendar-week"></i> @lang('clinicCore::lang.calendar')</h1>
</section>

<section class="content">
<div class="cal-layout">

    {{-- ─────────── SIDEBAR ─────────── --}}
    <div class="cal-sidebar">

        {{-- Date --}}
        <div class="sb-card">
            <div class="today-display">
                <div class="day-name">{{ now()->format('l') }}</div>
                <div class="day-num">{{ now()->format('d') }}</div>
                <div class="month-year">{{ now()->format('F Y') }}</div>
            </div>
            <div class="stats-grid" style="padding:0 12px 12px;">
                <div class="stat-box">
                    <div class="s-num" style="color:#2c3e50;">{{ $totalToday }}</div>
                    <div class="s-lbl">Today</div>
                </div>
                <div class="stat-box">
                    <div class="s-num" style="color:#f39c12;">{{ $scheduledToday }}</div>
                    <div class="s-lbl">Scheduled</div>
                </div>
                @if($waitingToday)
                <div class="stat-box" style="grid-column:span 2;">
                    <div class="s-num" style="color:#0d9488;">{{ $waitingToday }}</div>
                    <div class="s-lbl">Waiting</div>
                </div>
                @endif
                <div class="stat-box">
                    <div class="s-num" style="color:#9b59b6;">{{ $inProgToday }}</div>
                    <div class="s-lbl">In Progress</div>
                </div>
                <div class="stat-box">
                    <div class="s-num" style="color:#27ae60;">{{ $doneToday }}</div>
                    <div class="s-lbl">Completed</div>
                </div>
            </div>
        </div>

        {{-- Today's Appointments --}}
        <div class="sb-card">
            <div class="sb-card-header">
                <i class="fa fa-list-ul"></i> Today's Schedule
            </div>
            <div class="sb-card-body" style="padding:8px 12px;">
                @if($todayAppointments->isEmpty())
                    <p class="text-muted text-center" style="font-size:12px;padding:8px 0;">No appointments today.</p>
                @else
                <div class="today-list">
                    @foreach($todayAppointments as $apt)
                    <a class="today-apt" href="{{ route('clinic.appointments.show', $apt->id) }}">
                        <span class="apt-time-badge">{{ \Carbon\Carbon::parse($apt->appointment_time)->format($calTimeFormat) }}</span>
                        <span class="apt-status-dot" style="background:{{ $statusColors[$apt->status] ?? '#95a5a6' }};"></span>
                        <span class="apt-info-col">
                            <div class="pet">{{ optional($apt->pet)->patient_name ?? '—' }}</div>
                            <div class="own">{{ trim(optional($apt->owner)->name ?? '') ?: (optional($apt->owner)->supplier_business_name ?? '—') }}</div>
                        </span>
                        <span class="apt-type-chip" style="background:{{ $typeColors[$apt->type] ?? '#7f8c8d' }};">
                            {{ ucfirst($apt->type) }}
                        </span>
                    </a>
                    @endforeach
                </div>
                @endif
            </div>
        </div>

        {{-- Filters --}}
        <div class="sb-card">
            <div class="sb-card-header"><i class="fa fa-filter"></i> Filters</div>
            <div class="sb-card-body">

                {{-- Doctor --}}
                <div style="margin-bottom:12px;">
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#aaa;margin-bottom:6px;">Doctor</div>
                    <select id="filter_doctor" class="form-control input-sm">
                        <option value="">All Doctors</option>
                        @foreach($doctors as $doc)
                        <option value="{{ $doc->id }}">{{ $doc->name }}</option>
                        @endforeach
                    </select>
                    @php $coloredDoctors = $doctors->filter(fn($d) => !empty($d->color)); @endphp
                    @if($coloredDoctors->isNotEmpty())
                    <div style="margin-top:8px;display:flex;flex-direction:column;gap:3px;">
                        @foreach($coloredDoctors as $doc)
                        <div style="display:flex;align-items:center;gap:6px;font-size:11px;color:#475569;">
                            <span style="width:11px;height:11px;border-radius:3px;background:{{ $doc->color }};flex-shrink:0;"></span>
                            <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">{{ $doc->name }}</span>
                        </div>
                        @endforeach
                    </div>
                    @endif
                </div>

                {{-- Appointment Type (DB-driven from clc_appointment_types) --}}
                <div style="margin-bottom:12px;">
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#aaa;margin-bottom:6px;">Type</div>
                    <div class="type-filter-grid">
                        @if(isset($aptTypes) && $aptTypes->isNotEmpty())
                            @foreach($aptTypes as $at)
                                @php $c = $at->color ?: '#7f8c8d'; @endphp
                                <div class="type-chip"
                                     data-type-id="{{ $at->id }}"
                                     data-type-name="{{ $at->name }}"
                                     style="background:{{ $c }}22;border-color:{{ $c }};">
                                    <span class="type-chip-dot" style="background:{{ $c }};"></span>
                                    @if($at->icon)<i class="fa {{ $at->icon }}" style="color:{{ $c }};font-size:10px;"></i>@endif
                                    <span style="color:{{ $c }};">{{ $at->name }}</span>
                                </div>
                            @endforeach
                        @else
                            {{-- Fallback to enum if catalogue empty --}}
                            @foreach(['checkup'=>'Checkup','vaccination'=>'Treatment','surgery'=>'Surgery','grooming'=>'Grooming','emergency'=>'Emergency','other'=>'Other'] as $t => $tl)
                            <div class="type-chip" data-type="{{ $t }}"
                                 style="background:{{ $typeColors[$t] }}22;border-color:{{ $typeColors[$t] }};">
                                <span class="type-chip-dot" style="background:{{ $typeColors[$t] }};"></span>
                                <span style="color:{{ $typeColors[$t] }};">{{ $tl }}</span>
                            </div>
                            @endforeach
                        @endif
                    </div>
                    <div style="margin-top:6px;">
                        <a href="#" id="btn_type_all" style="font-size:11px;color:#aaa;">Show All</a>
                        &nbsp;·&nbsp;
                        <a href="#" id="btn_type_none" style="font-size:11px;color:#aaa;">Clear All</a>
                    </div>
                </div>

                {{-- Status Legend --}}
                <div>
                    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;color:#aaa;margin-bottom:6px;">Status Colors</div>
                    @foreach(['pending'=>['Scheduled','#f39c12'],'waiting'=>['Waiting','#0d9488'],'confirmed'=>['Confirmed','#3498db'],'in_progress'=>['In Consultation','#9b59b6'],'completed'=>['Completed','#27ae60'],'cancelled'=>['Cancelled','#e74c3c']] as $s => [$sl, $sc])
                    <div class="legend-row">
                        <span class="legend-dot" style="background:{{ $sc }};"></span>
                        {{ $sl }}
                    </div>
                    @endforeach
                </div>

            </div>
        </div>

        @can('clinic.manage_appointments')
        <a href="{{ route('clinic.appointments.index') }}" class="btn btn-default btn-sm btn-block">
            <i class="fa fa-list"></i> List View
        </a>
        <button class="btn btn-primary btn-sm btn-block" style="margin-top:6px;"
                data-toggle="modal" data-target="#quickCreateModal">
            <i class="fa fa-plus"></i> New Appointment
        </button>
        @endcan

    </div>{{-- end sidebar --}}

    {{-- ─────────── CALENDAR ─────────── --}}
    <div class="cal-main">
        <div id="clc_calendar"></div>
    </div>

</div>
</section>

{{-- ═══════════ QUICK VIEW MODAL ═══════════ --}}
<div class="modal fade" id="quickViewModal" tabindex="-1">
    <div class="modal-dialog" style="max-width:560px;">
        <div class="modal-content" style="border:none;border-radius:8px;overflow:hidden;">
            <div class="qv-header" id="qv_header">
                <div class="qv-type" id="qv_type_label"></div>
                <div class="qv-pet" id="qv_pet_name"></div>
                <div class="qv-owner" id="qv_owner_line"></div>
            </div>
            <div class="modal-body" style="padding:16px 20px;">
                <div class="qv-meta-grid">
                    <div class="qv-meta-item">
                        <div class="qv-label"><i class="fa fa-calendar"></i> Date & Time</div>
                        <div class="qv-value" id="qv_datetime"></div>
                    </div>
                    <div class="qv-meta-item">
                        <div class="qv-label"><i class="fa fa-clock"></i> Duration</div>
                        <div class="qv-value" id="qv_duration"></div>
                    </div>
                    <div class="qv-meta-item">
                        <div class="qv-label"><i class="fa fa-user-md"></i> Doctor</div>
                        <div class="qv-value" id="qv_doctor"></div>
                    </div>
                    <div class="qv-meta-item">
                        <div class="qv-label"><i class="fa fa-hospital"></i> Department</div>
                        <div class="qv-value" id="qv_dept"></div>
                    </div>
                </div>
                <div style="margin-bottom:10px;">
                    <div class="qv-label" style="font-size:10px;text-transform:uppercase;letter-spacing:.5px;color:#aaa;margin-bottom:5px;">Status</div>
                    <div id="qv_status_pill" class="status-pill"></div>
                </div>
                <div id="qv_reason_row" style="display:none;">
                    <div class="qv-label" style="font-size:10px;text-transform:uppercase;letter-spacing:.5px;color:#aaa;margin-bottom:4px;">Reason</div>
                    <div id="qv_reason" style="font-size:13px;color:#555;background:#f8f9fa;border-radius:5px;padding:8px 10px;"></div>
                </div>
            </div>
            <div class="modal-footer" style="border-top:1px solid #f0f0f0;padding:10px 16px;">
                <button class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
                <a id="qv_btn_edit" href="#" class="btn btn-default btn-sm">
                    <i class="fa fa-edit"></i> Edit
                </a>
                <a id="qv_btn_view" href="#" class="btn btn-primary btn-sm">
                    <i class="fa fa-eye"></i> View Full Page
                </a>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════ QUICK CREATE MODAL ═══════════ --}}
<div class="modal fade" id="quickCreateModal" tabindex="-1">
    <div class="modal-dialog" style="width:860px;max-width:97vw;">
        <div class="modal-content" style="border:none;border-radius:10px;overflow:hidden;">
            <div class="modal-header" style="background:linear-gradient(135deg,#2c3e50,#34495e);color:#fff;padding:14px 20px;border-radius:0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;opacity:.8;font-size:15px;margin-top:-2px;">&times;</button>
                <h4 class="modal-title" style="font-size:15px;font-weight:700;">
                    <i class="fa fa-calendar-plus"></i> New Appointment
                </h4>
            </div>

            <div class="modal-body" style="padding:16px 20px 4px;background:#f8fafc;max-height:82vh;overflow-y:auto;">

                {{-- ① Patient ──────────────────────────────────────────── --}}
                <div class="qc-section">
                    <div class="qc-section-title"><i class="fa fa-user"></i> Patient</div>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="control-label" style="font-size:11px;font-weight:700;color:#475569;">Patient <span class="text-danger">*</span></label>
                            <select id="qc_owner" class="form-control" style="width:100%;"></select>
                        </div>
                        <div class="col-md-6">
                            <label class="control-label" style="font-size:11px;font-weight:700;color:#475569;">Patient <span class="text-danger">*</span></label>
                            <select id="qc_pet" class="form-control" style="width:100%;">
                                <option value="">— Select Contact First —</option>
                            </select>
                        </div>
                    </div>
                </div>

                {{-- ② Scheduling ─────────────────────────────────────── --}}
                <div class="qc-section">
                    <div class="qc-section-title"><i class="fa fa-clock"></i> Scheduling</div>

                    {{-- Step 1: Date --}}
                    <div class="row" style="margin-bottom:12px;">
                        <div class="col-md-5">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">
                                <span class="qc-step-badge">1</span> Date <span class="text-danger">*</span>
                            </label>
                            <input type="text" id="qc_date_display" class="form-control input-sm" autocomplete="off" placeholder="Select date">
                            <input type="hidden" id="qc_date_iso">
                        </div>
                    </div>

                    {{-- Step 2: Location + Department --}}
                    <div class="row" style="margin-bottom:12px;">
                        <div class="col-md-6">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">
                                <span class="qc-step-badge">2</span> <i class="fa fa-map-marker"></i> Clinic Location
                            </label>
                            <select id="qc_location" class="form-control input-sm" style="width:100%;">
                                <option value="">— Select date first —</option>
                            </select>
                            <div class="qc-cascade-hint" id="qc_loc_hint">Select a date to load available locations.</div>
                        </div>
                        <div class="col-md-6">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">
                                <i class="fa fa-hospital"></i> Department
                            </label>
                            <select id="qc_department" class="form-control input-sm" style="width:100%;">
                                <option value="">— Select location first —</option>
                            </select>
                            <div class="qc-cascade-hint" id="qc_dept_hint">Select a location to load departments.</div>
                        </div>
                    </div>

                    {{-- Step 3: Doctor --}}
                    <div class="row" style="margin-bottom:12px;">
                        <div class="col-md-12">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">
                                <span class="qc-step-badge">3</span> <i class="fa fa-user-md"></i> Doctor
                            </label>
                            <select id="qc_doctor" class="form-control input-sm" style="width:100%;">
                                <option value="">— Select department first —</option>
                            </select>
                            <div class="qc-cascade-hint" id="qc_doctor_hint">Select a department to load available doctors.</div>
                        </div>
                    </div>

                    {{-- Step 4: Slot Picker --}}
                    <div id="qc_slot_picker_section" style="display:none;">
                        <label style="font-size:11px;font-weight:700;color:#475569;display:flex;align-items:center;margin-bottom:4px;">
                            <span class="qc-step-badge">4</span> <i class="fa fa-clock" style="margin-right:4px;"></i> Available Time Slots
                        </label>
                        <p style="font-size:11px;color:#64748b;margin:0 0 4px;">Click a slot to select. Click consecutive slots to extend duration.</p>
                        <div class="qc-slot-grid" id="qc_slot_grid"></div>
                        <div class="qc-overlap-alert" id="qc_overlap_alert">
                            <i class="fa fa-exclamation-triangle"></i>
                            Selected slot(s) overlap an existing appointment for this doctor.
                        </div>
                        <div class="qc-selection-summary" id="qc_selection_summary">
                            <i class="fa fa-calendar-check text-primary"></i>
                            <span id="qc_selection_detail"></span>
                        </div>
                    </div>

                    {{-- Manual time fallback (shown when no schedule found) --}}
                    <div id="qc_manual_time_group" style="display:none;margin-top:10px;">
                        <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">
                            <span class="qc-step-badge">4</span> Time <span class="text-danger">*</span>
                        </label>
                        <div style="display:flex;align-items:center;gap:10px;">
                            <input type="time" id="qc_time_manual" class="form-control input-sm" style="width:160px;" value="09:00">
                            <span class="text-muted" style="font-size:11px;">No schedule found — enter manually.</span>
                        </div>
                    </div>

                    {{-- Initial manual time (shown before doctor picked) --}}
                    <div id="qc_pre_doctor_time" style="margin-top:10px;">
                        <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">Time <span class="text-danger">*</span></label>
                        <input type="time" id="qc_time_pre" class="form-control input-sm" style="width:160px;" value="09:00">
                        <div class="qc-cascade-hint">Will be replaced by slot picker once a doctor is selected.</div>
                    </div>

                    {{-- Hidden inputs --}}
                    <input type="hidden" id="qc_time">
                    <input type="hidden" id="qc_schedule_id">
                    <input type="hidden" id="qc_duration" value="30">
                </div>

                {{-- ③ Visit Details ─────────────────────────────────── --}}
                <div class="qc-section" style="margin-bottom:4px;">
                    <div class="qc-section-title"><i class="fa fa-stethoscope"></i> Visit Details</div>

                    <div class="row" style="margin-bottom:12px;">
                        <div class="col-md-6">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">Type <span class="text-danger">*</span></label>
                            @if(isset($aptTypes) && $aptTypes->isNotEmpty())
                                <select id="qc_type_ids" class="form-control" style="width:100%;" multiple>
                                    @foreach($aptTypes as $at)
                                    <option value="{{ $at->id }}">{{ $at->name }}</option>
                                    @endforeach
                                </select>
                                <input type="hidden" id="qc_type" value="other">
                            @else
                                <select id="qc_type" class="form-control input-sm">
                                    @foreach(['checkup'=>'Checkup','vaccination'=>'Treatment','surgery'=>'Surgery','grooming'=>'Grooming','emergency'=>'Emergency','other'=>'Other'] as $t => $tl)
                                    <option value="{{ $t }}">{{ $tl }}</option>
                                    @endforeach
                                </select>
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">Reason / Chief Complaint</label>
                            @if(isset($aptReasons) && $aptReasons->isNotEmpty())
                                <select id="qc_reason_ids" class="form-control" style="width:100%;" multiple>
                                    @foreach($aptReasons as $ar)
                                    <option value="{{ $ar->id }}">{{ $ar->name }}</option>
                                    @endforeach
                                </select>
                            @else
                                <input type="text" id="qc_reason" class="form-control input-sm" placeholder="e.g. Annual checkup, limping…">
                            @endif
                        </div>
                    </div>

                    <div class="form-group" style="margin-bottom:0;">
                        <label style="font-size:11px;font-weight:700;color:#475569;display:block;margin-bottom:4px;">Notes</label>
                        <textarea id="qc_notes" class="form-control input-sm" rows="2" placeholder="Additional notes…" style="resize:vertical;"></textarea>
                    </div>
                </div>

            </div>{{-- /modal-body --}}

            <div class="modal-footer" style="padding:10px 20px;background:#fff;border-top:1px solid #e8ecf0;display:flex;align-items:center;justify-content:space-between;">
                <a id="qc_full_form_link" href="{{ route('clinic.appointments.create') }}"
                   style="font-size:12px;color:#64748b;text-decoration:none;">
                    <i class="fa fa-external-link-alt"></i> Open Full Form
                </a>
                <div>
                    <button class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
                    <button class="btn btn-primary btn-sm" id="btn_quick_create" style="margin-left:6px;">
                        <i class="fa fa-save"></i> Create Appointment
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.js"></script>
<script>
var eventsUrl       = '{{ route('clinic.appointments.events') }}';
var storeUrl        = '{{ route('clinic.appointments.store') }}';
var petsByOwner     = '{{ url('clinic/patients/by-owner') }}';
var ownerSearch     = '{{ route('clinic.patient-contacts.search') }}';
var csrfToken       = '{{ csrf_token() }}';
var urlQcLocations  = '{{ route('clinic.appointments.locations-by-date') }}';
var urlQcDepts      = '{{ route('clinic.appointments.depts-by-location') }}';
var urlQcDoctors    = '{{ route('clinic.appointments.doctors-by-dept') }}';
var urlQcSlots      = '{{ route('clinic.appointments.slots') }}';
var qcAllowOverlap  = {{ ($allowOverlap ?? true) ? 'true' : 'false' }};

var filterDoctorId = '';
var filterTypeIds  = '';      // CSV of DB appointment-type IDs (preferred path)
var filterType     = '';       // CSV of legacy enum values (fallback path)
var activeTypeIds  = {};       // {id: bool} for DB-driven chips
var activeTypes    = {};       // {enum: bool} for fallback chips

// Init DB-driven type chips (active by default)
@if(isset($aptTypes) && $aptTypes->isNotEmpty())
@foreach($aptTypes as $at)
activeTypeIds[{{ $at->id }}] = true;
@endforeach
@else
// Fallback: enum types
@foreach(array_keys(['checkup'=>1,'vaccination'=>1,'surgery'=>1,'grooming'=>1,'emergency'=>1,'other'=>1]) as $t)
activeTypes['{{ $t }}'] = true;
@endforeach
@endif

// Legacy enum colors / icons / labels (still used for old appointments without type_ids)
var typeColors = {
    checkup:'#2980b9', vaccination:'#27ae60', surgery:'#c0392b',
    grooming:'#8e44ad', emergency:'#e67e22', other:'#7f8c8d'
};
var typeLabels = {
    checkup:'Checkup', vaccination:'Treatment', surgery:'Surgery',
    grooming:'Grooming', emergency:'Emergency', other:'Other'
};
var typeIcons  = {
    checkup:'fa-stethoscope', vaccination:'fa-syringe', surgery:'fa-procedures',
    grooming:'fa-cut', emergency:'fa-ambulance', other:'fa-notes-medical'
};

// ── FullCalendar ───────────────────────────────────────
document.addEventListener('DOMContentLoaded', function () {

    var calEl = document.getElementById('clc_calendar');
    var drmIsMobile = window.matchMedia('(max-width: 768px)').matches;
    var calendar = new FullCalendar.Calendar(calEl, {
        initialView: drmIsMobile ? 'listWeek' : 'timeGridWeek',
        height: 'auto',
        slotMinTime: '07:00:00',
        slotMaxTime: '21:00:00',
        allDaySlot: false,
        nowIndicator: true,
        selectable: true,
        selectMirror: true,
        businessHours: { daysOfWeek:[0,1,2,3,4,5,6], startTime:'08:00', endTime:'18:00' },
        headerToolbar: drmIsMobile
            ? { left:'prev,next', center:'title', right:'listWeek,timeGridDay' }
            : { left:'prev,next today', center:'title', right:'dayGridMonth,timeGridWeek,timeGridDay,listWeek' },
        buttonText: {
            today:        'Today',
            month:        'Month',
            week:         'Week',
            day:          'Day',
            list:         'List',
        },
        events: {
            url: eventsUrl,
            method: 'GET',
            extraParams: function () {
                return {
                    doctor_id: filterDoctorId,
                    type_ids:  filterTypeIds,   // DB-driven path
                    type:      filterType        // enum fallback path
                };
            },
            failure: function () { toastr.error('Failed to load appointments'); }
        },
        eventDidMount: function (info) {
            // Layered styling: type color drives the left border, doctor color drives the background.
            var p = info.event.extendedProps;
            var typeCol = (p.type_color) || (typeColors[p.type] || '#7f8c8d');
            // Stripe the left edge with type color so users can see type even when doctor color owns the bg
            info.el.style.borderLeft = '4px solid ' + typeCol;
            // Soft outer halo by status (subtle shadow)
            info.el.style.boxShadow = 'inset 0 0 0 1px rgba(255,255,255,.25), 0 0 0 1.5px ' + (p.status_color || 'transparent') + '55';
        },
        eventContent: function (arg) {
            var p = arg.event.extendedProps;
            // Pick icon: DB icon first, then enum icon, then default
            var icon = p.type_icon || typeIcons[p.type] || 'fa-calendar';

            // Status dot (color from p.status_color)
            var dot = '<span class="ev-status-dot" style="background:' + (p.status_color || '#94a3b8') + ';" title="' + (p.status || '') + '"></span>';
            // Optional doctor badge (small filled chip on right) when doctor has a color
            var docBadge = '';
            if (p.doctor_color) {
                docBadge = '<span class="ev-doc-badge" style="background:' + p.doctor_color + ';" title="' + (p.doctor_name || '') + '">'
                         + '<i class="fa fa-user-md"></i></span>';
            }
            // Stacked type pills (one per type) for multi-type appointments
            var typeChips = '';
            if (Array.isArray(p.type_names) && p.type_names.length) {
                typeChips = p.type_names.slice(0, 2).map(function (name, i) {
                    var c = (p.type_colors && p.type_colors[i]) || '#7f8c8d';
                    var ic = (p.type_icons && p.type_icons[i]) || 'fa-calendar';
                    return '<span class="ev-type-chip" style="background:' + c + 'cc;" title="' + name + '">'
                         + '<i class="fa ' + ic + '"></i></span>';
                }).join('');
                if (p.type_names.length > 2) {
                    typeChips += '<span class="ev-type-chip ev-type-more">+' + (p.type_names.length - 2) + '</span>';
                }
            }

            var html = '<div class="fc-event-custom">'
                     + '<div class="ev-title">' + dot
                     + '<i class="fas ' + icon + ' ev-type-icon"></i>'
                     + '<span class="ev-pet">' + (p.pet_name || '') + '</span>'
                     + docBadge
                     + '</div>';
            if (arg.event.display !== 'list-item') {
                html += '<div class="ev-sub">'
                     + '<span>' + (p.owner_name || '') + '</span>'
                     + (typeChips ? '<span class="ev-chips">' + typeChips + '</span>' : '')
                     + '</div>';
            }
            html += '</div>';
            return { html: html };
        },
        eventClick: function (info) {
            info.jsEvent.preventDefault();
            openQuickView(info.event);
        },
        select: function (selInfo) {
            openQuickCreate(selInfo.startStr, selInfo.endStr);
        },
        dateClick: function (info) {
            openQuickCreate(info.dateStr, null);
        },
        eventTimeFormat: { hour: '2-digit', minute: '2-digit', meridiem: false }
    });

    calendar.render();

    // ── Doctor Filter ────────────────────────────────
    $('#filter_doctor').on('change', function () {
        filterDoctorId = $(this).val();
        calendar.refetchEvents();
    });

    // ── Type Filter Chips (DB-driven or enum fallback) ─────────
    $('.type-chip').on('click', function () {
        var id = $(this).data('type-id');
        if (id) {
            activeTypeIds[id] = !activeTypeIds[id];
            $(this).toggleClass('inactive', !activeTypeIds[id]);
        } else {
            var t = $(this).data('type');
            activeTypes[t] = !activeTypes[t];
            $(this).toggleClass('inactive', !activeTypes[t]);
        }
        applyTypeFilter();
        calendar.refetchEvents();
    });

    $('#btn_type_all').on('click', function (e) {
        e.preventDefault();
        $('.type-chip').removeClass('inactive');
        Object.keys(activeTypeIds).forEach(function(k){ activeTypeIds[k] = true; });
        Object.keys(activeTypes).forEach(function(t){ activeTypes[t] = true; });
        applyTypeFilter();
        calendar.refetchEvents();
    });

    $('#btn_type_none').on('click', function (e) {
        e.preventDefault();
        $('.type-chip').addClass('inactive');
        Object.keys(activeTypeIds).forEach(function(k){ activeTypeIds[k] = false; });
        Object.keys(activeTypes).forEach(function(t){ activeTypes[t] = false; });
        applyTypeFilter();
        calendar.refetchEvents();
    });

    function applyTypeFilter() {
        // DB-driven path
        var idKeys = Object.keys(activeTypeIds);
        if (idKeys.length) {
            var activeIds = idKeys.filter(function(k){ return activeTypeIds[k]; });
            if (activeIds.length === 0) {
                filterTypeIds = 'none';      // sentinel → backend returns zero events
            } else if (activeIds.length === idKeys.length) {
                filterTypeIds = '';           // empty → no filter (show all)
            } else {
                filterTypeIds = activeIds.join(',');
            }
            filterType = '';
            return;
        }
        // Enum fallback
        var enumKeys = Object.keys(activeTypes);
        var activeEnum = enumKeys.filter(function(t){ return activeTypes[t]; });
        if (activeEnum.length === 0) {
            filterType = 'none';
        } else if (activeEnum.length === enumKeys.length) {
            filterType = '';
        } else {
            filterType = activeEnum.join(',');
        }
        filterTypeIds = '';
    }

    // ── Quick View ───────────────────────────────────
    window.openQuickView = function (event) {
        var p = event.extendedProps;
        // Header background: doctor color if set, else primary type color, else enum fallback
        var color = p.doctor_color || p.type_color || typeColors[p.type] || '#2c3e50';
        // Type label: DB type names list joined, else enum label
        var typeLabel = (p.type_names && p.type_names.length)
            ? p.type_names.join(' · ')
            : (typeLabels[p.type] || p.type || '');
        var typeIcon = p.type_icon || typeIcons[p.type] || 'fa-calendar';

        $('#qv_header').css('background', 'linear-gradient(135deg, ' + color + ' 0%, ' + color + 'cc 100%)');
        $('#qv_type_label').html('<i class="fas ' + typeIcon + '"></i> ' + typeLabel);
        $('#qv_pet_name').text(p.pet_name || '—');
        $('#qv_owner_line').html('<i class="fa fa-user"></i> ' + (p.owner_name||'—') + (p.owner_mobile ? '  · ' + p.owner_mobile : ''));

        var start = event.start;
        var dateStr = start ? start.toLocaleDateString('en-GB', {day:'2-digit',month:'short',year:'numeric'}) : '—';
        var timeStr = start ? start.toLocaleTimeString('en-GB', {hour:'2-digit',minute:'2-digit'}) : '';
        $('#qv_datetime').text(dateStr + (timeStr ? ' @ ' + timeStr : ''));
        $('#qv_duration').text((p.duration || 30) + ' min');
        $('#qv_doctor').text(p.doctor_name || '—');
        $('#qv_dept').text(p.department || '—');

        var statusLabels = {pending:'Scheduled',confirmed:'Confirmed',in_progress:'In Consultation',completed:'Completed',cancelled:'Cancelled',no_show:'No Show'};
        $('#qv_status_pill').css('background', p.status_color).text(statusLabels[p.status] || p.status);

        if (p.reason) {
            $('#qv_reason').text(p.reason);
            $('#qv_reason_row').show();
        } else {
            $('#qv_reason_row').hide();
        }

        $('#qv_btn_view').attr('href', p.url);
        $('#qv_btn_edit').attr('href', p.edit_url);
        $('#quickViewModal').modal('show');
    };

    // ══════════════════════════════════════════════════════════
    //  QUICK CREATE — cascade & slot logic
    // ══════════════════════════════════════════════════════════

    var qcSelectedSlots = [];

    // ── Helpers ──────────────────────────────────────────────
    function qcSetDropdown(sel, label) {
        $(sel).empty().append('<option value="">' + label + '</option>');
        if ($(sel).hasClass('select2-hidden-accessible')) $(sel).trigger('change.select2');
    }

    function qcResetSlots() {
        qcSelectedSlots = [];
        $('#qc_slot_picker_section').hide();
        $('#qc_manual_time_group').hide();
        $('#qc_overlap_alert').hide();
        $('#qc_selection_summary').hide();
        $('#qc_slot_grid').html('');
        $('#qc_time').val('');
        $('#qc_schedule_id').val('');
        $('#qc_duration').val(30);
    }

    function qcSlotFrom($btn) {
        return {
            start:       $btn.data('start'),
            end:         $btn.data('end'),
            duration:    parseInt($btn.data('duration')) || 30,
            schedule_id: $btn.data('schedule') || '',
            booked:      $btn.data('booked') == '1',
        };
    }

    function qcApplySlotSelection() {
        $('#qc_slot_grid .qc-slot-btn').removeClass('selected');
        if (!qcSelectedSlots.length) {
            $('#qc_time').val('');
            $('#qc_schedule_id').val('');
            $('#qc_duration').val(30);
            $('#qc_overlap_alert').hide();
            $('#qc_selection_summary').hide();
            return;
        }
        var first     = qcSelectedSlots[0].start;
        var last      = qcSelectedSlots[qcSelectedSlots.length - 1].end;
        var slotDur   = qcSelectedSlots[0].duration;
        var totalMins = qcSelectedSlots.length * slotDur;
        var anyBooked = qcSelectedSlots.some(function(s){ return s.booked; });

        $('#qc_slot_grid .qc-slot-btn').each(function() {
            var s = $(this).data('start'), e = $(this).data('end');
            if (s >= first && e <= last) $(this).addClass('selected');
        });

        $('#qc_time').val(first);
        $('#qc_schedule_id').val(qcSelectedSlots[0].schedule_id || '');
        $('#qc_duration').val(totalMins);
        if (anyBooked) $('#qc_overlap_alert').show(); else $('#qc_overlap_alert').hide();
        $('#qc_selection_detail').html(
            '<strong>' + first + ' – ' + last + '</strong> &nbsp;(' + totalMins + ' min)' +
            (anyBooked ? ' &nbsp;<span class="label label-warning">Overlap</span>' : '')
        );
        $('#qc_selection_summary').show();
    }

    // ── Slot click ────────────────────────────────────────────
    $(document).on('click', '#qc_slot_grid .qc-slot-btn:not([disabled])', function() {
        var $btn = $(this), clickedStart = $btn.data('start');
        if (!qcSelectedSlots.length) {
            qcSelectedSlots = [qcSlotFrom($btn)];
        } else {
            var last = qcSelectedSlots[qcSelectedSlots.length - 1];
            if (last.end === clickedStart) {
                qcSelectedSlots.push(qcSlotFrom($btn));
            } else if (qcSelectedSlots[0].start === clickedStart && qcSelectedSlots.length === 1) {
                qcSelectedSlots = [];
            } else {
                qcSelectedSlots = [qcSlotFrom($btn)];
            }
        }
        qcApplySlotSelection();
    });

    // ── Date → load locations ─────────────────────────────────
    function qcOnDateChange(iso) {
        qcResetSlots();
        $('#qc_pre_doctor_time').show();
        qcSetDropdown('#qc_department', '— Select location first —');
        qcSetDropdown('#qc_doctor',     '— Select department first —');
        $('#qc_dept_hint').text('Select a location to load departments.');
        $('#qc_doctor_hint').text('Select a department to load available doctors.');
        if (!iso) { qcSetDropdown('#qc_location', '— Select date first —'); return; }
        $('#qc_loc_hint').text('Loading…');
        qcSetDropdown('#qc_location', '— loading… —');
        $.getJSON(urlQcLocations, { date: iso }, function(locs) {
            $('#qc_location').empty().append('<option value="">— Select Location —</option>');
            locs.forEach(function(loc) {
                var avail = loc.has_available !== false;
                $('<option>').val(loc.id).text(loc.name + (avail ? '' : ' (no slots)'))
                    .prop('disabled', !avail).appendTo('#qc_location');
            });
            if ($('#qc_location').hasClass('select2-hidden-accessible')) $('#qc_location').trigger('change.select2');
            $('#qc_loc_hint').text(locs.some(function(l){ return l.has_available; }) ? '' : 'No locations have available slots on this date.');
        }).fail(function() { $('#qc_loc_hint').text('Failed to load locations.'); });
    }

    $('#qc_location').on('change', function() {
        qcResetSlots();
        var locId = $(this).val(), date = $('#qc_date_iso').val();
        qcSetDropdown('#qc_department', '— loading… —');
        qcSetDropdown('#qc_doctor', '— Select department first —');
        $('#qc_dept_hint, #qc_doctor_hint').text('');
        if (!locId) { qcSetDropdown('#qc_department', '— Select location first —'); return; }
        $.getJSON(urlQcDepts, { location_id: locId, date: date }, function(depts) {
            $('#qc_department').empty().append('<option value="">— Select Department —</option>');
            depts.forEach(function(dept) {
                var avail = dept.has_available !== false;
                $('<option>').val(dept.id).text(dept.name + (avail ? '' : ' (no slots)'))
                    .prop('disabled', !avail).appendTo('#qc_department');
            });
            if ($('#qc_department').hasClass('select2-hidden-accessible')) $('#qc_department').trigger('change.select2');
            $('#qc_dept_hint').text(depts.some(function(d){ return d.has_available; }) ? '' : 'No departments have available slots.');
        });
    });

    $('#qc_department').on('change', function() {
        qcResetSlots();
        var deptId = $(this).val(), locId = $('#qc_location').val(), date = $('#qc_date_iso').val();
        qcSetDropdown('#qc_doctor', '— loading… —');
        $('#qc_doctor_hint').text('');
        if (!deptId) { qcSetDropdown('#qc_doctor', '— Select department first —'); return; }
        $.getJSON(urlQcDoctors, { department_id: deptId, location_id: locId, date: date }, function(docs) {
            $('#qc_doctor').empty().append('<option value="">— Select Doctor —</option>');
            docs.forEach(function(doc) {
                var avail = doc.has_available !== false;
                $('<option>').val(doc.id).text(doc.text + (avail ? '' : ' (no slots)'))
                    .prop('disabled', !avail).appendTo('#qc_doctor');
            });
            if ($('#qc_doctor').hasClass('select2-hidden-accessible')) $('#qc_doctor').trigger('change.select2');
            $('#qc_doctor_hint').text(docs.some(function(d){ return d.has_available; }) ? '' : 'No doctors have available slots.');
        });
    });

    $('#qc_doctor').on('change', function() {
        qcResetSlots();
        var docId = $(this).val(), deptId = $('#qc_department').val(), date = $('#qc_date_iso').val();
        if (!docId) return;
        $('#qc_pre_doctor_time').hide();
        $.getJSON(urlQcSlots, { doctor_id: docId, department_id: deptId, date: date }, function(slots) {
            if (!slots || !slots.length) { $('#qc_manual_time_group').show(); return; }
            var html = '';
            slots.forEach(function(s) {
                var cls = 'qc-slot-btn';
                if (!s.available) cls += ' unavailable';
                else if (s.booked) cls += ' booked-warn';
                html += '<button type="button" class="' + cls + '"'
                    + ' data-start="' + s.start + '" data-end="' + s.end + '"'
                    + ' data-duration="' + s.duration + '"'
                    + ' data-booked="' + (s.booked ? '1' : '0') + '"'
                    + ' data-schedule="' + (s.schedule_id || '') + '"'
                    + (s.available ? '' : ' disabled') + '>'
                    + s.start + ' – ' + s.end
                    + (s.booked && s.available ? ' <i class="fa fa-exclamation-circle" style="font-size:9px;"></i>' : '')
                    + '</button>';
            });
            $('#qc_slot_grid').html(html);
            $('#qc_slot_picker_section').show();
        }).fail(function() { $('#qc_manual_time_group').show(); });
    });

    $('#qc_time_manual, #qc_time_pre').on('input change', function() {
        if (!$('#qc_time').val()) $('#qc_time').val($(this).val());
    });

    // ── openQuickCreate ────────────────────────────────────────
    window.openQuickCreate = function (startStr, endStr) {
        var dateStr = startStr.substr(0, 10);
        var timeStr = startStr.length > 10 ? startStr.substr(11, 5) : '09:00';

        qcResetSlots();
        $('#qc_pre_doctor_time').show();
        $('#qc_owner').val(null).trigger('change');
        $('#qc_pet').empty().append('<option value="">— Select Contact First —</option>');
        if ($('#qc_pet').hasClass('select2-hidden-accessible')) $('#qc_pet').trigger('change.select2');
        qcSetDropdown('#qc_location',   '— Select date first —');
        qcSetDropdown('#qc_department', '— Select location first —');
        qcSetDropdown('#qc_doctor',     '— Select department first —');
        $('#qc_loc_hint').text('Select a date to load available locations.');
        $('#qc_dept_hint').text('Select a location to load departments.');
        $('#qc_doctor_hint').text('Select a department to load available doctors.');
        if ($('#qc_type_ids').length) $('#qc_type_ids').val(null).trigger('change');
        if ($('#qc_reason_ids').length) $('#qc_reason_ids').val(null).trigger('change');
        if ($('#qc_reason').length) $('#qc_reason').val('');
        $('#qc_notes').val('');
        $('#qc_time_pre').val(timeStr);
        $('#qc_time_manual').val(timeStr);
        $('#qc_date_iso').val(dateStr);

        var base = '{{ route('clinic.appointments.create') }}';
        $('#qc_full_form_link').attr('href', base + '?date=' + dateStr);

        $('#quickCreateModal').modal('show');
    };

    // ── Modal shown: init pickers & Select2 ───────────────────
    $('#quickCreateModal').on('shown.bs.modal', function () {
        $('#qc_date_display').datepicker('destroy').datepicker({
            todayHighlight: true, autoclose: true, format: datepicker_date_format
        }).on('changeDate', function(e) {
            if (e.dates.length) {
                var d = e.dates[0];
                var iso = d.getFullYear() + '-' +
                    String(d.getMonth()+1).padStart(2,'0') + '-' +
                    String(d.getDate()).padStart(2,'0');
                $('#qc_date_iso').val(iso);
                qcOnDateChange(iso);
            }
        });

        var existingIso = $('#qc_date_iso').val();
        if (existingIso) {
            var p = existingIso.split('-');
            $('#qc_date_display').datepicker('setDate', new Date(+p[0], +p[1]-1, +p[2]));
            qcOnDateChange(existingIso);
        }

        if (!$('#qc_owner').hasClass('select2-hidden-accessible')) {
            $('#qc_owner').select2({
                width: '100%', minimumInputLength: 1,
                dropdownParent: $('#quickCreateModal'),
                ajax: {
                    url: ownerSearch, dataType: 'json', delay: 300,
                    data: function(p) { return { q: p.term }; },
                    processResults: function(d) { return { results: d }; }
                },
                placeholder: 'Search contact by name or phone…'
            }).on('select2:select', function(e) {
                var contactId = e.params.data.id;
                $('#qc_pet').empty().append('<option value="">Loading…</option>');
                $.get(petsByOwner + '/' + contactId, function(data) {
                    $('#qc_pet').empty().append('<option value="">— Select Patient —</option>');
                    $.each(data, function(i, patient) {
                        $('#qc_pet').append('<option value="'+pet.id+'">'+pet.text+'</option>');
                    });
                    if ($('#qc_pet').hasClass('select2-hidden-accessible')) $('#qc_pet').trigger('change.select2');
                });
            });
        }

        ['#qc_pet','#qc_location','#qc_department','#qc_doctor'].forEach(function(sel) {
            if (!$(sel).hasClass('select2-hidden-accessible'))
                $(sel).select2({ width: '100%', dropdownParent: $('#quickCreateModal') });
        });

        if ($('#qc_type_ids').length && !$('#qc_type_ids').hasClass('select2-hidden-accessible'))
            $('#qc_type_ids').select2({ width: '100%', placeholder: '— Select type(s) —', dropdownParent: $('#quickCreateModal') });

        if ($('#qc_reason_ids').length && !$('#qc_reason_ids').hasClass('select2-hidden-accessible'))
            $('#qc_reason_ids').select2({ width: '100%', placeholder: '— Select reason(s) —', dropdownParent: $('#quickCreateModal') });
    });

    // ── Submit Quick Create ────────────────────────────────────
    $('#btn_quick_create').on('click', function () {
        var contactId = $('#qc_owner').val();
        var patientId     = $('#qc_pet').val();
        var dateIso   = $('#qc_date_iso').val();
        var time      = $('#qc_time').val() || $('#qc_time_manual').val() || $('#qc_time_pre').val();

        if (!contactId) { toastr.warning('Please select a Patient.'); return; }
        if (!patientId)     { toastr.warning('Please select a Patient.'); return; }
        if (!dateIso)   { toastr.warning('Please select a Date.'); return; }
        if (!time)      { toastr.warning('Please select or enter a Time.'); return; }

        var postData = {
            _token:           csrfToken,
            contact_id:       contactId,
            patient_id:           patientId,
            appointment_date: dateIso,
            appointment_time: time.length === 5 ? time + ':00' : time,
            duration_minutes: $('#qc_duration').val() || 30,
            department_id:    $('#qc_department').val() || '',
            doctor_id:        $('#qc_doctor').val() || '',
            notes:            $('#qc_notes').val(),
        };

        var locId = $('#qc_location').val();
        if (locId) postData.location_id = locId;
        var schId = $('#qc_schedule_id').val();
        if (schId) postData.schedule_id = schId;

        if ($('#qc_type_ids').length) {
            var tids = $('#qc_type_ids').val();
            if (tids && tids.length) postData['type_ids[]'] = tids;
            postData.type = 'other';
        } else {
            postData.type = ($('#qc_type').val() || 'checkup');
        }

        if ($('#qc_reason_ids').length) {
            var rids = $('#qc_reason_ids').val();
            if (rids && rids.length) postData['reason_ids[]'] = rids;
        } else if ($('#qc_reason').length) {
            postData.reason = $('#qc_reason').val();
        }

        var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Creating…');

        $.ajax({
            url: storeUrl,
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            data: postData,
            success: function (res) {
                if (res.success) {
                    $('#quickCreateModal').modal('hide');
                    toastr.success(res.msg || 'Appointment created!');
                    calendar.refetchEvents();
                    if (dateIso === new Date().toISOString().substr(0,10)) {
                        setTimeout(function(){ location.reload(); }, 1200);
                    }
                }
            },
            error: function (xhr) {
                var msg = (xhr.responseJSON && xhr.responseJSON.message) || 'Failed to create appointment.';
                toastr.error(msg);
            },
            complete: function () {
                $btn.prop('disabled', false).html('<i class="fa fa-save"></i> Create Appointment');
            }
        });
    });

});
</script>
@endsection
