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

@section('css')
<style>
/* ── Page Header ─────────────────────────────────── */
.apt-page-header {
    display:flex; align-items:center; justify-content:space-between;
    margin-bottom:18px; flex-wrap:wrap; gap:10px;
}
.apt-page-title { font-size:22px; font-weight:800; color:#1e293b; display:flex; align-items:center; gap:10px; }
.apt-page-title i { color:#3b82f6; }
.apt-page-actions { display:flex; gap:8px; flex-wrap:wrap; }

/* ── Filter Card ─────────────────────────────────── */
.filter-card {
    background:#fff; border-radius:12px; padding:18px 20px;
    box-shadow:0 1px 6px rgba(0,0,0,.08); margin-bottom:16px;
    border:1px solid #e8ecf1;
}
.filter-row { display:flex; gap:10px; flex-wrap:wrap; align-items:flex-end; margin-bottom:12px; }
.filter-row:last-child { margin-bottom:0; }
.filter-field { display:flex; flex-direction:column; gap:4px; }
.filter-label {
    font-size:10px; font-weight:700; text-transform:uppercase;
    letter-spacing:.5px; color:#64748b; white-space:nowrap;
}
.filter-field .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; }
.filter-field .form-control:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
.filter-sep { width:1px; background:#e2e8f0; align-self:stretch; margin:0 4px; }

/* Date preset pills */
.date-presets { display:flex; gap:5px; flex-wrap:wrap; }
.preset-pill {
    padding:5px 13px; border-radius:20px; font-size:11.5px; font-weight:700;
    border:1.5px solid #e2e8f0; background:#fff; color:#64748b; cursor:pointer;
    transition:all .13s; line-height:1;
}
.preset-pill:hover { border-color:#3b82f6; color:#2563eb; background:#eff6ff; }
.preset-pill.active { background:#2563eb; border-color:#2563eb; color:#fff; box-shadow:0 2px 6px rgba(37,99,235,.3); }

/* Date range */
.date-range-wrap { display:flex; align-items:center; gap:6px; }
.date-range-wrap .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; width:120px; }
.date-range-sep { font-size:13px; color:#94a3b8; font-weight:700; }
.btn-apply-range {
    height:34px; padding:0 12px; border-radius:7px; font-size:12px;
    background:#3b82f6; border:none; color:#fff; font-weight:600; cursor:pointer;
    transition:background .13s;
}
.btn-apply-range:hover { background:#2563eb; }

/* Search input */
.search-wrap { position:relative; flex:1; min-width:160px; }
.search-wrap .fa { position:absolute; left:10px; top:50%; transform:translateY(-50%); color:#94a3b8; font-size:12px; }
.search-wrap input { padding-left:30px !important; }

/* ── Status Tabs ─────────────────────────────────── */
.status-tab-row {
    display:flex; gap:5px; flex-wrap:wrap; padding:4px 0 10px;
    border-bottom:2px solid #f1f5f9; margin-bottom:14px;
}
.status-tab {
    display:inline-flex; align-items:center; gap:5px;
    padding:6px 14px; border-radius:20px; font-size:12px; font-weight:700;
    border:1.5px solid transparent; cursor:pointer;
    background:#f8fafc; color:#64748b;
    transition:all .14s; white-space:nowrap;
}
.status-tab:hover { background:#f1f5f9; }
.status-tab .cnt-badge {
    background:rgba(0,0,0,.1); border-radius:10px; font-size:10px;
    padding:0px 6px; font-weight:800; line-height:1.5;
}
.status-tab.active { color:#fff !important; box-shadow:0 2px 8px rgba(0,0,0,.18); }
.status-tab[data-status="all"].active      { background:#475569; border-color:#475569; }
.status-tab[data-status="pending"].active   { background:#f59e0b; border-color:#f59e0b; }
.status-tab[data-status="confirmed"].active { background:#0ea5e9; border-color:#0ea5e9; }
.status-tab[data-status="in_progress"].active { background:#6366f1; border-color:#6366f1; }
.status-tab[data-status="completed"].active { background:#22c55e; border-color:#22c55e; }
.status-tab[data-status="waiting"].active   { background:#0d9488; border-color:#0d9488; }
.status-tab[data-status="cancelled"].active { background:#ef4444; border-color:#ef4444; }
.status-tab[data-status="no_show"].active   { background:#94a3b8; border-color:#94a3b8; }

/* Tab border colors (inactive) */
.status-tab[data-status="pending"]     { border-color:#f59e0b22; color:#d97706; }
.status-tab[data-status="waiting"]     { border-color:#0d948822; color:#0d9488; }
.status-tab[data-status="confirmed"]   { border-color:#0ea5e922; color:#0284c7; }
.status-tab[data-status="in_progress"] { border-color:#6366f122; color:#4f46e5; }
.status-tab[data-status="completed"]   { border-color:#22c55e22; color:#16a34a; }
.status-tab[data-status="cancelled"]   { border-color:#ef444422; color:#dc2626; }
.status-tab[data-status="no_show"]     { border-color:#94a3b822; color:#64748b; }

/* ── DataTable tweaks ────────────────────────────── */
#appointments_table_wrapper { width:100%; }
#appointments_table_wrapper .dataTables_filter { display:none; }
#appointments_table_wrapper table.dataTable { width:100% !important; }
#appointments_table td { vertical-align:middle; font-size:12.5px; }
#appointments_table .ref-col { font-size:11px; font-weight:700; color:#475569; font-family:monospace; }
#appointments_table .apt-ref-link { color:#2563eb; text-decoration:none; border-bottom:1px dashed transparent; transition:border-color .12s, color .12s; }
#appointments_table .apt-ref-link:hover { color:#1d4ed8; border-bottom-color:#2563eb; }

/* Clear filters button */
#btn_clear_filters:hover { background:#fef2f2 !important; border-color:#fca5a5 !important; color:#dc2626 !important; }

/* Active filters bar */
.active-filters { display:flex; gap:6px; flex-wrap:wrap; align-items:center; margin-bottom:8px; }
.af-chip {
    display:inline-flex; align-items:center; gap:5px;
    padding:3px 10px; border-radius:20px; font-size:11px; font-weight:600;
    background:#dbeafe; color:#1d4ed8; border:1px solid #bfdbfe;
}
.af-chip .af-remove { cursor:pointer; font-size:10px; opacity:.7; }
.af-chip .af-remove:hover { opacity:1; }

/* ── Action buttons ──────────────────────────────────── */
.vc-act-group { display:inline-flex; gap:5px; }
.vc-act-btn {
    width:30px; height:30px; border-radius:8px;
    display:inline-flex; align-items:center; justify-content:center;
    font-size:12px; border:1.5px solid transparent; cursor:pointer;
    transition:all .15s; text-decoration:none; padding:0;
}
.vc-act-btn:hover { transform:translateY(-2px); }
.vc-act-view { background:#eff6ff; color:#2563eb; border-color:#bfdbfe; }
.vc-act-view:hover { background:#2563eb; color:#fff; box-shadow:0 4px 10px rgba(37,99,235,.3); }
.vc-act-edit { background:#fffbeb; color:#d97706; border-color:#fde68a; }
.vc-act-edit:hover { background:#d97706; color:#fff; box-shadow:0 4px 10px rgba(217,119,6,.3); }
.vc-act-eval { background:#f0fdf4; color:#16a34a; border-color:#bbf7d0; }
.vc-act-eval:hover { background:#16a34a; color:#fff; box-shadow:0 4px 10px rgba(22,163,74,.32); }
.vc-act-disabled {
    background:#f8fafc; color:#cbd5e1; border-color:#e9eef3;
    cursor:not-allowed;
}
.vc-act-disabled:hover { transform:none; }

/* ── Evaluation modal shell ──────────────────────────── */
.vc-eval-modal .modal-content {
    border:none; border-radius:14px; overflow:hidden;
    box-shadow:0 24px 60px rgba(15,23,42,.32);
}
.vc-eval-modal .modal-body { max-height:74vh; overflow-y:auto; }
.vc-eval-x {
    position:absolute; top:13px; right:15px; z-index:10;
    width:30px; height:30px; border-radius:50%;
    border:none; background:rgba(255,255,255,.22); color:#fff;
    font-size:15px; line-height:1; cursor:pointer; opacity:.92;
    transition:all .18s;
}
.vc-eval-x:hover { background:rgba(255,255,255,.42); opacity:1; transform:rotate(90deg); }
.vc-eval-loading {
    display:flex; flex-direction:column; align-items:center; justify-content:center;
    gap:13px; padding:64px 20px; color:#94a3b8; font-size:13px; font-weight:600;
}
.vc-eval-loading i { font-size:30px; color:#5b8def; }
.vc-eval-foot { border-top:1px solid #eef1f5; background:#fafbfc; padding:12px 18px; }
.vc-eval-foot .btn { border-radius:8px; font-weight:600; padding:7px 18px; }
.vc-eval-foot .btn-success {
    background:linear-gradient(135deg,#22c55e,#16a34a); border:none;
    box-shadow:0 4px 12px rgba(34,197,94,.32);
}
.vc-eval-foot .btn-success:hover { background:linear-gradient(135deg,#16a34a,#15803d); }

/* ── Inline status changer ───────────────────────────── */
.vc-status-dd { display:inline-block; position:relative; }
.vc-status-trigger { text-decoration:none; cursor:pointer; white-space:nowrap; }
.vc-status-trigger:hover, .vc-status-trigger:focus, .vc-status-trigger:active { text-decoration:none; outline:none; }
.vc-status-menu {
    min-width:170px; font-size:12px; padding:4px 0;
    z-index:9999; box-shadow:0 6px 22px rgba(15,23,42,.22);
}
.vc-status-menu > li > a { padding:6px 14px; }
.vc-status-menu > li > a:hover { background:#f1f5f9; }
.vc-status-menu > li.active > a,
.vc-status-menu > li.active > a:hover { background:#eff6ff; color:#2563eb; font-weight:700; }
.vc-status-menu .fa-check { color:#22c55e; }
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header" style="padding-bottom:0;">
    <h1 style="display:none;"></h1>
</section>

<section class="content">

    {{-- Page Header --}}
    <div class="apt-page-header">
        <div class="apt-page-title">
            <i class="fas fa-calendar-alt"></i>
            @lang('clinicCore::lang.appointments')
            <span style="font-size:13px;font-weight:500;color:#94a3b8;margin-left:4px;">
                · {{ \Carbon\Carbon::today()->format('l, d M Y') }}
            </span>
        </div>
        <div class="apt-page-actions">
            <a href="{{ route('clinic.appointments.calendar') }}" class="btn btn-default btn-sm">
                <i class="fas fa-calendar-week"></i> Calendar View
            </a>
            @can('clinic.manage_appointments')
            <a href="{{ route('clinic.appointments.create') }}" class="btn btn-primary btn-sm">
                <i class="fa fa-plus"></i> New Appointment
            </a>
            @endcan
        </div>
    </div>

    {{-- Filter Card --}}
    <div class="filter-card">
        {{-- Row 1: Date presets + date range + search --}}
        <div class="filter-row">
            <div class="filter-field">
                <span class="filter-label"><i class="fa fa-calendar fa-fw"></i> Date Preset</span>
                <div class="date-presets">
                    <button class="preset-pill active" data-preset="today">Today</button>
                    <button class="preset-pill" data-preset="tomorrow">Tomorrow</button>
                    <button class="preset-pill" data-preset="week">This Week</button>
                    <button class="preset-pill" data-preset="month">This Month</button>
                    <button class="preset-pill" data-preset="all">All Time</button>
                </div>
            </div>
            <div class="filter-sep"></div>
            <div class="filter-field">
                <span class="filter-label"><i class="fa fa-calendar fa-fw"></i> Date Range</span>
                <div class="date-range-wrap">
                    <input type="text" id="filter_date_from" class="form-control" placeholder="From" style="width:115px;">
                    <span class="date-range-sep">→</span>
                    <input type="text" id="filter_date_to" class="form-control" placeholder="To" style="width:115px;">
                    <button class="btn-apply-range" id="btn_apply_dates" title="Apply date range">
                        <i class="fa fa-check"></i>
                    </button>
                </div>
            </div>
            <div class="filter-sep" style="display:none;" id="sep_right"></div>
            <div class="filter-field" style="flex:1;min-width:180px;">
                <span class="filter-label"><i class="fa fa-search fa-fw"></i> Search</span>
                <div class="search-wrap">
                    <i class="fa fa-search"></i>
                    <input type="text" id="filter_search" class="form-control" placeholder="Patient name, contact, ref#…" style="width:100%;">
                </div>
            </div>
        </div>

        {{-- Row 2: Doctor / Department / Type / Skin Type --}}
        <div class="filter-row">
            <div class="filter-field" style="flex:1;min-width:150px;">
                <span class="filter-label"><i class="fa fa-user-md fa-fw"></i> Doctor</span>
                <select id="filter_doctor_id" class="form-control select2" style="width:100%;">
                    <option value="">All Doctors</option>
                    @foreach($doctors as $doc)
                    <option value="{{ $doc->id }}">{{ $doc->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="filter-field" style="flex:1;min-width:140px;">
                <span class="filter-label"><i class="fa fa-hospital fa-fw"></i> Department</span>
                <select id="filter_department_id" class="form-control select2" style="width:100%;">
                    <option value="">All Departments</option>
                    @foreach($departments as $dept)
                    <option value="{{ $dept->id }}">{{ $dept->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="filter-field" style="flex:1;min-width:130px;">
                <span class="filter-label"><i class="fa fa-tag fa-fw"></i> Type</span>
                <select id="filter_type" class="form-control" style="width:100%;">
                    <option value="">All Types</option>
                    @foreach(['checkup'=>'Checkup','vaccination'=>'Treatment','surgery'=>'Surgery','grooming'=>'Grooming','emergency'=>'Emergency','other'=>'Other'] as $val => $label)
                    <option value="{{ $val }}">{{ $label }}</option>
                    @endforeach
                    @foreach($aptTypes as $at)
                    <option value="{{ $at->id }}">{{ $at->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="filter-field" style="align-self:flex-end;">
                <button id="btn_clear_filters" title="Clear all filters"
                        style="height:34px;padding:0 14px;border-radius:7px;border:1.5px solid #e2e8f0;
                               background:#fff;color:#64748b;font-size:12px;font-weight:700;cursor:pointer;
                               display:inline-flex;align-items:center;gap:6px;transition:all .14s;white-space:nowrap;">
                    <i class="fa fa-times-circle" style="color:#ef4444;font-size:13px;"></i> Clear Filters
                </button>
            </div>
        </div>
    </div>

    {{-- Status tabs --}}
    <div class="status-tab-row" id="status_tabs">
        @php
        $tabDefs = [
            'all'         => ['All',            '#475569'],
            'pending'     => ['Scheduled',      '#f59e0b'],
            'waiting'     => ['Waiting',        '#0d9488'],
            'confirmed'   => ['Confirmed',      '#0ea5e9'],
            'in_progress' => ['In Consultation','#6366f1'],
            'completed'   => ['Completed',      '#22c55e'],
            'cancelled'   => ['Cancelled',      '#ef4444'],
            'no_show'     => ['No Show',        '#94a3b8'],
        ];
        $totalAll = $statusCounts->sum();
        @endphp
        @foreach($tabDefs as $key => [$label, $color])
        @php
        $cnt = $key === 'all' ? $totalAll : ($statusCounts[$key] ?? 0);
        @endphp
        <button class="status-tab {{ $key === 'all' ? 'active' : '' }}" data-status="{{ $key }}">
            {{ $label }}
            @if($cnt > 0)
            <span class="cnt-badge">{{ $cnt }}</span>
            @endif
        </button>
        @endforeach
    </div>

    {{-- Evaluation modal (shared, lazy body) --}}
    <div class="modal fade vc-eval-modal" id="drmEvaluationModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <button type="button" class="vc-eval-x" data-dismiss="modal" aria-label="Close">&times;</button>
                <div class="modal-body" id="clc_eval_modal_body">
                    <div class="vc-eval-loading">
                        <i class="fa fa-spinner fa-spin"></i>
                        <span>Loading evaluation form…</span>
                    </div>
                </div>
                <div class="modal-footer vc-eval-foot">
                    <button class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
                    <button class="btn btn-success" id="btn_clc_eval_save"><i class="fa fa-save"></i> Save Evaluation</button>
                </div>
            </div>
        </div>
    </div>

    {{-- DataTable --}}
    <div class="box box-default" style="border-radius:10px;overflow:hidden;box-shadow:0 1px 6px rgba(0,0,0,.08);border:1px solid #e8ecf1;">
        <div class="box-body" style="padding:14px;">
            <table class="table table-bordered table-striped table-hover" id="appointments_table" width="100%" style="font-size:12.5px;width:100%;">
                <thead style="background:#f8fafc;">
                    <tr>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Ref</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Date</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Patient</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Contact</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Doctor / Dept</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Type</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Status</th>
                        <th style="font-size:11px;color:#64748b;font-weight:700;text-transform:uppercase;letter-spacing:.3px;">Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>

</section>
@endsection

@section('javascript')
<script>
var currentStatus      = 'all';
var currentDateFrom    = '{{ date('Y-m-d') }}';
var currentDateTo      = '{{ date('Y-m-d') }}';
var currentSearch      = '';
var currentPreset      = 'today';
window.clcActionTarget  = '{{ $clcActionTarget ?? "_self" }}';

// Open action-button links in new tab if the module setting says so
$(document).on('click', '#appointments_table a.vc-act-btn[href]', function (e) {
    if (window.clcActionTarget === '_blank') {
        e.preventDefault();
        window.open($(this).attr('href'), '_blank');
    }
});

$(document).ready(function () {
    initDatePickers();
    initSelect2();
    setPreset('today', false);
    initTable();
    loadURLParams();
});

function initSelect2() {
    $('#filter_doctor_id, #filter_department_id').select2({ width: '100%', placeholder: 'All' });
}

function initDatePickers() {
    $('#filter_date_from, #filter_date_to').datepicker({
        autoclose: true,
        format: datepicker_date_format,
        todayHighlight: true,
    }).on('changeDate', function (e) {
        // Guard: clearDates fires changeDate with an empty array — ignore it
        if (!e.dates || !e.dates.length || !e.dates[0]) return;
        currentPreset = '';
        $('.preset-pill').removeClass('active');
        var d   = e.dates[0];
        var iso = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
        if ($(this).is('#filter_date_from')) currentDateFrom = iso;
        else                                  currentDateTo   = iso;
    });
}

function setPreset(preset, reload) {
    reload = reload !== false;
    var today = new Date();
    var from, to;

    if (preset === 'today') {
        from = to = toIso(today);
    } else if (preset === 'tomorrow') {
        var t = new Date(today); t.setDate(t.getDate() + 1);
        from = to = toIso(t);
    } else if (preset === 'week') {
        var day = today.getDay();
        var mon = new Date(today); mon.setDate(today.getDate() - day + (day === 0 ? -6 : 1));
        var sun = new Date(mon); sun.setDate(mon.getDate() + 6);
        from = toIso(mon); to = toIso(sun);
    } else if (preset === 'month') {
        from = toIso(new Date(today.getFullYear(), today.getMonth(), 1));
        to   = toIso(new Date(today.getFullYear(), today.getMonth() + 1, 0));
    } else {
        from = to = '';
    }

    currentDateFrom = from;
    currentDateTo   = to;
    currentPreset   = preset;

    $('.preset-pill').removeClass('active');
    $('.preset-pill[data-preset="' + preset + '"]').addClass('active');

    if (from) {
        $('#filter_date_from').datepicker('setDate', new Date(from + 'T00:00:00'));
        $('#filter_date_to').datepicker('setDate', new Date(to + 'T00:00:00'));
    } else {
        // Safely clear datepicker inputs — 'clearDates' may not exist in all versions
        $('#filter_date_from, #filter_date_to').val('');
        try { $('#filter_date_from, #filter_date_to').datepicker('update', ''); } catch (e) {}
    }

    if (reload) reloadTable();
}

function toIso(d) {
    return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
}

function reloadTable() {
    if ($.fn.DataTable.isDataTable('#appointments_table')) {
        $('#appointments_table').DataTable().ajax.reload(null, false);
    }
}

function initTable() {
    $('#appointments_table').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: false,
        scrollX: false,
        order: [[1, 'asc'], [2, 'asc']],
        language: {
            processing: '<i class="fa fa-spinner fa-spin fa-2x fa-fw text-primary"></i>',
            emptyTable: '<div style="padding:30px;color:#94a3b8;"><i class="fa fa-calendar-times fa-2x" style="margin-bottom:8px;display:block;"></i>No appointments found for these filters.</div>',
        },
        ajax: {
            url: '{{ route('clinic.appointments.list') }}',
            data: function (d) {
                d.status               = currentStatus;
                d.date_from            = currentDateFrom;
                d.date_to              = currentDateTo;
                d.filter_doctor_id     = $('#filter_doctor_id').val();
                d.filter_department_id = $('#filter_department_id').val();
                d.filter_type          = $('#filter_type').val();
                d.filter_species       = $('#filter_species').val();
                d.filter_search        = currentSearch;
            }
        },
        columns: [
            { data: 'ref_no',           name: 'ref_no',           width: '90px', className: 'ref-col' },
            { data: 'datetime_col',     name: 'appointment_date',  width: '110px' },
            { data: 'pet_name',         name: 'pet_name',          orderable: false },
            { data: 'owner_name',       name: 'owner_name',        orderable: false },
            { data: 'doctor_name',      name: 'doctor_name',       orderable: false },
            { data: 'type_badge',       name: 'type',              orderable: false, width: '95px' },
            { data: 'status_badge',     name: 'status',            orderable: false, width: '105px' },
            { data: 'action',           name: 'action',            orderable: false, searchable: false, width: '115px' }
        ]
    });
}

// Date preset buttons
$('.preset-pill').on('click', function () {
    setPreset($(this).data('preset'));
});

// Apply date range button
$('#btn_apply_dates').on('click', function () {
    currentPreset = '';
    $('.preset-pill').removeClass('active');
    reloadTable();
});

// Status tabs
$(document).on('click', '#status_tabs .status-tab', function () {
    $('#status_tabs .status-tab').removeClass('active');
    $(this).addClass('active');
    currentStatus = $(this).data('status');
    reloadTable();
});

// Doctor / Dept / Type / Skin Type dropdowns
$('#filter_doctor_id, #filter_department_id, #filter_type, #filter_species').on('change', function () {
    reloadTable();
});

// Search (debounce 400ms)
var searchTimer;
$('#filter_search').on('input', function () {
    clearTimeout(searchTimer);
    var val = $(this).val().trim();
    searchTimer = setTimeout(function () {
        currentSearch = val;
        reloadTable();
    }, 400);
});

// Clear all filters
$('#btn_clear_filters').on('click', function () {
    currentStatus  = 'all';
    currentSearch  = '';
    $('#filter_search').val('');
    $('#filter_doctor_id, #filter_department_id').val(null).trigger('change');
    $('#filter_type, #filter_species').val('');
    $('#status_tabs .status-tab').removeClass('active');
    $('#status_tabs .status-tab[data-status="all"]').addClass('active');
    setPreset('all');
});

// ── Status dropdown: float the menu with position:fixed so the table's
//    overflow:hidden box can't clip it ("goes under the table" fix) ────────────
$(document).on('shown.bs.dropdown', '.vc-status-dd', function () {
    var trigger = $(this).find('.vc-status-trigger')[0];
    var $menu   = $(this).find('.vc-status-menu');
    if (!trigger || !$menu.length) return;

    var rect  = trigger.getBoundingClientRect();
    var menuH = $menu.outerHeight();
    var menuW = $menu.outerWidth();

    var top = rect.bottom + 2;
    // flip above the trigger if there isn't enough room below
    if (top + menuH > window.innerHeight && rect.top - menuH > 0) {
        top = rect.top - menuH - 2;
    }
    var left = rect.left;
    if (left + menuW > window.innerWidth - 8) {
        left = Math.max(8, window.innerWidth - menuW - 8);
    }

    $menu.css({ position: 'fixed', top: top + 'px', left: left + 'px', margin: 0, zIndex: 9999 });
});

$(document).on('hidden.bs.dropdown', '.vc-status-dd', function () {
    $(this).find('.vc-status-menu').removeAttr('style');
});

// ── Inline status change (no need to open the appointment) ─────────────────────
$(document).on('click', '.vc-status-opt', function (e) {
    e.preventDefault();
    var $opt   = $(this);
    var id     = $opt.data('id');
    var status = $opt.data('status');
    $('.vc-status-dd').removeClass('open');
    $.post('{{ url('clinic/appointments') }}/' + id + '/status',
        { _token: '{{ csrf_token() }}', status: status })
        .done(function (res) {
            if (res.success) {
                toastr.success('Status updated');
                reloadTable();
            } else {
                toastr.error(res.msg || 'Update failed');
            }
        })
        .fail(function (xhr) {
            toastr.error(xhr.responseJSON?.msg ?? 'Failed to update status');
        });
});

// ── Evaluation modal (clinic category, from action column) ─────────────────────
var drmEvalAppointmentId = null;
var drmEvalCategory      = 'clinic';

$(document).on('click', '.btn-evaluate-clinic', function () {
    drmEvalAppointmentId = $(this).data('id');
    drmEvalCategory      = 'clinic';
    openClcEvaluationModal();
});

function openClcEvaluationModal() {
    $('#clc_eval_modal_body').html('<div class="text-center" style="padding:30px;"><i class="fa fa-spinner fa-spin fa-2x text-primary"></i></div>');
    $('#drmEvaluationModal').modal('show');
    $.get('{{ url('clinic/appointments') }}/' + drmEvalAppointmentId + '/evaluation/form', { category: drmEvalCategory })
        .done(function (res) {
            if (res.success) {
                $('#clc_eval_modal_body').html(res.html);
            } else {
                $('#clc_eval_modal_body').html('<div class="alert alert-warning">' + (res.msg || 'Could not load form.') + '</div>');
            }
        })
        .fail(function (xhr) {
            $('#clc_eval_modal_body').html('<div class="alert alert-danger">' + (xhr.responseJSON?.msg ?? 'Error loading form') + '</div>');
        });
}

$('#btn_clc_eval_save').on('click', function () {
    if (!drmEvalAppointmentId) return;
    var $form = $('#clc_evaluation_form');
    if (!$form.length) { toastr.error('No questions to submit.'); return; }

    // Required-field validation
    var missing = false;
    $form.find('[data-required="1"]').each(function () {
        var v = $(this).val();
        if (v === '' || v === null || v === undefined) missing = true;
    });
    if (missing) { toastr.warning('Please answer all required questions.'); return; }

    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
    $.post('{{ url('clinic/appointments') }}/' + drmEvalAppointmentId + '/evaluation', $form.serialize())
        .done(function (res) {
            if (res.success) {
                toastr.success(res.msg);
                if (res.flagged) toastr.warning('Average rating below 3 — flagged for management review.');
                $('#drmEvaluationModal').modal('hide');
            } else {
                toastr.error(res.msg || 'Save failed');
            }
        })
        .fail(function (xhr) { toastr.error(xhr.responseJSON?.msg ?? 'Save failed'); })
        .always(function () { $btn.prop('disabled', false).html('<i class="fa fa-save"></i> Save Evaluation'); });
});

// Pre-select doctor from URL (linked from doctor list)
function loadURLParams() {
    var params = new URLSearchParams(window.location.search);
    var doctorId = params.get('filter_doctor_id');
    if (doctorId) {
        var opt = new Option('...', doctorId, true, true);
        $('#filter_doctor_id').append(opt).trigger('change');
    }
    var preset = params.get('preset') || 'today';
    if (params.get('preset')) setPreset(preset, false);
}
</script>
@endsection
