@extends('layouts.app')
@section('title', __('vetClinic::lang.reports'))

@section('css')
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap.min.css">
<style>
/* ── KPI Header ──────────────────────────────────────── */
.rpt-kpi-row { display:grid; grid-template-columns:repeat(6,1fr); gap:12px; margin-bottom:20px; }
@media(max-width:1100px){ .rpt-kpi-row { grid-template-columns:repeat(3,1fr); } }
@media(max-width:600px) { .rpt-kpi-row { grid-template-columns:repeat(2,1fr); } }
.rpt-kpi {
    background:#fff; border-radius:10px; padding:14px 16px;
    box-shadow:0 1px 4px rgba(0,0,0,.08); border-top:4px solid;
    display:flex; align-items:center; gap:12px;
}
.rpt-kpi-icon { font-size:24px; opacity:.2; }
.rpt-kpi-num  { font-size:26px; font-weight:800; line-height:1; }
.rpt-kpi-lbl  { font-size:10px; text-transform:uppercase; letter-spacing:.5px; color:#94a3b8; margin-top:2px; }

/* ── Layout ──────────────────────────────────────────── */
.rpt-layout { display:flex; gap:16px; align-items:flex-start; }
.rpt-nav {
    width:200px; flex-shrink:0;
    background:#fff; border-radius:10px;
    box-shadow:0 1px 4px rgba(0,0,0,.08);
    overflow:hidden; position:sticky; top:20px;
}
.rpt-nav-item {
    display:flex; align-items:center; gap:10px;
    padding:11px 16px; font-size:13px; font-weight:600;
    color:#475569; cursor:pointer; border-left:3px solid transparent;
    transition:all .13s; text-decoration:none; border-bottom:1px solid #f8fafc;
}
.rpt-nav-item:hover { background:#f8fafc; color:#1e293b; text-decoration:none; }
.rpt-nav-item.active { background:#eff6ff; color:#2563eb; border-left-color:#2563eb; }
.rpt-nav-item i { width:16px; text-align:center; }
.rpt-content { flex:1; min-width:0; }

/* ── Report Section Card ─────────────────────────────── */
.rpt-section { display:none; }
.rpt-section.active { display:block; }
.rpt-card {
    background:#fff; border-radius:10px;
    box-shadow:0 1px 4px rgba(0,0,0,.08);
    border:1px solid #e8ecf0; margin-bottom:16px; overflow:hidden;
}
.rpt-card-header {
    padding:12px 18px; border-bottom:1px solid #f1f5f9;
    display:flex; align-items:center; justify-content:space-between;
    background:#f8fafc;
}
.rpt-card-title { font-size:13px; font-weight:700; color:#1e293b; display:flex; align-items:center; gap:8px; }
.rpt-card-body  { padding:16px 18px; }

/* ── Filters ──────────────────────────────────────────── */
.rpt-filter-bar {
    background:#fff; border-radius:10px; padding:16px 18px;
    box-shadow:0 1px 4px rgba(0,0,0,.08); border:1px solid #e8ecf0;
    margin-bottom:16px;
}
.rpt-filter-grid { display:flex; flex-wrap:wrap; gap:12px; align-items:flex-end; }
.rpt-filter-field { display:flex; flex-direction:column; gap:4px; flex:1; min-width:130px; }
.rpt-filter-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; }
.rpt-filter-field .form-control { height:34px; font-size:12px; border-radius:7px; border:1.5px solid #e2e8f0; }

/* ── Summary Boxes ────────────────────────────────────── */
.rpt-sum-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:10px; margin-bottom:16px; }
.rpt-sum-box {
    border-radius:8px; padding:12px 14px; text-align:center;
    border:1px solid; opacity:.9;
}
.rpt-sum-box .sum-num { font-size:28px; font-weight:800; line-height:1; }
.rpt-sum-box .sum-lbl { font-size:10px; text-transform:uppercase; letter-spacing:.5px; margin-top:3px; }

/* ── Charts Row ────────────────────────────────────────── */
.chart-row { display:grid; gap:16px; margin-bottom:16px; }
.chart-row.cols-2 { grid-template-columns:1fr 1fr; }
.chart-row.cols-3 { grid-template-columns:1fr 1fr 1fr; }
@media(max-width:900px){ .chart-row.cols-2, .chart-row.cols-3 { grid-template-columns:1fr; } }
.chart-canvas-wrap { position:relative; }

/* ── Table ─────────────────────────────────────────────── */
.rpt-table { font-size:12px; }
.rpt-table thead th { background:#f8fafc; font-size:10px; text-transform:uppercase; letter-spacing:.4px; color:#64748b; font-weight:700; border-bottom:2px solid #e2e8f0; }
.rpt-table td { vertical-align:middle; border-color:#f1f5f9; }

/* ── Doctor Activity ───────────────────────────────────── */
.doctor-row { display:flex; align-items:center; gap:10px; padding:10px 0; border-bottom:1px solid #f1f5f9; }
.doctor-row:last-child { border-bottom:none; }
.progress-bar-track { flex:1; background:#f1f5f9; border-radius:4px; height:6px; overflow:hidden; }
.progress-bar-fill  { height:100%; border-radius:4px; background:#22c55e; transition:width .4s ease; }

/* ── Evaluation table action buttons ───────────────────── */
.eval-act-btn {
    display:inline-flex; align-items:center; justify-content:center;
    width:30px; height:30px; border-radius:8px;
    border:1.5px solid transparent; cursor:pointer; padding:0;
    font-size:12px; text-decoration:none; transition:all .15s;
}
.eval-act-btn:hover { transform:translateY(-2px); text-decoration:none; }
.eval-act-open { background:#eff6ff; color:#2563eb; border-color:#bfdbfe; }
.eval-act-open:hover { background:#2563eb; color:#fff; box-shadow:0 4px 10px rgba(37,99,235,.32); }
.eval-act-review { background:#f0fdf4; color:#16a34a; border-color:#bbf7d0; width:auto; padding:0 11px; gap:5px; font-weight:600; }
.eval-act-review:hover { background:#16a34a; color:#fff; box-shadow:0 4px 10px rgba(22,163,74,.32); }
</style>
@endsection

@section('content')
<section class="content-header" style="display:none"></section>
<section class="content">

{{-- Page Header --}}
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
    <div style="font-size:22px;font-weight:800;color:#1e293b;display:flex;align-items:center;gap:10px;">
        <i class="fas fa-chart-bar" style="color:#2563eb;"></i>
        Reports
        <span style="font-size:13px;font-weight:500;color:#94a3b8;">· Vet Clinic Analytics</span>
    </div>
    <div style="font-size:12px;color:#94a3b8;"><i class="fa fa-calendar"></i> {{ now()->format('d M Y') }}</div>
</div>

{{-- KPI Row --}}
<div class="rpt-kpi-row">
    <div class="rpt-kpi" style="border-color:#8b5cf6;">
        <div class="rpt-kpi-icon" style="color:#8b5cf6;"><i class="fas fa-paw"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#8b5cf6;">{{ $kpi['total_pets'] }}</div>
            <div class="rpt-kpi-lbl">Total Pets</div>
        </div>
    </div>
    <div class="rpt-kpi" style="border-color:#22c55e;">
        <div class="rpt-kpi-icon" style="color:#22c55e;"><i class="fa fa-check-circle"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#22c55e;">{{ $kpi['active_pets'] }}</div>
            <div class="rpt-kpi-lbl">Active Pets</div>
        </div>
    </div>
    <div class="rpt-kpi" style="border-color:#3b82f6;">
        <div class="rpt-kpi-icon" style="color:#3b82f6;"><i class="fa fa-calendar"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#3b82f6;">{{ $kpi['today_apts'] }}</div>
            <div class="rpt-kpi-lbl">Today's Apts</div>
        </div>
    </div>
    <div class="rpt-kpi" style="border-color:#ef4444;">
        <div class="rpt-kpi-icon" style="color:#ef4444;"><i class="fas fa-syringe"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#ef4444;">{{ $kpi['overdue_vaccines'] }}</div>
            <div class="rpt-kpi-lbl">Overdue Vaccines</div>
        </div>
    </div>
    <div class="rpt-kpi" style="border-color:#f59e0b;">
        <div class="rpt-kpi-icon" style="color:#f59e0b;"><i class="fa fa-calendar-check"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#f59e0b;">{{ $kpi['month_apts'] }}</div>
            <div class="rpt-kpi-lbl">This Month Apts</div>
        </div>
    </div>
    <div class="rpt-kpi" style="border-color:#0ea5e9;">
        <div class="rpt-kpi-icon" style="color:#0ea5e9;"><i class="fa fa-thumbs-up"></i></div>
        <div>
            <div class="rpt-kpi-num" style="color:#0ea5e9;">{{ $kpi['month_apts'] > 0 ? round($kpi['month_completed']/$kpi['month_apts']*100) : 0 }}%</div>
            <div class="rpt-kpi-lbl">Completion Rate</div>
        </div>
    </div>
</div>

{{-- Main Layout --}}
<div class="rpt-layout">

    {{-- Navigation --}}
    <div class="rpt-nav">
        <div style="padding:12px 16px;border-bottom:2px solid #f1f5f9;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.6px;color:#94a3b8;">Reports</div>
        <a class="rpt-nav-item active" data-section="rpt_appointments" href="#">
            <i class="fas fa-calendar-check" style="color:#3b82f6;"></i> Appointments
        </a>
        <a class="rpt-nav-item" data-section="rpt_vaccinations" href="#">
            <i class="fas fa-syringe" style="color:#22c55e;"></i> Vaccinations
        </a>
        <a class="rpt-nav-item" data-section="rpt_pets" href="#">
            <i class="fas fa-paw" style="color:#8b5cf6;"></i> Pet Registrations
        </a>
        <a class="rpt-nav-item" data-section="rpt_doctors" href="#">
            <i class="fas fa-user-md" style="color:#f59e0b;"></i> Doctor Activity
        </a>
        <a class="rpt-nav-item" data-section="rpt_evaluations" href="#">
            <i class="fas fa-star" style="color:#f43f5e;"></i> Evaluations
        </a>
        <a class="rpt-nav-item" data-section="rpt_time" href="#">
            <i class="fas fa-stopwatch" style="color:#0ea5e9;"></i> Time Tracking
        </a>
        <a class="rpt-nav-item" data-section="rpt_geo" href="#">
            <i class="fas fa-map-marked-alt" style="color:#0d9488;"></i> Owner Geography
        </a>
        <a class="rpt-nav-item" data-section="rpt_visits" href="#">
            <i class="fas fa-redo" style="color:#d946ef;"></i> Visit Patterns
        </a>
        <a class="rpt-nav-item" data-section="rpt_inactive" href="#">
            <i class="fas fa-user-clock" style="color:#e11d48;"></i> Inactive Owners
        </a>
        <a class="rpt-nav-item" data-section="rpt_pref_doctor" href="#">
            <i class="fas fa-user-md" style="color:#7c3aed;"></i> Preferred-Doctor Changes
        </a>
        {{-- Item 4.1 - server-rendered page; navigates inline (no new tab)
             so doctors stay inside the reports area. Carries its own URL
             state via querystring for date/doctor/severity filters. --}}
        <a class="rpt-nav-item" href="{{ route('vc.reports.critical-check') }}"
           style="border-top:2px solid #fecaca;background:#fef2f2;">
            <i class="fa fa-exclamation-triangle" style="color:#dc2626;"></i> Medical Critical Check
        </a>
    </div>

    {{-- Content Panels --}}
    <div class="rpt-content">

        {{-- ══════════════════════════════════════════════ --}}
        {{-- APPOINTMENTS --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section active" id="rpt_appointments">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="apt_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="apt_from" value="{{ date('Y-m-01') }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="apt_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="apt_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Doctor</span>
                        <select id="apt_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="rpt-filter-field">
                        <span class="rpt-filter-label">Department</span>
                        <select id="apt_department_id" class="form-control">
                            <option value="">All Departments</option>
                            @foreach($departments as $dept)
                            <option value="{{ $dept->id }}">{{ $dept->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Type</span>
                        <select id="apt_type" class="form-control">
                            <option value="">All Types</option>
                            @foreach(['checkup'=>'Checkup','vaccination'=>'Vaccination','surgery'=>'Surgery','grooming'=>'Grooming','emergency'=>'Emergency','other'=>'Other'] as $tv=>$tl)
                            <option value="{{ $tv }}">{{ $tl }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Status</span>
                        <select id="apt_status" class="form-control">
                            <option value="">All</option>
                            @foreach(['pending','confirmed','in_progress','completed','cancelled','no_show'] as $s)
                            <option value="{{ $s }}">{{ ucfirst(str_replace('_',' ',$s)) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_appointments" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            {{-- Summary --}}
            <div id="apt_results_wrap" style="display:none;">
                <div class="rpt-sum-row">
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;">
                        <div class="sum-num" id="apt_total">0</div>
                        <div class="sum-lbl">Total</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f0fdf4;border-color:#bbf7d0;color:#15803d;">
                        <div class="sum-num" id="apt_completed">0</div>
                        <div class="sum-lbl">Completed</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fffbeb;border-color:#fde68a;color:#b45309;">
                        <div class="sum-num" id="apt_pending">0</div>
                        <div class="sum-lbl">Scheduled</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef3c7;border-color:#fcd34d;color:#92400e;">
                        <div class="sum-num" id="apt_in_progress">0</div>
                        <div class="sum-lbl">In Progress</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c;">
                        <div class="sum-num" id="apt_cancelled">0</div>
                        <div class="sum-lbl">Cancelled</div>
                    </div>
                </div>

                <div class="chart-row cols-3">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#8b5cf6;"></i> By Type</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_by_type" height="200"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#3b82f6;"></i> By Doctor</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_by_doctor" height="200"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#f59e0b;"></i> By Status</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_by_status" height="200"></canvas></div>
                    </div>
                </div>

                <div class="chart-row cols-2" style="grid-template-columns:2fr 1fr;">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-line" style="color:#22c55e;"></i> Timeline</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_timeline" height="120"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#0ea5e9;"></i> By Department</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_by_dept" height="120"></canvas></div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-table" style="color:#64748b;"></i> Appointments List</div>
                        <button class="btn btn-xs btn-default" id="btn_apt_export_csv"><i class="fa fa-download"></i> CSV</button>
                    </div>
                    <div class="rpt-card-body" style="padding:0;">
                        <div style="overflow-x:auto;">
                            <table class="table table-bordered table-striped rpt-table" id="apt_table" style="margin:0;">
                                <thead>
                                    <tr>
                                        <th>Date</th><th>Time</th><th>Ref</th><th>Pet</th>
                                        <th>Doctor</th><th>Type</th><th>Status</th><th></th>
                                    </tr>
                                </thead>
                                <tbody id="apt_table_body"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- VACCINATIONS --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_vaccinations">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Show Due Within</span>
                        <select id="vax_days" class="form-control">
                            <option value="7">7 days</option>
                            <option value="14">14 days</option>
                            <option value="30" selected>30 days</option>
                            <option value="60">60 days</option>
                            <option value="90">90 days</option>
                            <option value="0">Overdue Only</option>
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Vaccine Type</span>
                        <select id="vax_type_id" class="form-control">
                            <option value="">All Vaccines</option>
                            @foreach($vaccineTypes as $vt)
                            <option value="{{ $vt->id }}">{{ $vt->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Species</span>
                        <select id="vax_species" class="form-control">
                            <option value="">All Species</option>
                            @foreach(['dog'=>'🐕 Dog','cat'=>'🐈 Cat','rabbit'=>'🐇 Rabbit','bird'=>'🦜 Bird'] as $sv=>$sl)
                            <option value="{{ $sv }}">{{ $sl }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_vaccinations" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="vax_results_wrap" style="display:none;">
                <div class="rpt-sum-row" style="grid-template-columns:repeat(3,1fr);max-width:500px;">
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c;">
                        <div class="sum-num" id="vax_total_overdue">0</div>
                        <div class="sum-lbl">Overdue</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fffbeb;border-color:#fde68a;color:#b45309;">
                        <div class="sum-num" id="vax_total_due">0</div>
                        <div class="sum-lbl">Due Soon</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f8fafc;border-color:#e2e8f0;color:#475569;">
                        <div class="sum-num" id="vax_total">0</div>
                        <div class="sum-lbl">Total Found</div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fas fa-syringe" style="color:#22c55e;"></i> Vaccination Due List</div>
                    </div>
                    <div class="rpt-card-body" style="padding:0;">
                        <div style="overflow-x:auto;">
                            <table class="table table-bordered table-striped rpt-table" style="margin:0;">
                                <thead>
                                    <tr>
                                        <th>Pet</th><th>Species</th><th>Owner</th><th>Mobile</th>
                                        <th>Vaccine</th><th>Last Administered</th><th>Next Due</th><th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="vax_report_body">
                                    <tr><td colspan="8" class="text-center text-muted" style="padding:30px;">Click "Generate" to load data.</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- PET REGISTRATIONS --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_pets">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="pet_reg_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="pet_reg_from" value="{{ date('Y-m-d', strtotime('-11 months')) }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="pet_reg_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="pet_reg_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_pet_reg" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="pet_reg_results" style="display:none;">
                <div class="chart-row cols-2">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-line" style="color:#8b5cf6;"></i> Registrations Over Time</div>
                            <span id="pet_reg_period_total" style="font-size:11px;color:#94a3b8;"></span>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_pet_timeline" height="180"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#3b82f6;"></i> By Species</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_pet_species" height="180"></canvas></div>
                    </div>
                </div>
                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#f59e0b;"></i> Age Distribution</div>
                    </div>
                    <div class="rpt-card-body"><canvas id="chart_pet_age" height="100"></canvas></div>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- DOCTOR ACTIVITY --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_doctors">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="doc_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="doc_from" value="{{ date('Y-m-01') }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="doc_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="doc_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_doctors" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="doc_results" style="display:none;">
                <div class="chart-row cols-2">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#f59e0b;"></i> Appointments by Doctor</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_doc_apts" height="200"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-check-circle" style="color:#22c55e;"></i> Completion Rate</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_doc_rate" height="200"></canvas></div>
                    </div>
                </div>
                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fas fa-user-md" style="color:#64748b;"></i> Doctor Performance</div>
                    </div>
                    <div class="rpt-card-body" id="doc_perf_list"></div>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- EVALUATIONS --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_evaluations">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="eval_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="eval_from" value="{{ date('Y-m-01', strtotime('-2 months')) }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="eval_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="eval_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Category</span>
                        <select id="eval_category" class="form-control">
                            <option value="">Both</option>
                            <option value="pet_owner">Pet Owner Eval (doctor)</option>
                            <option value="clinic">Clinic / Doctor Eval (pet owner)</option>
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Doctor</span>
                        <select id="eval_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="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_evaluations" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="eval_results" style="display:none;">
                <div class="rpt-sum-row">
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#2563eb;">
                        <div class="sum-num" id="eval_sum_total">0</div>
                        <div class="sum-lbl">Total Evaluations</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#dc2626;">
                        <div class="sum-num" id="eval_sum_flagged">0</div>
                        <div class="sum-lbl">Flagged (Critical)</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fffbeb;border-color:#fde68a;color:#d97706;">
                        <div class="sum-num" id="eval_sum_pending_review">0</div>
                        <div class="sum-lbl">Pending Mgmt Review</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f0fdf4;border-color:#bbf7d0;color:#16a34a;">
                        <div class="sum-num" id="eval_sum_reviewed">0</div>
                        <div class="sum-lbl">Reviewed</div>
                    </div>
                </div>

                <div class="chart-row cols-2">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-star" style="color:#f59e0b;"></i> Avg Rating per Doctor</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_eval_doctor" height="220"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#8b5cf6;"></i> By Category</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_eval_category" height="220"></canvas></div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fas fa-user-md" style="color:#64748b;"></i> Per-Doctor Breakdown</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="eval_doctor_table" style="width:100%;">
                            <thead>
                                <tr>
                                    <th>Doctor</th>
                                    <th class="text-center">Total Evals</th>
                                    <th class="text-center">Pet Owner Avg</th>
                                    <th class="text-center">Clinic Avg</th>
                                    <th class="text-center">Overall</th>
                                    <th class="text-center">Flagged</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>

                <div class="rpt-card" style="border:2px solid #fecaca;">
                    <div class="rpt-card-header" style="background:#fef2f2;">
                        <div class="rpt-card-title" style="color:#dc2626;">
                            <i class="fa fa-exclamation-triangle"></i> Critical Appointments (Flagged for Review)
                        </div>
                        <small class="text-muted">Appointments with avg rating &lt; 3.00 — require management attention.</small>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="eval_critical_table" style="width:100%;">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Ref</th>
                                    <th>Category</th>
                                    <th>Pet</th>
                                    <th>Owner</th>
                                    <th>Doctor</th>
                                    <th class="text-center">Avg Rating</th>
                                    <th class="text-center">Review Status</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div id="eval_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-inbox fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No evaluations found in this period.</p>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- TIME TRACKING --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_time">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="tt_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="tt_from" value="{{ date('Y-m-01') }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="tt_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="tt_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Doctor</span>
                        <select id="tt_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="rpt-filter-field">
                        <span class="rpt-filter-label">Department</span>
                        <select id="tt_department_id" class="form-control">
                            <option value="">All Departments</option>
                            @foreach($departments as $dept)
                            <option value="{{ $dept->id }}">{{ $dept->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_time" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="tt_results" style="display:none;">
                <div class="rpt-sum-row">
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#2563eb;">
                        <div class="sum-num" id="tt_total">0</div>
                        <div class="sum-lbl">Tracked Visits</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fff7ed;border-color:#fed7aa;color:#d97706;">
                        <div class="sum-num"><span id="tt_avg_wait">0</span><small> min</small></div>
                        <div class="sum-lbl">Avg Waiting Time</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#dc2626;">
                        <div class="sum-num"><span id="tt_max_wait">0</span><small> min</small></div>
                        <div class="sum-lbl">Longest Wait</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f0fdf4;border-color:#bbf7d0;color:#16a34a;">
                        <div class="sum-num"><span id="tt_avg_consult">0</span><small> min</small></div>
                        <div class="sum-lbl">Avg Consultation</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f5f3ff;border-color:#ddd6fe;color:#7c3aed;">
                        <div class="sum-num"><span id="tt_max_consult">0</span><small> min</small></div>
                        <div class="sum-lbl">Longest Consultation</div>
                    </div>
                </div>

                <div class="chart-row cols-2">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#0ea5e9;"></i> Avg Time per Doctor</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_tt_doctor" height="220"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#d97706;"></i> Waiting Time Distribution</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_tt_dist" height="220"></canvas></div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fas fa-stopwatch" style="color:#64748b;"></i> Visit Details</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="tt_table" style="width:100%;">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Ref</th>
                                    <th>Pet</th>
                                    <th>Doctor</th>
                                    <th class="text-center">Arrived</th>
                                    <th class="text-center">Start</th>
                                    <th class="text-center">End</th>
                                    <th class="text-center">Waiting</th>
                                    <th class="text-center">Consultation</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div id="tt_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-stopwatch fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No tracked visits in this period.<br>
                    <small>Times are captured automatically as appointments move through Waiting → In Consultation → Completed.</small></p>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- OWNER GEOGRAPHY (1.1) --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_geo">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Country</span>
                        <select id="geo_country" class="form-control">
                            <option value="">All Countries</option>
                            @foreach($geoCountries as $c)<option value="{{ $c }}">{{ $c }}</option>@endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">State / Region</span>
                        <select id="geo_state" class="form-control">
                            <option value="">All States</option>
                            @foreach($geoStates as $s)<option value="{{ $s }}">{{ $s }}</option>@endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">City / Area</span>
                        <select id="geo_city" class="form-control">
                            <option value="">All Cities</option>
                            @foreach($geoCities as $c)<option value="{{ $c }}">{{ $c }}</option>@endforeach
                        </select>
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Search (name / address)</span>
                        <input type="text" id="geo_search" class="form-control" placeholder="Search…">
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_geo" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="geo_results" style="display:none;">
                <div class="rpt-sum-row">
                    <div class="rpt-sum-box" style="background:#f0fdfa;border-color:#99f6e4;color:#0f766e;">
                        <div class="sum-num" id="geo_total">0</div><div class="sum-lbl">Pet Owners</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;">
                        <div class="sum-num" id="geo_with_addr">0</div><div class="sum-lbl">With Address</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f5f3ff;border-color:#ddd6fe;color:#7c3aed;">
                        <div class="sum-num" id="geo_areas">0</div><div class="sum-lbl">Distinct Areas</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f0fdf4;border-color:#bbf7d0;color:#15803d;">
                        <div class="sum-num" id="geo_highest" style="font-size:16px;">—</div><div class="sum-lbl">Highest Area</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c;">
                        <div class="sum-num" id="geo_lowest" style="font-size:16px;">—</div><div class="sum-lbl">Lowest Area</div>
                    </div>
                </div>

                <div class="chart-row cols-2" style="grid-template-columns:2fr 1fr;">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-bar" style="color:#0d9488;"></i> Owners per City / Area</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_geo_city" height="150"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#3b82f6;"></i> By Country</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_geo_country" height="150"></canvas></div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-table" style="color:#64748b;"></i> Pet Owners by Location</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="geo_table" style="width:100%;">
                            <thead><tr>
                                <th>Owner</th><th>Mobile</th><th>Address</th><th>City / Area</th>
                                <th>State</th><th>Country</th><th>Zip</th><th class="text-center">Pets</th>
                            </tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div id="geo_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-map-marked-alt fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No pet owners match these filters.</p>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- VISIT PATTERNS (1.2) --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_visits">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="vp_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="vp_from" value="{{ date('Y-m-d', strtotime('-5 months')) }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="vp_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="vp_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Doctor</span>
                        <select id="vp_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="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_visits" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="vp_results" style="display:none;">
                <div class="rpt-sum-row">
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;">
                        <div class="sum-num" id="vp_owners">0</div><div class="sum-lbl">Owners with Visits</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#faf5ff;border-color:#e9d5ff;color:#9333ea;">
                        <div class="sum-num" id="vp_repeat">0</div><div class="sum-lbl">Repeat Visitors</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f8fafc;border-color:#e2e8f0;color:#475569;">
                        <div class="sum-num" id="vp_one_time">0</div><div class="sum-lbl">One-Time Only</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c;">
                        <div class="sum-num" id="vp_high_risk">0</div><div class="sum-lbl">High Cancel / No-Show</div>
                    </div>
                </div>

                <div class="chart-row cols-2">
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#22c55e;"></i> Appointment Attendance</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_vp_attendance" height="200"></canvas></div>
                    </div>
                    <div class="rpt-card">
                        <div class="rpt-card-header">
                            <div class="rpt-card-title"><i class="fa fa-chart-pie" style="color:#9333ea;"></i> Repeat vs One-Time</div>
                        </div>
                        <div class="rpt-card-body"><canvas id="chart_vp_repeat" height="200"></canvas></div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-exclamation-triangle" style="color:#ef4444;"></i> Highest Cancellations / No-Shows</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;padding:0;">
                        <table class="table rpt-table" id="vp_cancel_table" style="margin:0;width:100%;">
                            <thead><tr>
                                <th>Owner</th><th>Mobile</th><th class="text-center">Total</th>
                                <th class="text-center">Cancelled</th><th class="text-center">No-Show</th>
                                <th class="text-center">Missed</th>
                            </tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-table" style="color:#64748b;"></i> All Owners — Visit Summary</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="vp_table" style="width:100%;">
                            <thead><tr>
                                <th>Owner</th><th class="text-center">Total</th><th class="text-center">Completed</th>
                                <th class="text-center">Cancelled</th><th class="text-center">No-Show</th>
                                <th class="text-center">Attendance</th><th class="text-center">Repeat?</th>
                            </tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div id="vp_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-redo fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No appointments in this period.</p>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- INACTIVE OWNERS (1.3) --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_inactive">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">No Visit In The Last</span>
                        <select id="ina_days" class="form-control">
                            <option value="30">30 days</option>
                            <option value="60">60 days</option>
                            <option value="90" selected>90 days</option>
                            <option value="120">120 days</option>
                            <option value="180">180 days</option>
                            <option value="365">1 year</option>
                        </select>
                    </div>
                    <div class="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_inactive" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
                <p style="font-size:11px;color:#94a3b8;margin:8px 0 0;">
                    <i class="fa fa-info-circle"></i> Shows owners with at least one <strong>active pet</strong> who have not visited within the selected window — including those who never visited.
                </p>
            </div>

            <div id="ina_results" style="display:none;">
                <div class="rpt-sum-row" style="grid-template-columns:repeat(3,1fr);max-width:560px;">
                    <div class="rpt-sum-box" style="background:#fef2f2;border-color:#fecaca;color:#b91c1c;">
                        <div class="sum-num" id="ina_total">0</div><div class="sum-lbl">Inactive Owners</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fff7ed;border-color:#fed7aa;color:#c2410c;">
                        <div class="sum-num" id="ina_lapsed">0</div><div class="sum-lbl">Lapsed (had visited)</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f8fafc;border-color:#e2e8f0;color:#475569;">
                        <div class="sum-num" id="ina_never">0</div><div class="sum-lbl">Never Visited</div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-table" style="color:#64748b;"></i> Inactive Pet Owners</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="ina_table" style="width:100%;">
                            <thead><tr>
                                <th>Owner</th><th>Mobile</th><th>Email</th>
                                <th class="text-center">Active Pets</th><th>Last Visit</th><th class="text-center">Days Since</th>
                            </tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div id="ina_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-user-clock fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No inactive owners for this window — everyone with an active pet has visited recently.</p>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════ --}}
        {{-- PREFERRED-DOCTOR CHANGES (1.4) --}}
        {{-- ══════════════════════════════════════════════ --}}
        <div class="rpt-section" id="rpt_pref_doctor">
            <div class="rpt-filter-bar">
                <div class="rpt-filter-grid">
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">From</span>
                        <input type="text" id="pd_from_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="From date">
                        <input type="hidden" id="pd_from" value="{{ date('Y-m-d', strtotime('-5 months')) }}">
                    </div>
                    <div class="rpt-filter-field" style="min-width:140px;">
                        <span class="rpt-filter-label">To</span>
                        <input type="text" id="pd_to_display" class="form-control rpt-datepicker" autocomplete="off" placeholder="To date">
                        <input type="hidden" id="pd_to" value="{{ date('Y-m-d') }}">
                    </div>
                    <div class="rpt-filter-field">
                        <span class="rpt-filter-label">Doctor (old or new)</span>
                        <select id="pd_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="rpt-filter-field" style="flex:0 0 auto;align-self:flex-end;">
                        <button class="btn btn-primary btn-sm" id="btn_load_pref_doctor" style="height:34px;white-space:nowrap;">
                            <i class="fa fa-search"></i> Generate
                        </button>
                    </div>
                </div>
            </div>

            <div id="pd_results" style="display:none;">
                <div class="rpt-sum-row" style="grid-template-columns:repeat(4,1fr);">
                    <div class="rpt-sum-box" style="background:#f5f3ff;border-color:#ddd6fe;color:#7c3aed;">
                        <div class="sum-num" id="pd_total">0</div><div class="sum-lbl">Total Changes</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;">
                        <div class="sum-num" id="pd_owner_level">0</div><div class="sum-lbl">Owner-Level (general)</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#f0fdf4;border-color:#bbf7d0;color:#15803d;">
                        <div class="sum-num" id="pd_pet_level">0</div><div class="sum-lbl">Pet-Level (override)</div>
                    </div>
                    <div class="rpt-sum-box" style="background:#fff7ed;border-color:#fed7aa;color:#c2410c;">
                        <div class="sum-num" id="pd_via_request">0</div><div class="sum-lbl">Via Approved Request</div>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-exclamation-triangle" style="color:#d946ef;"></i> Owners Who Change Their Preferred Doctor Most</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;padding:0;">
                        <table class="table rpt-table" id="pd_owner_table" style="margin:0;width:100%;">
                            <thead><tr><th>Owner</th><th class="text-center">Changes</th></tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>

                <div class="rpt-card">
                    <div class="rpt-card-header">
                        <div class="rpt-card-title"><i class="fa fa-table" style="color:#64748b;"></i> Preferred-Doctor Change Log</div>
                    </div>
                    <div class="rpt-card-body" style="overflow-x:auto;">
                        <table class="table rpt-table" id="pd_table" style="width:100%;">
                            <thead><tr>
                                <th>Date</th><th>Owner</th><th>Scope</th><th>From</th><th>To</th>
                                <th>Changed By</th><th>Source</th><th>Reason</th>
                            </tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div id="pd_empty" class="rpt-card" style="display:none;">
                <div class="rpt-card-body text-center text-muted" style="padding:40px;">
                    <i class="fa fa-user-md fa-3x" style="opacity:.3;"></i>
                    <p style="margin-top:10px;">No preferred-doctor changes in this period.</p>
                </div>
            </div>
        </div>

        {{-- Review Modal --}}
        <div class="modal fade" id="evalReviewModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                        <h4 class="modal-title">Mark Evaluation as Reviewed</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="review_eval_id">
                        <p class="text-muted" style="font-size:13px;">
                            Add your management notes for this critical appointment. Saving will record you as the reviewer and timestamp the action.
                        </p>
                        <div class="form-group">
                            <label>Review notes</label>
                            <textarea id="review_notes" class="form-control" rows="4" placeholder="Action taken, follow-up steps, etc."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-success" id="btn_save_review"><i class="fa fa-check"></i> Mark Reviewed</button>
                    </div>
                </div>
            </div>
        </div>

    </div>{{-- /rpt-content --}}
</div>{{-- /rpt-layout --}}

</section>
@endsection

@section('javascript')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
var aptUrl     = '{{ route('vc.reports.appointments') }}';
var vaxUrl     = '{{ route('vc.reports.vaccinations-due') }}';
var petRegUrl  = '{{ route('vc.reports.pet-registrations') }}';
var docUrl     = '{{ route('vc.reports.doctor-activity') }}';
var evalUrl    = '{{ route('vc.reports.evaluations') }}';
var evalCanReview = {{ auth()->user()->can('vet_clinic.review_evaluations') ? 'true' : 'false' }};
var timeUrl    = '{{ route('vc.reports.time-tracking') }}';
var geoUrl     = '{{ route('vc.reports.owner-geography') }}';
var visitsUrl  = '{{ route('vc.reports.visit-patterns') }}';
var inactiveUrl= '{{ route('vc.reports.inactive-owners') }}';
var prefDocUrl = '{{ route('vc.reports.preferred-doctor-changes') }}';

var TYPE_COLORS   = ['#3b82f6','#22c55e','#ef4444','#f59e0b','#8b5cf6','#06b6d4','#ec4899'];
var STATUS_COLORS = { completed:'#22c55e', pending:'#f59e0b', confirmed:'#3b82f6', in_progress:'#8b5cf6', cancelled:'#ef4444', no_show:'#94a3b8' };

// Chart instances
var _charts = {};
function _destroyChart(key) { if (_charts[key]) { _charts[key].destroy(); delete _charts[key]; } }

// ── Report date pickers ────────────────────────────────────
function initRptDatepicker(displayId, isoId) {
    var $disp = $('#' + displayId);
    var $iso  = $('#' + isoId);
    var defaultIso = $iso.val();

    $disp.datepicker({
        todayHighlight: true, autoclose: true, format: datepicker_date_format
    }).on('changeDate', function(e) {
        if (e.dates.length) {
            var d = e.dates[0];
            $iso.val(d.getFullYear() + '-' +
                String(d.getMonth()+1).padStart(2,'0') + '-' +
                String(d.getDate()).padStart(2,'0'));
        }
    });

    if (defaultIso) {
        var p = defaultIso.split('-');
        $disp.datepicker('setDate', new Date(+p[0], +p[1]-1, +p[2]));
    }
}

$(function() {
    initRptDatepicker('apt_from_display',     'apt_from');
    initRptDatepicker('apt_to_display',       'apt_to');
    initRptDatepicker('pet_reg_from_display', 'pet_reg_from');
    initRptDatepicker('pet_reg_to_display',   'pet_reg_to');
    initRptDatepicker('doc_from_display',     'doc_from');
    initRptDatepicker('doc_to_display',       'doc_to');
    initRptDatepicker('eval_from_display',    'eval_from');
    initRptDatepicker('eval_to_display',      'eval_to');
    initRptDatepicker('tt_from_display',      'tt_from');
    initRptDatepicker('tt_to_display',        'tt_to');
    initRptDatepicker('vp_from_display',      'vp_from');
    initRptDatepicker('vp_to_display',        'vp_to');
    initRptDatepicker('pd_from_display',      'pd_from');
    initRptDatepicker('pd_to_display',        'pd_to');
});

// Section nav
$('.rpt-nav-item').on('click', function(e) {
    // Items with no data-section but a real href (like the Medical Critical
    // Check link added in item 4.1) should NAVIGATE normally - they have
    // their own server-rendered page, they're not in-page panels. Skip
    // preventDefault for those.
    var sec = $(this).data('section');
    if (!sec) return; // let the browser follow the href
    e.preventDefault();
    $('.rpt-nav-item').removeClass('active');
    $(this).addClass('active');
    $('.rpt-section').removeClass('active');
    $('#' + sec).addClass('active');
});

/* ══════════════════════════════════════════════════════════
   APPOINTMENTS
══════════════════════════════════════════════════════════ */
$('.select2').select2({ width: '100%' });

$('#btn_load_appointments').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(aptUrl, {
        from:          $('#apt_from').val(),
        to:            $('#apt_to').val(),
        doctor_id:     $('#apt_doctor_id').val(),
        department_id: $('#apt_department_id').val(),
        type:          $('#apt_type').val(),
        status:        $('#apt_status').val()
    }, function (d) {
        $('#apt_total').text(d.total);
        $('#apt_completed').text(d.completed);
        $('#apt_pending').text(d.pending);
        $('#apt_in_progress').text(d.in_progress);
        $('#apt_cancelled').text(d.cancelled);
        $('#apt_results_wrap').show();

        // Charts
        _destroyChart('type'); _destroyChart('doctor'); _destroyChart('status'); _destroyChart('timeline'); _destroyChart('dept');

        _charts.type = new Chart($('#chart_by_type')[0], {
            type: 'doughnut',
            data: { labels: d.by_type.labels, datasets: [{ data: d.by_type.values, backgroundColor: TYPE_COLORS }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });
        _charts.doctor = new Chart($('#chart_by_doctor')[0], {
            type: 'bar',
            data: { labels: d.by_doctor.labels, datasets: [{ label: 'Appointments', data: d.by_doctor.values, backgroundColor: '#3b82f6', borderRadius: 5 }] },
            options: { indexAxis: 'y', plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true, ticks: { precision: 0 } } } }
        });
        _charts.status = new Chart($('#chart_by_status')[0], {
            type: 'doughnut',
            data: { labels: d.by_status.labels, datasets: [{ data: d.by_status.values, backgroundColor: TYPE_COLORS }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });
        _charts.timeline = new Chart($('#chart_timeline')[0], {
            type: 'line',
            data: { labels: d.timeline.labels, datasets: [{ label: 'Appointments', data: d.timeline.values, borderColor: '#22c55e', backgroundColor: 'rgba(34,197,94,.1)', fill: true, tension: .35, pointRadius: 3 }] },
            options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
        });
        _charts.dept = new Chart($('#chart_by_dept')[0], {
            type: 'bar',
            data: { labels: d.by_dept.labels, datasets: [{ data: d.by_dept.values, backgroundColor: '#8b5cf6', borderRadius: 5 }] },
            options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
        });

        // Table
        var statBadge = { completed:'#22c55e', pending:'#f59e0b', confirmed:'#3b82f6', in_progress:'#8b5cf6', cancelled:'#ef4444', no_show:'#94a3b8' };
        var html = d.rows.length ? '' : '<tr><td colspan="8" class="text-center text-muted" style="padding:20px;">No records found.</td></tr>';
        $.each(d.rows, function(i, r) {
            var clr = statBadge[r.status_raw] || '#94a3b8';
            html += '<tr>';
            html += '<td style="white-space:nowrap;">' + r.date + '</td>';
            html += '<td>' + r.time + '</td>';
            html += '<td><code>' + r.ref + '</code></td>';
            html += '<td style="font-weight:600;">' + r.pet + '</td>';
            html += '<td>' + r.doctor + '</td>';
            html += '<td>' + r.type + '</td>';
            html += '<td><span class="badge" style="background:' + clr + ';font-size:10px;">' + r.status + '</span></td>';
            html += '<td><a href="' + r.url + '" target="_blank" class="btn btn-xs btn-info"><i class="fa fa-eye"></i></a></td>';
            html += '</tr>';
        });
        $('#apt_table_body').html(html);
    }).always(function(){ $btn.prop('disabled', false); });
});

/* ══════════════════════════════════════════════════════════
   VACCINATIONS DUE
══════════════════════════════════════════════════════════ */
$('#btn_load_vaccinations').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(vaxUrl, {
        days:            $('#vax_days').val(),
        vaccine_type_id: $('#vax_type_id').val(),
        species:         $('#vax_species').val()
    }, function (d) {
        $('#vax_total_overdue').text(d.stats.overdue);
        $('#vax_total_due').text(d.stats.due);
        $('#vax_total').text(d.stats.total);
        $('#vax_results_wrap').show();

        var html = d.results.length ? '' : '<tr><td colspan="8" class="text-center text-muted" style="padding:30px;">No records found.</td></tr>';
        $.each(d.results, function(i, r) {
            var rowBg = r.is_overdue ? 'rgba(239,68,68,.04)' : '';
            html += '<tr style="background:' + rowBg + ';">';
            html += '<td><a href="' + r.pet_url + '" style="font-weight:700;">' + r.pet_name + '</a></td>';
            html += '<td>' + r.species + '</td>';
            html += '<td>' + r.owner_name + '</td>';
            html += '<td style="font-size:11px;">' + r.owner_mobile + '</td>';
            html += '<td>' + r.vaccine_name + '</td>';
            html += '<td>' + r.administered_date + '</td>';
            html += '<td style="font-weight:600;">' + r.next_due_date + '</td>';
            html += '<td>' + r.due_badge + '</td>';
            html += '</tr>';
        });
        $('#vax_report_body').html(html);
    }).always(function(){ $btn.prop('disabled', false); });
});

/* ══════════════════════════════════════════════════════════
   PET REGISTRATIONS
══════════════════════════════════════════════════════════ */
$('#btn_load_pet_reg').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(petRegUrl, { from: $('#pet_reg_from').val(), to: $('#pet_reg_to').val() }, function (d) {
        $('#pet_reg_period_total').text(d.total_in_period + ' registered');
        $('#pet_reg_results').show();

        _destroyChart('petTimeline'); _destroyChart('petSpecies'); _destroyChart('petAge');

        // Build multi-line or stacked dataset
        var lineDatasets = d.datasets.map(function(ds, i) {
            return {
                label: ds.label,
                data: ds.data,
                borderColor: ds.color,
                backgroundColor: ds.color + '22',
                fill: false, tension: .35, pointRadius: 3
            };
        });
        _charts.petTimeline = new Chart($('#chart_pet_timeline')[0], {
            type: 'line',
            data: { labels: d.months, datasets: lineDatasets },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
        });

        var spLabels = Object.keys(d.species_counts).map(function(k){ return k.charAt(0).toUpperCase()+k.slice(1); });
        var spValues = Object.values(d.species_counts);
        _charts.petSpecies = new Chart($('#chart_pet_species')[0], {
            type: 'doughnut',
            data: { labels: spLabels, datasets: [{ data: spValues, backgroundColor: TYPE_COLORS }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });

        var ag = d.age_groups || {};
        _charts.petAge = new Chart($('#chart_pet_age')[0], {
            type: 'bar',
            data: {
                labels: ['< 1 yr (Puppy/Kitten)', '1–3 yrs (Young)', '4–7 yrs (Adult)', '> 7 yrs (Senior)'],
                datasets: [{ data: [ag.puppy||0, ag.young||0, ag.adult||0, ag.senior||0], backgroundColor: ['#22c55e','#3b82f6','#f59e0b','#94a3b8'], borderRadius: 5 }]
            },
            options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }
        });
    }).always(function(){ $btn.prop('disabled', false); });
});

/* ══════════════════════════════════════════════════════════
   DOCTOR ACTIVITY
══════════════════════════════════════════════════════════ */
$('#btn_load_doctors').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(docUrl, { from: $('#doc_from').val(), to: $('#doc_to').val() }, function (d) {
        if (!d.length) {
            $('#doc_results').show();
            $('#doc_perf_list').html('<p class="text-muted text-center" style="padding:20px;">No data found for selected period.</p>');
            return;
        }
        $('#doc_results').show();

        _destroyChart('docApts'); _destroyChart('docRate');

        _charts.docApts = new Chart($('#chart_doc_apts')[0], {
            type: 'bar',
            data: {
                labels: d.map(function(r){ return r.doctor; }),
                datasets: [
                    { label: 'Completed',   data: d.map(function(r){ return r.completed; }),   backgroundColor: '#22c55e', borderRadius: 4 },
                    { label: 'Pending',     data: d.map(function(r){ return r.pending; }),     backgroundColor: '#f59e0b', borderRadius: 4 },
                    { label: 'In Progress', data: d.map(function(r){ return r.in_progress; }), backgroundColor: '#8b5cf6', borderRadius: 4 },
                    { label: 'Cancelled',   data: d.map(function(r){ return r.cancelled; }),   backgroundColor: '#ef4444', borderRadius: 4 },
                ]
            },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } }, scales: { x: { stacked: true }, y: { stacked: true, beginAtZero: true, ticks: { precision: 0 } } } }
        });
        _charts.docRate = new Chart($('#chart_doc_rate')[0], {
            type: 'bar',
            data: {
                labels: d.map(function(r){ return r.doctor; }),
                datasets: [{ label: 'Completion %', data: d.map(function(r){ return r.completion_rate; }), backgroundColor: '#22c55e', borderRadius: 5 }]
            },
            options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, max: 100, ticks: { callback: function(v){ return v+'%'; } } } } }
        });

        var html = '';
        d.forEach(function(r) {
            var clr = r.completion_rate >= 80 ? '#22c55e' : (r.completion_rate >= 50 ? '#f59e0b' : '#ef4444');
            html += '<div class="doctor-row">';
            html += '  <div style="width:36px;height:36px;border-radius:50%;background:' + clr + '22;display:flex;align-items:center;justify-content:center;flex-shrink:0;">';
            html += '    <i class="fas fa-user-md" style="color:' + clr + ';font-size:15px;"></i>';
            html += '  </div>';
            html += '  <div style="flex:1;min-width:0;">';
            html += '    <div style="font-size:13px;font-weight:700;color:#1e293b;">' + r.doctor + '</div>';
            html += '    <div style="font-size:11px;color:#94a3b8;">' + r.specialization + '</div>';
            html += '  </div>';
            html += '  <div style="display:flex;gap:14px;font-size:12px;color:#64748b;margin:0 16px;">';
            html += '    <span title="Total"><strong style="color:#1e293b;">' + r.total + '</strong> Total</span>';
            html += '    <span title="Completed"><strong style="color:#22c55e;">' + r.completed + '</strong> Done</span>';
            html += '    <span title="Cancelled"><strong style="color:#ef4444;">' + r.cancelled + '</strong> Cancelled</span>';
            html += '  </div>';
            html += '  <div style="width:180px;">';
            html += '    <div style="font-size:10px;color:#94a3b8;margin-bottom:3px;text-align:right;">' + r.completion_rate + '% completion</div>';
            html += '    <div class="progress-bar-track"><div class="progress-bar-fill" style="width:' + r.completion_rate + '%;background:' + clr + ';"></div></div>';
            html += '  </div>';
            html += '</div>';
        });
        $('#doc_perf_list').html(html);
    }).always(function(){ $btn.prop('disabled', false); });
});

/* ══════════════════════════════════════════════════════════
   EVALUATIONS
══════════════════════════════════════════════════════════ */
function ratingBadge(v) {
    if (v === null || v === undefined || v === '—') return '<span class="text-muted">—</span>';
    var n = parseFloat(v);
    var color = n >= 4 ? '#16a34a' : (n >= 3 ? '#f59e0b' : '#dc2626');
    return '<span style="font-weight:700;color:' + color + ';">' + n.toFixed(2) + '<small style="opacity:.7;font-weight:400;"> /5</small></span>';
}

$('#btn_load_evaluations').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(evalUrl, {
        from:        $('#eval_from').val(),
        to:          $('#eval_to').val(),
        doctor_id:   $('#eval_doctor_id').val(),
        category:    $('#eval_category').val(),
    }, function (d) {
        if (!d.stats.total) {
            $('#eval_results').hide();
            $('#eval_empty').show();
            return;
        }
        $('#eval_empty').hide();
        $('#eval_results').show();

        $('#eval_sum_total').text(d.stats.total);
        $('#eval_sum_flagged').text(d.stats.flagged);
        $('#eval_sum_reviewed').text(d.stats.reviewed);
        $('#eval_sum_pending_review').text(Math.max(0, d.stats.pending_review));

        // Doctor avg chart (horizontal bar of overall avg)
        _destroyChart('eval_doctor');
        var docLabels = d.by_doctor.map(function (r) { return r.doctor_name; });
        var docVals   = d.by_doctor.map(function (r) { return r.overall_avg || 0; });
        var docColors = d.by_doctor.map(function (r) {
            var v = r.overall_avg || 0;
            return v >= 4 ? '#16a34a' : (v >= 3 ? '#f59e0b' : '#dc2626');
        });
        _charts.eval_doctor = new Chart(document.getElementById('chart_eval_doctor').getContext('2d'), {
            type: 'bar',
            data: {
                labels: docLabels,
                datasets: [{ label: 'Avg rating (/5)', data: docVals, backgroundColor: docColors }]
            },
            options: {
                indexAxis: 'y',
                scales: { x: { beginAtZero: true, max: 5 } },
                plugins: { legend: { display: false } }
            }
        });

        // Category pie
        _destroyChart('eval_category');
        var catLabels = [], catVals = [], catColors = [];
        ['pet_owner', 'clinic'].forEach(function (k) {
            if (d.by_category[k]) {
                catLabels.push(k === 'pet_owner' ? 'Pet Owner Eval' : 'Clinic / Doctor Eval');
                catVals.push(d.by_category[k].count);
                catColors.push(k === 'pet_owner' ? '#5b8def' : '#f39c12');
            }
        });
        _charts.eval_category = new Chart(document.getElementById('chart_eval_category').getContext('2d'), {
            type: 'doughnut',
            data: { labels: catLabels, datasets: [{ data: catVals, backgroundColor: catColors }] },
            options: { plugins: { legend: { position: 'bottom' } } }
        });

        // Per-doctor table
        var $tb = $('#eval_doctor_table tbody').empty();
        d.by_doctor.forEach(function (r) {
            $tb.append(
                '<tr>' +
                '<td><strong>' + r.doctor_name + '</strong></td>' +
                '<td class="text-center">' + r.evals_total + '</td>' +
                '<td class="text-center">' + ratingBadge(r.pet_owner_avg) + '</td>' +
                '<td class="text-center">' + ratingBadge(r.clinic_avg) + '</td>' +
                '<td class="text-center">' + ratingBadge(r.overall_avg) + '</td>' +
                '<td class="text-center">' +
                    (r.flagged > 0
                        ? '<span class="label label-danger">' + r.flagged + '</span>'
                        : '<span class="text-muted">0</span>') +
                '</td>' +
                '</tr>'
            );
        });

        // Critical table
        var $ct = $('#eval_critical_table tbody').empty();
        if (!d.critical.length) {
            $ct.append('<tr><td colspan="9" class="text-center text-muted" style="padding:20px;">No flagged appointments — great work!</td></tr>');
        } else {
            d.critical.forEach(function (r) {
                var status = r.reviewed
                    ? '<span class="label label-success" title="By ' + (r.reviewed_by || '—') + ' on ' + (r.reviewed_at || '') + '">' +
                          '<i class="fa fa-check"></i> Reviewed</span>'
                    : '<span class="label label-warning">Pending review</span>';
                var actions = '<div style="display:inline-flex;gap:5px;align-items:center;">';
                actions += '<a href="' + r.apt_url + '" class="eval-act-btn eval-act-open" title="Open appointment" target="_blank"><i class="fa fa-external-link-alt"></i></a>';
                if (evalCanReview && !r.reviewed) {
                    actions += '<button class="eval-act-btn eval-act-review btn-mark-reviewed" data-id="' + r.id + '" title="Mark as reviewed"><i class="fa fa-check"></i> Review</button>';
                }
                actions += '</div>';
                $ct.append(
                    '<tr>' +
                    '<td>' + r.date + '</td>' +
                    '<td><strong>' + r.ref + '</strong></td>' +
                    '<td>' + r.category + '</td>' +
                    '<td>' + r.pet + '</td>' +
                    '<td>' + r.owner + '</td>' +
                    '<td>' + r.doctor + '</td>' +
                    '<td class="text-center">' + ratingBadge(r.avg_rating) + '</td>' +
                    '<td class="text-center">' + status + '</td>' +
                    '<td class="text-center">' + actions + '</td>' +
                    '</tr>'
                );
            });
        }
    }).always(function () { $btn.prop('disabled', false); });
});

// Mark reviewed handler
$(document).on('click', '.btn-mark-reviewed', function () {
    $('#review_eval_id').val($(this).data('id'));
    $('#review_notes').val('');
    $('#evalReviewModal').modal('show');
});

$('#btn_save_review').on('click', function () {
    var id = $('#review_eval_id').val();
    if (!id) return;
    var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
    $.post('{{ url('vet-clinic/evaluations') }}/' + id + '/review', {
        _token: '{{ csrf_token() }}',
        review_notes: $('#review_notes').val()
    }).done(function (res) {
        if (res.success) {
            toastr.success(res.msg);
            $('#evalReviewModal').modal('hide');
            $('#btn_load_evaluations').click();
        }
    }).fail(function (xhr) { toastr.error(xhr.responseJSON?.msg ?? 'Failed'); })
    .always(function () { $btn.prop('disabled', false).html('<i class="fa fa-check"></i> Mark Reviewed'); });
});

/* ══════════════════════════════════════════════════════════
   TIME TRACKING
══════════════════════════════════════════════════════════ */
function fmtMins(m) {
    if (m === null || m === undefined) return '<span class="text-muted">—</span>';
    if (m < 60) return m + ' min';
    return Math.floor(m / 60) + 'h ' + (m % 60) + 'm';
}

$('#btn_load_time').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(timeUrl, {
        from:          $('#tt_from').val(),
        to:            $('#tt_to').val(),
        doctor_id:     $('#tt_doctor_id').val(),
        department_id: $('#tt_department_id').val()
    }, function (d) {
        if (!d.stats.total_visits) {
            $('#tt_results').hide();
            $('#tt_empty').show();
            return;
        }
        $('#tt_empty').hide();
        $('#tt_results').show();

        $('#tt_total').text(d.stats.total_visits);
        $('#tt_avg_wait').text(d.stats.avg_waiting);
        $('#tt_max_wait').text(d.stats.max_waiting);
        $('#tt_avg_consult').text(d.stats.avg_consult);
        $('#tt_max_consult').text(d.stats.max_consult);

        // Per-doctor grouped bar chart
        _destroyChart('tt_doctor');
        _charts.tt_doctor = new Chart(document.getElementById('chart_tt_doctor').getContext('2d'), {
            type: 'bar',
            data: {
                labels: d.by_doctor.map(function (r) { return r.doctor; }),
                datasets: [
                    { label: 'Avg waiting (min)',      data: d.by_doctor.map(function (r) { return r.avg_waiting; }), backgroundColor: '#f59e0b' },
                    { label: 'Avg consultation (min)', data: d.by_doctor.map(function (r) { return r.avg_consult; }), backgroundColor: '#2563eb' }
                ]
            },
            options: { scales: { y: { beginAtZero: true } }, plugins: { legend: { position: 'bottom' } } }
        });

        // Waiting distribution
        _destroyChart('tt_dist');
        _charts.tt_dist = new Chart(document.getElementById('chart_tt_dist').getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: d.distribution.labels.map(function (l) { return l + ' min'; }),
                datasets: [{
                    data: d.distribution.values,
                    backgroundColor: ['#22c55e','#84cc16','#f59e0b','#f97316','#ef4444','#b91c1c']
                }]
            },
            options: { plugins: { legend: { position: 'bottom' } } }
        });

        // Detail table
        var $tb = $('#tt_table tbody').empty();
        d.rows.forEach(function (r) {
            $tb.append(
                '<tr>' +
                '<td>' + r.date + '</td>' +
                '<td><strong>' + r.ref + '</strong></td>' +
                '<td>' + r.pet + '</td>' +
                '<td>' + r.doctor + '</td>' +
                '<td class="text-center">' + r.arrived + '</td>' +
                '<td class="text-center">' + r.started + '</td>' +
                '<td class="text-center">' + r.ended + '</td>' +
                '<td class="text-center" style="font-weight:700;color:#d97706;">' + fmtMins(r.waiting) + '</td>' +
                '<td class="text-center" style="font-weight:700;color:#2563eb;">' + fmtMins(r.consult) + '</td>' +
                '<td class="text-center"><a href="' + r.url + '" target="_blank" class="eval-act-btn eval-act-open" title="Open appointment"><i class="fa fa-external-link-alt"></i></a></td>' +
                '</tr>'
            );
        });
    }).always(function () { $btn.prop('disabled', false); });
});

/* ══════════════════════════════════════════════════════════
   NEW REPORTS — shared helper
══════════════════════════════════════════════════════════ */
function esc(s) { return $('<div>').text(s == null ? '' : s).html(); }

/* ── 1.1 Owner Geography ─────────────────────────────────── */
$('#btn_load_geo').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(geoUrl, {
        country: $('#geo_country').val(),
        state:   $('#geo_state').val(),
        city:    $('#geo_city').val(),
        search:  $('#geo_search').val()
    }, function (d) {
        if (!d.stats.total_owners) { $('#geo_results').hide(); $('#geo_empty').show(); return; }
        $('#geo_empty').hide(); $('#geo_results').show();
        $('#geo_total').text(d.stats.total_owners);
        $('#geo_with_addr').text(d.stats.with_address);
        $('#geo_areas').text(d.stats.areas);
        $('#geo_highest').text(d.highest ? (d.highest.name + ' (' + d.highest.count + ')') : '—');
        $('#geo_lowest').text(d.lowest ? (d.lowest.name + ' (' + d.lowest.count + ')') : '—');

        _destroyChart('geo_city');
        var cities = d.by_city.slice(0, 15);
        _charts.geo_city = new Chart($('#chart_geo_city')[0], {
            type: 'bar',
            data: { labels: cities.map(function (c) { return c.name; }),
                    datasets: [{ label: 'Owners', data: cities.map(function (c) { return c.count; }), backgroundColor: '#0d9488', borderRadius: 5 }] },
            options: { indexAxis: 'y', plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true, ticks: { precision: 0 } } } }
        });
        _destroyChart('geo_country');
        _charts.geo_country = new Chart($('#chart_geo_country')[0], {
            type: 'doughnut',
            data: { labels: d.by_country.map(function (c) { return c.name; }),
                    datasets: [{ data: d.by_country.map(function (c) { return c.count; }), backgroundColor: TYPE_COLORS }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });

        var $tb = $('#geo_table tbody').empty();
        d.rows.forEach(function (r) {
            $tb.append('<tr>' +
                '<td style="font-weight:600;">' + esc(r.name) + '</td>' +
                '<td>' + esc(r.mobile) + '</td>' +
                '<td>' + esc(r.address || '—') + '</td>' +
                '<td>' + esc(r.city) + '</td>' +
                '<td>' + esc(r.state) + '</td>' +
                '<td>' + esc(r.country) + '</td>' +
                '<td>' + esc(r.zip) + '</td>' +
                '<td class="text-center"><span class="badge" style="background:#0d9488;">' + r.pets + '</span></td>' +
                '</tr>');
        });
    }).always(function () { $btn.prop('disabled', false); });
});

/* ── 1.2 Visit Patterns ──────────────────────────────────── */
$('#btn_load_visits').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(visitsUrl, { from: $('#vp_from').val(), to: $('#vp_to').val(), doctor_id: $('#vp_doctor_id').val() }, function (d) {
        if (!d.stats.owners) { $('#vp_results').hide(); $('#vp_empty').show(); return; }
        $('#vp_empty').hide(); $('#vp_results').show();
        $('#vp_owners').text(d.stats.owners);
        $('#vp_repeat').text(d.stats.repeat);
        $('#vp_one_time').text(d.stats.one_time);
        $('#vp_high_risk').text(d.stats.high_risk);

        _destroyChart('vp_att');
        _charts.vp_att = new Chart($('#chart_vp_attendance')[0], {
            type: 'doughnut',
            data: { labels: ['Completed (on schedule)', 'Missed (cancelled / no-show)', 'Other (pending etc.)'],
                    datasets: [{ data: [d.attendance.completed, d.attendance.missed, d.attendance.other], backgroundColor: ['#22c55e', '#ef4444', '#94a3b8'] }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });
        _destroyChart('vp_rep');
        _charts.vp_rep = new Chart($('#chart_vp_repeat')[0], {
            type: 'doughnut',
            data: { labels: ['Repeat visitors', 'One-time only'],
                    datasets: [{ data: [d.repeat_split.repeat, d.repeat_split.one_time], backgroundColor: ['#9333ea', '#cbd5e1'] }] },
            options: { plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } } }
        });

        var $ct = $('#vp_cancel_table tbody').empty();
        if (!d.top_cancellers.length) {
            $ct.append('<tr><td colspan="6" class="text-center text-muted" style="padding:16px;">No cancellations or no-shows in this period.</td></tr>');
        }
        d.top_cancellers.forEach(function (r) {
            $ct.append('<tr>' +
                '<td style="font-weight:600;">' + esc(r.owner) + '</td>' +
                '<td>' + esc(r.mobile) + '</td>' +
                '<td class="text-center">' + r.total + '</td>' +
                '<td class="text-center">' + r.cancelled + '</td>' +
                '<td class="text-center">' + r.no_show + '</td>' +
                '<td class="text-center"><span class="badge" style="background:#ef4444;">' + r.missed + '</span></td>' +
                '</tr>');
        });

        var $tb = $('#vp_table tbody').empty();
        d.rows.forEach(function (r) {
            var rateClr = r.attendance_rate >= 70 ? '#22c55e' : (r.attendance_rate >= 40 ? '#f59e0b' : '#ef4444');
            $tb.append('<tr>' +
                '<td style="font-weight:600;">' + esc(r.owner) + '</td>' +
                '<td class="text-center">' + r.total + '</td>' +
                '<td class="text-center">' + r.completed + '</td>' +
                '<td class="text-center">' + r.cancelled + '</td>' +
                '<td class="text-center">' + r.no_show + '</td>' +
                '<td class="text-center" style="font-weight:700;color:' + rateClr + ';">' + r.attendance_rate + '%</td>' +
                '<td class="text-center">' + (r.is_repeat ? '<span class="label label-success">Repeat</span>' : '<span class="label label-default">Once</span>') + '</td>' +
                '</tr>');
        });
    }).always(function () { $btn.prop('disabled', false); });
});

/* ── 1.3 Inactive Owners ─────────────────────────────────── */
$('#btn_load_inactive').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(inactiveUrl, { days: $('#ina_days').val() }, function (d) {
        if (!d.stats.total) { $('#ina_results').hide(); $('#ina_empty').show(); return; }
        $('#ina_empty').hide(); $('#ina_results').show();
        $('#ina_total').text(d.stats.total);
        $('#ina_lapsed').text(d.stats.lapsed);
        $('#ina_never').text(d.stats.never);
        var $tb = $('#ina_table tbody').empty();
        d.rows.forEach(function (r) {
            var days = r.never
                ? '<span class="label label-danger">Never visited</span>'
                : '<span style="font-weight:700;color:#b91c1c;">' + r.days_since + ' days</span>';
            $tb.append('<tr>' +
                '<td style="font-weight:600;">' + esc(r.owner) + '</td>' +
                '<td>' + esc(r.mobile) + '</td>' +
                '<td>' + esc(r.email) + '</td>' +
                '<td class="text-center"><span class="badge" style="background:#8b5cf6;">' + r.active_pets + '</span></td>' +
                '<td>' + (r.last_visit || '<span class="text-muted">—</span>') + '</td>' +
                '<td class="text-center">' + days + '</td>' +
                '</tr>');
        });
    }).always(function () { $btn.prop('disabled', false); });
});

/* ── 1.4 Preferred-Doctor Changes ────────────────────────── */
$('#btn_load_pref_doctor').on('click', function () {
    var $btn = $(this).prop('disabled', true);
    $.get(prefDocUrl, { from: $('#pd_from').val(), to: $('#pd_to').val(), doctor_id: $('#pd_doctor_id').val() }, function (d) {
        if (!d.stats.total) { $('#pd_results').hide(); $('#pd_empty').show(); return; }
        $('#pd_empty').hide(); $('#pd_results').show();
        $('#pd_total').text(d.stats.total);
        $('#pd_owner_level').text(d.stats.owner_level);
        $('#pd_pet_level').text(d.stats.pet_level);
        $('#pd_via_request').text(d.stats.via_request);

        var $ot = $('#pd_owner_table tbody').empty();
        if (!d.by_owner.length) {
            $ot.append('<tr><td colspan="2" class="text-center text-muted" style="padding:16px;">No owner changed their preferred doctor more than once.</td></tr>');
        }
        d.by_owner.forEach(function (r) {
            $ot.append('<tr><td style="font-weight:600;">' + esc(r.owner) + '</td>' +
                '<td class="text-center"><span class="badge" style="background:#d946ef;">' + r.changes + '</span></td></tr>');
        });

        var $tb = $('#pd_table tbody').empty();
        d.rows.forEach(function (r) {
            var srcBadge = r.source === 'Approved request'
                ? '<span class="label label-primary">' + esc(r.source) + '</span>'
                : '<span class="label label-default">' + esc(r.source) + '</span>';
            $tb.append('<tr>' +
                '<td style="white-space:nowrap;">' + esc(r.date) + '</td>' +
                '<td style="font-weight:600;">' + esc(r.owner) + '</td>' +
                '<td>' + esc(r.scope) + '</td>' +
                '<td>' + esc(r.from) + '</td>' +
                '<td style="font-weight:600;">' + esc(r.to) + '</td>' +
                '<td>' + esc(r.by) + '</td>' +
                '<td>' + srcBadge + '</td>' +
                '<td>' + esc(r.reason) + '</td>' +
                '</tr>');
        });
    }).always(function () { $btn.prop('disabled', false); });
});
</script>
@endsection
