{{-- Ophthalmology panel, injected into ClinicCore's patient show AND appointment
     screens via the SpecialtyDriverRegistry.
       - patient show fragment -> receives $patient
       - appointment fragment  -> receives $patient + $appointment
     Contains: the at-a-glance eye profile (unchanged), a per-visit OD/OS exam
     entry form, an IOP trend (last N exams, table + sparkline), a diabetic-
     retinopathy grade badge with referral hint at R2+, target-IOP display, and
     glasses-Rx entry with a print link. All writes go through this module's own
     AJAX endpoints. --}}
@php
    use Modules\OphthalmologyClinic\Entities\OpthEyeExam;
    use Modules\OphthalmologyClinic\Entities\OpthGlassesRx;

    $ophth       = \Modules\OphthalmologyClinic\Entities\OphthPatientProfile::where('clc_patient_id', $patient->id)->first();
    $oCanExams   = auth()->user() && auth()->user()->can('opth.exams.manage');
    $oCanGlasses = auth()->user() && auth()->user()->can('opth.glasses_rx.manage');
    $oApptId     = isset($appointment) ? $appointment->id : null;

    $oExams = OpthEyeExam::where('business_id', $patient->business_id)
        ->where('patient_id', $patient->id)
        ->orderBy('examined_at')->orderBy('id')->get();
    $oLatest = $oExams->last();

    $oGlasses = OpthGlassesRx::where('business_id', $patient->business_id)
        ->where('patient_id', $patient->id)
        ->orderByDesc('prescribed_at')->orderByDesc('id')->get();

    $oUid = 'ophth' . $patient->id;
    $iopHi = fn($v) => $v !== null && $v > 21;
@endphp

{{-- ── At-a-glance eye profile (unchanged behaviour) ── --}}
@if($ophth && ($ophth->va_right || $ophth->va_left || $ophth->iop_right || $ophth->iop_left
    || $ophth->sphere_right !== null || $ophth->sphere_left !== null))
<div class="detail-row" style="display:block;">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-eye fa-fw"></i> Eye Profile</span>
    <table style="width:100%;font-size:11px;border-collapse:collapse;">
        <tr style="color:#64748b;"><td></td><td style="text-align:center;">OD (R)</td><td style="text-align:center;">OS (L)</td></tr>
        <tr><td style="color:#64748b;">VA</td><td style="text-align:center;font-weight:600;">{{ $ophth->va_right ?: '—' }}</td><td style="text-align:center;font-weight:600;">{{ $ophth->va_left ?: '—' }}</td></tr>
        <tr><td style="color:#64748b;">Refraction</td><td style="text-align:center;">{{ $ophth->refraction('right') ?: '—' }}</td><td style="text-align:center;">{{ $ophth->refraction('left') ?: '—' }}</td></tr>
        <tr>
            <td style="color:#64748b;">IOP</td>
            <td style="text-align:center;{{ $iopHi($ophth->iop_right) ? 'color:#dc3545;font-weight:700;' : '' }}">{{ $ophth->iop_right !== null ? $ophth->iop_right.' mmHg' : '—' }}</td>
            <td style="text-align:center;{{ $iopHi($ophth->iop_left) ? 'color:#dc3545;font-weight:700;' : '' }}">{{ $ophth->iop_left !== null ? $ophth->iop_left.' mmHg' : '—' }}</td>
        </tr>
        @if($ophth->target_iop_od !== null || $ophth->target_iop_os !== null)
        <tr>
            <td style="color:#64748b;">{{ __('ophthClinic::lang.target_iop') }}</td>
            <td style="text-align:center;color:#64748b;">{{ $ophth->target_iop_od !== null ? $ophth->target_iop_od.' mmHg' : '—' }}</td>
            <td style="text-align:center;color:#64748b;">{{ $ophth->target_iop_os !== null ? $ophth->target_iop_os.' mmHg' : '—' }}</td>
        </tr>
        @endif
    </table>
    @if($ophth->wears_glasses)
        <span class="label label-info" style="font-size:10px;margin-top:4px;display:inline-block;"><i class="fas fa-glasses"></i> Wears glasses</span>
    @endif
    @if($ophth->notes)
        <div style="font-size:11px;color:#475569;margin-top:4px;">{{ $ophth->notes }}</div>
    @endif
</div>
@endif

{{-- ── Glaucoma & DR tracking: IOP trend + DR badge + referral hint ── --}}
@if($oExams->count())
<div class="detail-row" style="display:block;">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-chart-line fa-fw"></i> {{ __('ophthClinic::lang.glaucoma_dr') }}</span>

    {{-- Diabetic-retinopathy grade badge (latest exam) with referral hint at R2+ --}}
    @if($oLatest && ($oLatest->dr_grade_od || $oLatest->dr_grade_os))
        @php $worst = $oLatest->worstDrLevel(); @endphp
        <div style="margin-bottom:6px;font-size:11px;">
            <span style="color:#64748b;">{{ __('ophthClinic::lang.dr_grade') }}:</span>
            <span class="label {{ $worst >= 2 ? 'label-danger' : ($worst == 1 ? 'label-warning' : 'label-default') }}" style="font-size:10px;">OD {{ $oLatest->dr_grade_od ?: '—' }}{{ $oLatest->maculopathy_od ? ' '.$oLatest->maculopathy_od : '' }}</span>
            <span class="label {{ $worst >= 2 ? 'label-danger' : ($worst == 1 ? 'label-warning' : 'label-default') }}" style="font-size:10px;">OS {{ $oLatest->dr_grade_os ?: '—' }}{{ $oLatest->maculopathy_os ? ' '.$oLatest->maculopathy_os : '' }}</span>
            @if($worst >= 2)
                <span class="label label-danger" style="font-size:9px;"><i class="fas fa-exclamation-triangle"></i> {{ __('ophthClinic::lang.referral_suggested') }} (R{{ $worst }}+)</span>
            @endif
        </div>
    @endif

    {{-- Cup:disc ratio (latest exam, read-only). Written by the exam form but was
         never displayed. --}}
    @if($oLatest && ($oLatest->cup_disc_od !== null || $oLatest->cup_disc_os !== null))
        <div style="margin-bottom:6px;font-size:11px;">
            <span style="color:#64748b;">{{ __('ophthClinic::lang.cup_disc') }}:</span>
            <span>OD {{ $oLatest->cup_disc_od !== null ? rtrim(rtrim(number_format($oLatest->cup_disc_od, 2), '0'), '.') : '—' }}</span>
            <span style="margin-left:8px;">OS {{ $oLatest->cup_disc_os !== null ? rtrim(rtrim(number_format($oLatest->cup_disc_os, 2), '0'), '.') : '—' }}</span>
        </div>
    @endif

    {{-- IOP trend: last N exams per eye (table + inline sparkline; table fallback) --}}
    @php
        $recent = $oExams->slice(-8)->values();
        $mkPts = function ($eye) use ($recent) {
            $vals = $recent->map(fn($e) => $e->{"iop_$eye"})->all();
            $pts = [];
            $n = count($vals);
            $has = false;
            foreach ($vals as $i => $v) {
                if ($v === null) continue;
                $has = true;
                $x = $n > 1 ? ($i / ($n - 1) * 100) : 0;
                $y = 20 - min(1, $v / 40) * 18; // scale 0..40 mmHg
                $pts[] = round($x,1).','.round($y,1);
            }
            return $has ? implode(' ', $pts) : '';
        };
        $ptsOd = $mkPts('od');
        $ptsOs = $mkPts('os');
    @endphp
    <table style="width:100%;font-size:11px;border-collapse:collapse;">
        <thead><tr style="color:#64748b;"><th style="text-align:left;">{{ __('ophthClinic::lang.iop_trend') }}</th><th style="text-align:left;">Sparkline</th><th style="text-align:right;">Latest</th></tr></thead>
        <tbody>
            <tr style="border-bottom:1px solid #f1f5f9;">
                <td style="padding:2px 4px;font-weight:600;">OD (R)</td>
                <td style="padding:2px 4px;">@if($ptsOd)<svg viewBox="0 0 100 20" width="90" height="20" preserveAspectRatio="none"><polyline points="{{ $ptsOd }}" fill="none" stroke="#6610f2" stroke-width="1.5"/></svg>@else<span style="color:#94a3b8;">—</span>@endif</td>
                <td style="padding:2px 4px;text-align:right;{{ $iopHi(optional($oLatest)->iop_od) ? 'color:#dc3545;font-weight:700;' : '' }}">{{ optional($oLatest)->iop_od !== null ? $oLatest->iop_od.' mmHg' : '—' }}</td>
            </tr>
            <tr>
                <td style="padding:2px 4px;font-weight:600;">OS (L)</td>
                <td style="padding:2px 4px;">@if($ptsOs)<svg viewBox="0 0 100 20" width="90" height="20" preserveAspectRatio="none"><polyline points="{{ $ptsOs }}" fill="none" stroke="#20c997" stroke-width="1.5"/></svg>@else<span style="color:#94a3b8;">—</span>@endif</td>
                <td style="padding:2px 4px;text-align:right;{{ $iopHi(optional($oLatest)->iop_os) ? 'color:#dc3545;font-weight:700;' : '' }}">{{ optional($oLatest)->iop_os !== null ? $oLatest->iop_os.' mmHg' : '—' }}</td>
            </tr>
        </tbody>
    </table>
    <div style="font-size:9px;color:#94a3b8;margin-top:2px;">{{ $oExams->count() }} exam(s) on record.</div>
</div>
@endif

{{-- ── Per-visit eye exam entry (OD/OS two-column form) ── --}}
@if($oCanExams)
<div class="detail-row" style="display:block;" id="{{ $oUid }}_exam" data-store-url="{{ route('opth.exams.store', $patient->id) }}" data-appointment-id="{{ $oApptId }}">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-eye fa-fw"></i> {{ __('ophthClinic::lang.eye_exam') }}</span>
    <div class="opth-exam-form" style="display:none;padding:10px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
        <table style="width:100%;font-size:11px;" class="table table-sm">
            <thead><tr><th style="width:38%;"></th><th>OD (Right)</th><th>OS (Left)</th></tr></thead>
            <tbody>
                <tr><td><strong>{{ __('ophthClinic::lang.visual_acuity') }} ({{ __('ophthClinic::lang.uncorrected') }})</strong></td>
                    <td><input type="text" class="form-control input-sm o-f" data-f="va_od" placeholder="6/6"></td>
                    <td><input type="text" class="form-control input-sm o-f" data-f="va_os" placeholder="6/6"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.visual_acuity') }} ({{ __('ophthClinic::lang.corrected') }})</strong></td>
                    <td><input type="text" class="form-control input-sm o-f" data-f="va_od_corrected" placeholder="6/6"></td>
                    <td><input type="text" class="form-control input-sm o-f" data-f="va_os_corrected" placeholder="6/6"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.sphere') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="sphere_od" placeholder="±0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="sphere_os" placeholder="±0.00"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.cylinder') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="cylinder_od" placeholder="±0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="cylinder_os" placeholder="±0.00"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.axis') }}</strong></td>
                    <td><input type="number" min="0" max="180" class="form-control input-sm o-f" data-f="axis_od" placeholder="0–180"></td>
                    <td><input type="number" min="0" max="180" class="form-control input-sm o-f" data-f="axis_os" placeholder="0–180"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.add') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="add_od" placeholder="+0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm o-f" data-f="add_os" placeholder="+0.00"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.iop') }}</strong></td>
                    <td><input type="number" step="0.1" class="form-control input-sm o-f" data-f="iop_od" placeholder="10–21"></td>
                    <td><input type="number" step="0.1" class="form-control input-sm o-f" data-f="iop_os" placeholder="10–21"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.cup_disc') }}</strong></td>
                    <td><input type="number" step="0.05" min="0" max="1" class="form-control input-sm o-f" data-f="cup_disc_od" placeholder="0.30"></td>
                    <td><input type="number" step="0.05" min="0" max="1" class="form-control input-sm o-f" data-f="cup_disc_os" placeholder="0.30"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.dr_grade') }}</strong></td>
                    <td><select class="form-control input-sm o-f" data-f="dr_grade_od"><option value="">—</option>@foreach(OpthEyeExam::DR_GRADES as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select></td>
                    <td><select class="form-control input-sm o-f" data-f="dr_grade_os"><option value="">—</option>@foreach(OpthEyeExam::DR_GRADES as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.maculopathy') }}</strong></td>
                    <td><select class="form-control input-sm o-f" data-f="maculopathy_od"><option value="">—</option>@foreach(OpthEyeExam::MACULOPATHY as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select></td>
                    <td><select class="form-control input-sm o-f" data-f="maculopathy_os"><option value="">—</option>@foreach(OpthEyeExam::MACULOPATHY as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select></td></tr>
            </tbody>
        </table>
        <div class="row" style="margin:0 -5px;">
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.iop_method') }}</label>
                <select class="form-control input-sm o-f" data-f="iop_method"><option value="">—</option>@foreach(OpthEyeExam::IOP_METHODS as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select>
            </div>
            <div class="col-xs-8" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.pupils') }}</label>
                <input type="text" class="form-control input-sm o-f" data-f="pupils_note" placeholder="PERRLA, no RAPD…">
            </div>
        </div>
        <div class="row" style="margin:6px -5px 0;">
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.slit_lamp') }}</label>
                <textarea rows="2" class="form-control input-sm o-f" data-f="slit_lamp_notes" placeholder="{{ __('ophthClinic::lang.slit_lamp_placeholder') }}"></textarea>
            </div>
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.fundus') }}</label>
                <textarea rows="2" class="form-control input-sm o-f" data-f="fundus_notes" placeholder="{{ __('ophthClinic::lang.fundus_placeholder') }}"></textarea>
            </div>
        </div>
        <div class="row" style="margin:6px -5px 0;">
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.target_iop') }} OD</label>
                <input type="number" step="0.1" min="0" max="99" class="form-control input-sm o-f" data-f="target_iop_od" placeholder="mmHg"
                       value="{{ optional($ophth)->target_iop_od }}">
            </div>
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.target_iop') }} OS</label>
                <input type="number" step="0.1" min="0" max="99" class="form-control input-sm o-f" data-f="target_iop_os" placeholder="mmHg"
                       value="{{ optional($ophth)->target_iop_os }}">
            </div>
        </div>
        <div style="margin-top:6px;">
            <label style="font-size:11px;">{{ __('ophthClinic::lang.notes') }}</label>
            <input type="text" class="form-control input-sm o-f" data-f="notes">
        </div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px;"><i class="fas fa-info-circle"></i> IOP &gt; 30 mmHg in either eye raises a critical medical alert.</div>
        <div style="margin-top:8px;text-align:right;">
            <button type="button" class="btn btn-xs btn-default opth-exam-cancel">Cancel</button>
            <button type="button" class="btn btn-xs btn-primary opth-exam-save">{{ __('ophthClinic::lang.save') }}</button>
        </div>
    </div>
    <button type="button" class="btn btn-xs btn-default opth-exam-add"><i class="fas fa-plus"></i> {{ __('ophthClinic::lang.record_exam') }}</button>
</div>
@endif

{{-- ── Glasses prescriptions: list + print + new-Rx entry ── --}}
<div class="detail-row" style="display:block;" id="{{ $oUid }}_glasses" data-store-url="{{ route('opth.glasses.store', $patient->id) }}" data-appointment-id="{{ $oApptId }}" data-del-base="{{ url('ophth/patients/'.$patient->id.'/glasses') }}">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-glasses fa-fw"></i> {{ __('ophthClinic::lang.glasses_rx') }}</span>
    @if($oGlasses->count())
        <table style="width:100%;font-size:11px;border-collapse:collapse;">
            <thead><tr style="color:#64748b;"><th style="text-align:left;">{{ __('ophthClinic::lang.date') }}</th><th style="text-align:left;">OD</th><th style="text-align:left;">OS</th><th style="text-align:left;">{{ __('ophthClinic::lang.lens_type') }}</th><th></th></tr></thead>
            <tbody>
            @foreach($oGlasses as $g)
                <tr style="border-bottom:1px solid #f1f5f9;">
                    <td style="padding:2px 4px;">{{ optional($g->prescribed_at)->format('Y-m-d') }}</td>
                    <td style="padding:2px 4px;">{{ OpthGlassesRx::dpt($g->sphere_od) }} / {{ OpthGlassesRx::dpt($g->cylinder_od) }} {{ OpthGlassesRx::axis($g->axis_od) }}</td>
                    <td style="padding:2px 4px;">{{ OpthGlassesRx::dpt($g->sphere_os) }} / {{ OpthGlassesRx::dpt($g->cylinder_os) }} {{ OpthGlassesRx::axis($g->axis_os) }}</td>
                    <td style="padding:2px 4px;">{{ $g->lens_type ? (OpthGlassesRx::LENS_TYPES[$g->lens_type] ?? $g->lens_type) : '—' }}</td>
                    <td style="padding:2px 4px;text-align:right;white-space:nowrap;">
                        <a href="{{ route('opth.glasses.print', [$patient->id, $g->id]) }}" target="_blank" rel="noopener" class="btn btn-xs btn-link" title="{{ __('ophthClinic::lang.print') }}" style="padding:0 4px;"><i class="fas fa-print"></i></a>
                        @if($oCanGlasses)
                            <button type="button" class="btn btn-xs btn-link opth-glasses-del" data-rx="{{ $g->id }}" title="{{ __('ophthClinic::lang.delete') }}" style="padding:0 4px;color:#dc3545;"><i class="fas fa-trash"></i></button>
                        @endif
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    @else
        <div style="font-size:11px;color:#94a3b8;">No prescriptions.</div>
    @endif

    @if($oCanGlasses)
    <div class="opth-glasses-form" style="display:none;margin-top:8px;padding:10px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
        <table style="width:100%;font-size:11px;" class="table table-sm">
            <thead><tr><th style="width:34%;"></th><th>OD</th><th>OS</th></tr></thead>
            <tbody>
                <tr><td><strong>{{ __('ophthClinic::lang.sphere') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="sphere_od" placeholder="±0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="sphere_os" placeholder="±0.00"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.cylinder') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="cylinder_od" placeholder="±0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="cylinder_os" placeholder="±0.00"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.axis') }}</strong></td>
                    <td><input type="number" min="0" max="180" class="form-control input-sm g-f" data-f="axis_od" placeholder="0–180"></td>
                    <td><input type="number" min="0" max="180" class="form-control input-sm g-f" data-f="axis_os" placeholder="0–180"></td></tr>
                <tr><td><strong>{{ __('ophthClinic::lang.add') }}</strong></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="add_od" placeholder="+0.00"></td>
                    <td><input type="number" step="0.25" class="form-control input-sm g-f" data-f="add_os" placeholder="+0.00"></td></tr>
            </tbody>
        </table>
        <div class="row" style="margin:0 -5px;">
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.pd') }}</label>
                <input type="number" step="0.5" class="form-control input-sm g-f" data-f="pd_mm" placeholder="63">
            </div>
            <div class="col-xs-8" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('ophthClinic::lang.lens_type') }}</label>
                <select class="form-control input-sm g-f" data-f="lens_type"><option value="">—</option>@foreach(OpthGlassesRx::LENS_TYPES as $v=>$l)<option value="{{ $v }}">{{ $l }}</option>@endforeach</select>
            </div>
        </div>
        <div style="margin-top:6px;">
            <label style="font-size:11px;">{{ __('ophthClinic::lang.notes') }}</label>
            <input type="text" class="form-control input-sm g-f" data-f="notes">
        </div>
        <div style="margin-top:8px;text-align:right;">
            <button type="button" class="btn btn-xs btn-default opth-glasses-cancel">Cancel</button>
            <button type="button" class="btn btn-xs btn-primary opth-glasses-save">{{ __('ophthClinic::lang.save') }} &amp; {{ __('ophthClinic::lang.print') }}</button>
        </div>
    </div>
    <button type="button" class="btn btn-xs btn-default opth-glasses-add" style="margin-top:6px;"><i class="fas fa-plus"></i> {{ __('ophthClinic::lang.new_glasses_rx') }}</button>
    @endif
</div>

@if($oCanExams || $oCanGlasses)
@once
<script>
(function () {
    var CSRF = '{{ csrf_token() }}';
    function post(url, body) {
        return fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' }, body: JSON.stringify(body || {}) }).then(function (r) { return r.json(); });
    }
    function del(url) {
        return fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json', 'X-HTTP-Method-Override': 'DELETE' }, body: JSON.stringify({ _method: 'DELETE' }) }).then(function (r) { return r.json(); });
    }
    function collect(scope, sel) {
        var out = {};
        scope.querySelectorAll(sel).forEach(function (el) {
            var v = el.value;
            out[el.dataset.f] = (v === '' ? null : v);
        });
        return out;
    }

    document.addEventListener('click', function (e) {
        // Exam form
        if (e.target.closest('.opth-exam-add')) {
            var er = e.target.closest('[id$="_exam"]');
            er.querySelector('.opth-exam-form').style.display = 'block';
            e.target.closest('.opth-exam-add').style.display = 'none';
            return;
        }
        if (e.target.closest('.opth-exam-cancel')) {
            var er2 = e.target.closest('[id$="_exam"]');
            er2.querySelector('.opth-exam-form').style.display = 'none';
            var addBtn = er2.querySelector('.opth-exam-add'); if (addBtn) addBtn.style.display = '';
            return;
        }
        if (e.target.closest('.opth-exam-save')) {
            var er3 = e.target.closest('[id$="_exam"]');
            var payload = collect(er3.querySelector('.opth-exam-form'), '.o-f');
            payload.appointment_id = er3.dataset.appointmentId || null;
            post(er3.dataset.storeUrl, payload).then(function (d) { if (d.success) location.reload(); });
            return;
        }

        // Glasses form
        if (e.target.closest('.opth-glasses-add')) {
            var gr = e.target.closest('[id$="_glasses"]');
            gr.querySelector('.opth-glasses-form').style.display = 'block';
            e.target.closest('.opth-glasses-add').style.display = 'none';
            return;
        }
        if (e.target.closest('.opth-glasses-cancel')) {
            var gr2 = e.target.closest('[id$="_glasses"]');
            gr2.querySelector('.opth-glasses-form').style.display = 'none';
            var gAdd = gr2.querySelector('.opth-glasses-add'); if (gAdd) gAdd.style.display = '';
            return;
        }
        if (e.target.closest('.opth-glasses-save')) {
            var gr3 = e.target.closest('[id$="_glasses"]');
            var gp = collect(gr3.querySelector('.opth-glasses-form'), '.g-f');
            gp.appointment_id = gr3.dataset.appointmentId || null;
            post(gr3.dataset.storeUrl, gp).then(function (d) {
                if (d.success) {
                    if (d.print_url) { window.open(d.print_url, '_blank'); }
                    location.reload();
                }
            });
            return;
        }
        var gdel = e.target.closest('.opth-glasses-del');
        if (gdel) {
            if (!confirm('Delete this prescription?')) return;
            var gr4 = e.target.closest('[id$="_glasses"]');
            del(gr4.dataset.delBase + '/' + gdel.dataset.rx).then(function (d) { if (d.success) location.reload(); });
            return;
        }
    });
})();
</script>
@endonce
@endif
