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

@section('css')
<style>
/* ── Stats Row ────────────────────────────────────────────── */
.vax-stats-row { display:grid; grid-template-columns:repeat(5,1fr); gap:14px; margin-bottom:20px; }
.vax-stat-box {
    background:#fff; border-radius:10px; padding:16px 20px;
    box-shadow:0 1px 4px rgba(0,0,0,.08); border-top:4px solid;
    display:flex; align-items:center; gap:14px;
    transition:box-shadow .15s, transform .12s; cursor:pointer;
}
.vax-stat-box:hover { box-shadow:0 4px 14px rgba(0,0,0,.14); transform:translateY(-2px); }
.vax-stat-box.active-filter { box-shadow:0 4px 16px rgba(0,0,0,.18); transform:translateY(-2px); outline:2px solid; outline-offset:2px; }
.vax-stat-icon { font-size:26px; opacity:.2; }
.vax-stat-num  { font-size:28px; font-weight:800; line-height:1; }
.vax-stat-lbl  { font-size:11px; text-transform:uppercase; letter-spacing:.5px; color:#94a3b8; margin-top:3px; }

/* ── Urgent Panel ─────────────────────────────────────────── */
.urgent-panel { background:#fff; border-radius:10px; box-shadow:0 1px 4px rgba(0,0,0,.08); margin-bottom:18px; overflow:hidden; }
.urgent-panel-toggle {
    padding:13px 18px; cursor:pointer;
    display:flex; align-items:center; gap:10px;
    border-left:4px solid; user-select:none;
}
.urgent-panel-toggle:hover { background:#fafafa; }
.urgent-panel-body { padding:0 18px 12px; }

.remind-card {
    display:flex; align-items:center; gap:12px;
    padding:9px 0; border-bottom:1px solid #f4f4f4; flex-wrap:wrap;
}
.remind-card:last-child { border-bottom:none; }
.rc-pet-name { font-weight:700; font-size:13px; color:#1e293b; }
.rc-meta     { font-size:11px; color:#94a3b8; }
.rc-vaccine  { font-size:12px; color:#555; margin-top:1px; }
.rc-date     { font-size:11px; color:#64748b; margin-top:2px; }
.rc-due-badge { font-size:11px; font-weight:700; padding:3px 10px; border-radius:12px; color:#fff; white-space:nowrap; flex-shrink:0; }

/* ── Filter Tabs ──────────────────────────────────────────── */
.vax-filter-row { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
.vax-filter-btn {
    padding:5px 14px; border-radius:20px; font-size:12px; font-weight:600;
    border:2px solid; cursor:pointer; background:transparent;
    transition:all .15s; line-height:1.4;
}
.vax-filter-btn.active { color:#fff !important; }

/* ── Table tweaks ─────────────────────────────────────────── */
#vaccinations_table td { vertical-align:middle; }

/* ── Vaccine Detail Modal ─────────────────────────────────── */
.vd-section { margin-bottom:16px; }
.vd-section-title {
    font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.8px;
    color:#94a3b8; padding-bottom:6px; margin-bottom:8px;
    border-bottom:1px solid #f1f5f9;
}
.vd-grid { display:grid; grid-template-columns:1fr 1fr; gap:0; }
.vd-item { padding:7px 0; }
.vd-label { font-size:11px; font-weight:600; color:#94a3b8; text-transform:uppercase; letter-spacing:.4px; }
.vd-value { font-size:13px; color:#1e293b; margin-top:2px; font-weight:500; }
.vd-badge { display:inline-block; padding:2px 9px; border-radius:10px; font-size:11px; font-weight:700; }
</style>
@include('vetClinic::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1>
        <i class="fas fa-syringe"></i> @lang('vetClinic::lang.vaccinations')
        <small class="text-muted" style="font-size:13px;">
            Urgent panel shows vaccinations due within <strong>{{ $reminderDays }}</strong> days
        </small>
    </h1>
</section>

<section class="content">

{{-- ─── Stats Row ─── --}}
<div class="vax-stats-row">
    <div class="vax-stat-box" style="border-color:#e74c3c;outline-color:#e74c3c;" data-stat-filter="overdue">
        <div class="vax-stat-icon" style="color:#e74c3c;"><i class="fas fa-exclamation-circle"></i></div>
        <div>
            <div class="vax-stat-num" style="color:#e74c3c;">{{ $stats['overdue'] }}</div>
            <div class="vax-stat-lbl">Overdue</div>
        </div>
    </div>
    <div class="vax-stat-box" style="border-color:#f39c12;outline-color:#f39c12;" data-stat-filter="due_soon">
        <div class="vax-stat-icon" style="color:#f39c12;"><i class="fas fa-clock"></i></div>
        <div>
            <div class="vax-stat-num" style="color:#f39c12;">{{ $stats['due_soon'] }}</div>
            <div class="vax-stat-lbl">Due This Month</div>
        </div>
    </div>
    <div class="vax-stat-box" style="border-color:#27ae60;outline-color:#27ae60;" data-stat-filter="upcoming">
        <div class="vax-stat-icon" style="color:#27ae60;"><i class="fas fa-calendar-check"></i></div>
        <div>
            <div class="vax-stat-num" style="color:#27ae60;">{{ $stats['upcoming'] }}</div>
            <div class="vax-stat-lbl">Upcoming</div>
        </div>
    </div>
    <div class="vax-stat-box" style="border-color:#2c3e50;outline-color:#2c3e50;" data-stat-filter="">
        <div class="vax-stat-icon" style="color:#2c3e50;"><i class="fas fa-syringe"></i></div>
        <div>
            <div class="vax-stat-num" style="color:#2c3e50;">{{ $stats['total'] }}</div>
            <div class="vax-stat-lbl">Total Records</div>
        </div>
    </div>
    <div class="vax-stat-box" style="border-color:#78909c;outline-color:#78909c;" data-stat-filter="waived">
        <div class="vax-stat-icon" style="color:#78909c;"><i class="fas fa-ban"></i></div>
        <div>
            <div class="vax-stat-num" style="color:#78909c;">{{ $stats['waived'] }}</div>
            <div class="vax-stat-lbl">Waived</div>
        </div>
    </div>
</div>

{{-- ─── Urgent Reminders Panel ─── --}}
@if($urgentVaccinations->isNotEmpty())
@php $hasOverdue = $urgentVaccinations->filter(fn($v) => $v->administered_date < now())->isNotEmpty(); @endphp
<div class="urgent-panel">
    <div class="urgent-panel-toggle" style="border-color:{{ $hasOverdue ? '#e74c3c' : '#f39c12' }};"
         onclick="$('#urgentPanelBody').slideToggle(200);">
        <i class="fas fa-bell" style="font-size:16px;color:{{ $hasOverdue ? '#e74c3c' : '#f39c12' }};flex-shrink:0;"></i>
        <div style="flex:1;">
            <strong style="color:{{ $hasOverdue ? '#e74c3c' : '#f39c12' }};">
                {{ $urgentVaccinations->count() }} vaccination{{ $urgentVaccinations->count() > 1 ? 's' : '' }}
                need{{ $urgentVaccinations->count() === 1 ? 's' : '' }} attention
            </strong>
            <span class="text-muted" style="font-size:12px;margin-left:8px;">
                @if($stats['overdue'] > 0){{ $stats['overdue'] }} overdue @endif
                @if($stats['overdue'] > 0 && $stats['due_soon'] > 0) · @endif
                @if($stats['due_soon'] > 0){{ $stats['due_soon'] }} due within 30 days @endif
            </span>
        </div>
        <i class="fa fa-chevron-down" style="color:#aaa;font-size:11px;flex-shrink:0;"></i>
    </div>
    <div id="urgentPanelBody" class="urgent-panel-body">
        @foreach($urgentVaccinations as $uv)
        @php
            $uvDays   = (int) now()->diffInDays($uv->administered_date, false);
            $uvColor  = $uvDays < 0 ? '#e74c3c' : '#f39c12';
            $uvLabel  = $uvDays < 0 ? abs($uvDays).' days overdue' : ($uvDays === 0 ? 'Due today' : 'In '.$uvDays.' days');
            $uvDateFmt = $uv->administered_date
                ? \Carbon\Carbon::parse($uv->administered_date)->format(session('business.date_format','d M Y'))
                : null;
        @endphp
        <div class="remind-card">
            <div style="min-width:0;flex:1;">
                <div class="rc-pet-name">
                    {{ optional($uv->pet)->petname ?? '—' }}
                    <span class="rc-meta" style="font-weight:400;">
                        {{ optional($uv->pet)->species }}
                        @if(optional($uv->pet)->breed) · {{ $uv->pet->breed }} @endif
                    </span>
                </div>
                <div class="rc-vaccine">
                    <i class="fas fa-syringe" style="color:#aaa;"></i>
                    {{ optional($uv->vaccineType)->name ?? '—' }}
                    @if(optional(optional($uv->pet)->owner)->mobile)
                    &nbsp; <i class="fa fa-phone" style="color:#aaa;"></i>
                    {{ $uv->pet->owner->mobile }}
                    @endif
                    <span class="rc-meta" style="margin-left:8px;">{{ optional(optional($uv->pet)->owner)->name ?? '' }}</span>
                </div>
                @if($uvDateFmt)
                <div class="rc-date"><i class="fa fa-calendar" style="color:#aaa;"></i> Scheduled: <strong>{{ $uvDateFmt }}</strong></div>
                @endif
            </div>
            <span class="rc-due-badge" style="background:{{ $uvColor }};">
                <i class="fas fa-{{ $uvDays < 0 ? 'exclamation-circle' : 'clock' }}"></i>
                {{ $uvLabel }}
            </span>
            @if($uv->reminder_sent)
                <span class="label label-success remind-status-{{ $uv->id }}" style="font-size:11px;"><i class="fa fa-check"></i> Reminded</span>
            @else
                <button class="btn btn-xs btn-warning btn-mark-reminded remind-status-{{ $uv->id }}"
                        data-id="{{ $uv->id }}" title="Mark as reminded">
                    <i class="fa fa-bell"></i> Remind
                </button>
            @endif
            <button class="btn btn-xs btn-primary btn-vax-edit" data-id="{{ $uv->id }}" title="Edit vaccination">
                <i class="fa fa-edit"></i>
            </button>
            <button class="btn btn-xs btn-waive-vax"
                    data-id="{{ $uv->id }}"
                    data-pet="{{ e(optional($uv->pet)->petname ?? '') }}"
                    data-vaccine="{{ e(optional($uv->vaccineType)->name ?? '') }}"
                    title="Waive — remove from overdue tracking"
                    style="background:#78909c;color:#fff;">
                <i class="fa fa-ban"></i> Waive
            </button>
            @if($uv->pet)
            <a href="{{ route('vc.pets.show', $uv->pet->id) }}" class="btn btn-xs btn-default" title="Pet Profile">
                <i class="fa fa-paw"></i>
            </a>
            @endif
        </div>
        @endforeach
    </div>
</div>
@endif

{{-- ─── Main DataTable ─── --}}
@component('components.widget', ['class' => 'box-default', 'title' => ''])

    {{-- Due-status filter row --}}
    <div class="vax-filter-row">
        @php
        $vfBtns = [
            ''        => ['All',      '#2c3e50'],
            'overdue' => ['Overdue',  '#e74c3c'],
            'due_soon'=> ['Due Soon', '#f39c12'],
            'upcoming'=> ['Upcoming', '#27ae60'],
            'waived'  => ['Waived',   '#78909c'],
        ];
        @endphp
        @foreach($vfBtns as $val => [$label, $color])
        <button class="vax-filter-btn {{ $val === '' ? 'active' : '' }}"
                data-filter="{{ $val }}"
                style="border-color:{{ $color }};color:{{ $color }};"
                data-color="{{ $color }}">
            {{ $label }}
            @if($val === 'overdue'  && $stats['overdue']  > 0)<span class="badge" style="background:{{ $color }};margin-left:3px;">{{ $stats['overdue'] }}</span>@endif
            @if($val === 'due_soon' && $stats['due_soon'] > 0)<span class="badge" style="background:{{ $color }};margin-left:3px;">{{ $stats['due_soon'] }}</span>@endif
            @if($val === 'waived'   && $stats['waived']   > 0)<span class="badge" style="background:{{ $color }};margin-left:3px;">{{ $stats['waived'] }}</span>@endif
        </button>
        @endforeach
    </div>

    {{-- Taken-status + category filter row --}}
    <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px;align-items:center;padding:7px 10px;background:#f8fafc;border-radius:7px;border:1px solid #e8ecf0;">
        <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;">Where:</span>
        <button class="vax-taken-filter-btn active" data-taken="" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #cbd5e1;background:transparent;cursor:pointer;">All</button>
        <button class="vax-taken-filter-btn" data-taken="taken_in"  style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #27ae60;color:#27ae60;background:transparent;cursor:pointer;"><i class="fa fa-hospital"></i> At Clinic</button>
        <button class="vax-taken-filter-btn" data-taken="taken_out" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #2980b9;color:#2980b9;background:transparent;cursor:pointer;"><i class="fa fa-home"></i> External</button>
        <button class="vax-taken-filter-btn" data-taken="not_taken" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #e67e22;color:#e67e22;background:transparent;cursor:pointer;"><i class="fa fa-clock"></i> Not Taken</button>
        <span style="width:1px;height:16px;background:#ddd;margin:0 4px;"></span>
        <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;">Type:</span>
        <button class="vax-cat-filter-btn active" data-cat="" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #cbd5e1;background:transparent;cursor:pointer;">All</button>
        <button class="vax-cat-filter-btn" data-cat="core_vaccine"     style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #2980b9;color:#2980b9;background:transparent;cursor:pointer;">Core</button>
        <button class="vax-cat-filter-btn" data-cat="non_core_vaccine" style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #8e44ad;color:#8e44ad;background:transparent;cursor:pointer;">Non-Core</button>
        <button class="vax-cat-filter-btn" data-cat="deworming"        style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #16a085;color:#16a085;background:transparent;cursor:pointer;">Dewormer</button>
        <button class="vax-cat-filter-btn" data-cat="spot_on"          style="font-size:11px;font-weight:700;padding:3px 10px;border-radius:12px;border:1px solid #d35400;color:#d35400;background:transparent;cursor:pointer;">Spot-on</button>
    </div>

    {{-- Next Due Date Range Filter --}}
    <div style="display:flex;gap:8px;align-items:center;margin-bottom:12px;padding:7px 12px;background:#f8fafc;border-radius:7px;border:1px solid #e8ecf0;">
        <span style="font-size:10px;font-weight:700;text-transform:uppercase;color:#aaa;white-space:nowrap;">
            <i class="fa fa-calendar" style="color:#2980b9;"></i> Next Due:
        </span>
        <input type="text" id="filter_due_date_range" class="form-control"
               style="width:220px;" placeholder="@lang('lang_v1.select_a_date_range')" readonly>
    </div>

    <table class="table table-bordered table-striped table-hover" id="vaccinations_table">
        <thead>
            <tr>
                <th>Pet</th>
                <th>Owner</th>
                <th>@lang('vetClinic::lang.vaccine_type')</th>
                <th>@lang('vetClinic::lang.administered_date')</th>
                <th>Next Due / Countdown</th>
                <th>Vaccination Status</th>
                <th><i class="fa fa-bell" title="Reminder"></i></th>
                <th>@lang('vetClinic::lang.actions')</th>
            </tr>
        </thead>
    </table>

@endcomponent

</section>

{{-- ─── Vaccine Detail Modal ─── --}}
<div class="modal fade" id="vaxDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background:linear-gradient(135deg,#1a3a5c,#16a085);color:#fff;padding:14px 20px;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;opacity:.9;font-size:15px;">&times;</button>
                <h4 class="modal-title" style="font-size:16px;">
                    <i class="fas fa-syringe" style="margin-right:8px;"></i>
                    <span id="vaxDetailTitle">Vaccination Record</span>
                </h4>
            </div>
            <div class="modal-body" id="vaxDetailBody" style="padding:20px 24px;min-height:200px;">
                <div style="text-align:center;padding:40px;"><i class="fa fa-spinner fa-spin fa-2x text-muted"></i></div>
            </div>
            <div class="modal-footer" style="background:#f8fafc;border-top:1px solid #e9ecef;padding:10px 20px;">
                <button type="button" id="btnEditFromDetail" class="btn btn-warning btn-sm" style="margin-right:auto;">
                    <i class="fa fa-edit"></i> Edit
                </button>
                <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

{{-- ─── Edit Vaccination Modal ─── --}}
<div class="modal fade" id="vaxEditModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background:#2471a3;color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;opacity:1;font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fas fa-syringe"></i> Edit Vaccination Record</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="edit_vax_id">
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.vaccine_type') <span class="text-danger">*</span></label>
                            <select id="edit_vax_vaccine_type_id" class="form-control select2-edit-vax" style="width:100%"></select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">Vaccination Status</label>
                            <select id="edit_vax_taken_status" class="form-control input-sm">
                                <option value="taken_in">🏥 At Clinic (Taken In)</option>
                                <option value="taken_out">🏠 External (Taken Out)</option>
                                <option value="not_taken">⏳ Not Taken / Scheduled</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.dose')</label>
                    <input type="text" id="edit_vax_dose" class="form-control input-sm" placeholder="e.g. 1 ml, Booster, 1st dose">
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.administered_date')</label>
                            <input type="text" id="edit_vax_date_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="edit_vax_date_iso">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.next_due_date')</label>
                            <input type="text" id="edit_vax_next_due_display" class="form-control input-sm" autocomplete="off">
                            <input type="hidden" id="edit_vax_next_due_iso">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.batch_no')</label>
                            <input type="text" id="edit_vax_batch" class="form-control input-sm">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.weight_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.01" id="edit_vax_weight" class="form-control">
                                <span class="input-group-addon">kg</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.temperature_at_time')</label>
                            <div class="input-group input-group-sm">
                                <input type="number" step="0.1" id="edit_vax_temperature" class="form-control" placeholder="38.5">
                                <span class="input-group-addon">°C</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label style="font-size:12px;font-weight:600;">@lang('vetClinic::lang.notes')</label>
                    <textarea id="edit_vax_notes" class="form-control input-sm" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer" style="display:flex;justify-content:space-between;align-items:center;">
                <button class="btn btn-danger btn-sm" id="btn_vax_modal_delete">
                    <i class="fa fa-trash"></i> @lang('vetClinic::lang.delete')
                </button>
                <div>
                    <button class="btn btn-default btn-sm" data-dismiss="modal">@lang('vetClinic::lang.cancel')</button>
                    <button class="btn btn-primary btn-sm" id="btn_save_vax_edit">
                        <i class="fa fa-save"></i> @lang('vetClinic::lang.update')
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- ─── Waive Reason Modal ─── --}}
<div class="modal fade" id="waiveModal" tabindex="-1">
    <div class="modal-dialog" style="max-width:440px;">
        <div class="modal-content">
            <div class="modal-header" style="background:#546e7a;color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;font-size:15px;">&times;</button>
                <h4 class="modal-title"><i class="fa fa-ban"></i> Waive Vaccination</h4>
            </div>
            <div class="modal-body">
                <p class="text-muted" style="font-size:13px;margin-bottom:14px;">
                    Waiving removes this record from overdue counts and reminder panels. The history is kept — you can restore it at any time.
                </p>
                <input type="hidden" id="waive_vax_id">
                <div class="form-group">
                    <label style="font-size:12px;font-weight:700;">Reason <span class="text-danger">*</span></label>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:6px;">
                        @foreach(['deceased'=>['Pet Deceased','fa-heart-broken','#e74c3c'],'refused'=>['Owner Refused','fa-hand-paper','#f39c12'],'contraindicated'=>['Contraindicated','fa-exclamation-triangle','#9b59b6'],'other'=>['Other','fa-ellipsis-h','#78909c']] as $code=>[$label,$icon,$color])
                        <label class="waive-reason-card" style="cursor:pointer;border:2px solid #e0e0e0;border-radius:8px;padding:10px 12px;text-align:center;transition:all .15s;margin:0;">
                            <input type="radio" name="waive_reason" value="{{ $code }}" style="display:none;">
                            <i class="fa {{ $icon }}" style="font-size:18px;color:{{ $color }};display:block;margin-bottom:4px;"></i>
                            <span style="font-size:12px;font-weight:600;color:#333;">{{ $label }}</span>
                        </label>
                        @endforeach
                    </div>
                    <div id="waive_reason_error" class="text-danger" style="font-size:11px;margin-top:5px;display:none;">Please select a reason.</div>
                </div>
                <div class="form-group" style="margin-bottom:0;">
                    <label style="font-size:12px;font-weight:700;">Note <span class="text-muted">(optional)</span></label>
                    <input type="text" id="waive_note" class="form-control input-sm" placeholder="Additional detail…" maxlength="255">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
                <button class="btn btn-sm" id="btn_confirm_waive" style="background:#546e7a;color:#fff;">
                    <i class="fa fa-ban"></i> Confirm Waiver
                </button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('javascript')
<script>
var currentFilter      = '';
var currentTakenFilter = '';
var currentCatFilter   = '';
var csrfToken          = '{{ csrf_token() }}';
var vaxBaseUrl         = '{{ url('vet-clinic/vaccinations') }}';
var currentDetailId    = null;
window.vcActionTarget  = '{{ $vcActionTarget ?? "_self" }}';

$(document).on('click', '#vaccinations_table a.btn[href]', function (e) {
    if (window.vcActionTarget === '_blank') {
        e.preventDefault();
        window.open($(this).attr('href'), '_blank');
    }
});

var table = $('#vaccinations_table').DataTable({
    processing: true,
    serverSide: true,
    order: [[3, 'desc']],
    ajax: {
        url: '{{ route('vc.vaccinations.list') }}',
        data: function (d) {
            d.status       = currentFilter;
            d.taken_status = currentTakenFilter;
            d.category     = currentCatFilter;

            var drp = $('#filter_due_date_range').data('daterangepicker');
            if ($('#filter_due_date_range').val() && drp) {
                d.filter_due_from = drp.startDate.format('YYYY-MM-DD');
                d.filter_due_to   = drp.endDate.format('YYYY-MM-DD');
            } else {
                d.filter_due_from = '';
                d.filter_due_to   = '';
            }
        }
    },
    columns: [
        { data: 'pet_col',               name: 'pet_name',         orderable: false },
        { data: 'owner_col',             name: 'owner_name',       orderable: false },
        { data: 'vaccine_name',          name: 'vaccine_name',     orderable: false },
        { data: 'administered_date_col', name: 'administered_date' },
        { data: 'due_col',               name: 'next_due_date' },
        { data: 'status_badge',          name: 'status',           orderable: false },
        { data: 'reminder_col',          name: 'reminder',         orderable: false, searchable: false },
        { data: 'action',                name: 'action',           orderable: false, searchable: false }
    ]
});

/* ── Stat box → filter trigger ─────────────────────────── */
$('.vax-stat-box[data-stat-filter]').on('click', function () {
    var filter = $(this).data('stat-filter');
    $('.vax-stat-box').removeClass('active-filter');
    $(this).addClass('active-filter');
    $('.vax-filter-btn[data-filter="' + filter + '"]').trigger('click');
});

/* ── Status Filter Tabs ─────────────────────────────────── */
$('.vax-filter-btn').on('click', function () {
    var color = $(this).data('color');
    $('.vax-filter-btn').each(function () {
        $(this).removeClass('active').css({ background:'transparent', color: $(this).data('color') });
    });
    $(this).addClass('active').css({ background: color, color:'#fff' });
    currentFilter = $(this).data('filter');
    table.ajax.reload();
});

$('.vax-taken-filter-btn').on('click', function () {
    var val = $(this).data('taken');
    $('.vax-taken-filter-btn').each(function () {
        $(this).removeClass('active').css({ background:'transparent' });
    });
    $(this).addClass('active').css({ background: val ? '#333' : '#555', color:'#fff', borderColor: val ? '#333':'#555' });
    currentTakenFilter = val;
    table.ajax.reload();
});

$('.vax-cat-filter-btn').on('click', function () {
    var val = $(this).data('cat');
    $('.vax-cat-filter-btn').each(function () {
        $(this).removeClass('active').css({ background:'transparent' });
    });
    $(this).addClass('active').css({ background:'#555', color:'#fff', borderColor:'#555' });
    currentCatFilter = val;
    table.ajax.reload();
});

/* ── Due Date Range Filter ──────────────────────────────── */
$('#filter_due_date_range').daterangepicker(
    dateRangeSettings,
    function (start, end) {
        $('#filter_due_date_range').val(
            start.format(moment_date_format) + ' ~ ' + end.format(moment_date_format)
        );
        table.ajax.reload();
    }
);
$('#filter_due_date_range').on('cancel.daterangepicker', function () {
    $(this).val('');
    table.ajax.reload();
});

/* ── Mark Reminded ─────────────────────────────────────── */
$(document).on('click', '.btn-mark-reminded', function () {
    var id   = $(this).data('id');
    var $btn = $(this);
    $.ajax({
        url:    vaxBaseUrl + '/' + id + '/remind',
        method: 'POST',
        data:   { _token: csrfToken },
        success: function (res) {
            if (res.success) {
                toastr.success('Reminder marked as sent.');
                $('.remind-status-' + id + ', .btn-mark-reminded[data-id="' + id + '"]')
                    .replaceWith('<span class="label label-success" style="font-size:11px;"><i class="fa fa-check"></i> Sent</span>');
                table.ajax.reload(null, false);
            }
        },
        error: function () { toastr.error('Failed to mark reminder.'); }
    });
});

/* ── Email Reminder ─────────────────────────────────────── */
$(document).on('click', '.btn-email-remind', function () {
    var id      = $(this).data('id');
    var email   = $(this).data('email');
    var pet     = $(this).data('pet');
    var vaccine = $(this).data('vaccine');
    var $btn    = $(this);

    if (!confirm('Send vaccination reminder email to ' + email + ' for ' + pet + ' (' + vaccine + ')?')) return;

    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    $.ajax({
        url:    vaxBaseUrl + '/' + id + '/send-email-reminder',
        method: 'POST',
        data:   { _token: csrfToken },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                $btn.closest('td').find('.btn-email-remind').replaceWith(
                    '<span class="label label-success" style="font-size:11px;" title="Email sent"><i class="fa fa-envelope"></i> Sent</span> '
                );
                table.ajax.reload(null, false);
            } else {
                toastr.error(res.msg);
                $btn.prop('disabled', false).html('<i class="fa fa-envelope"></i>');
            }
        },
        error: function () {
            toastr.error('Failed to send email.');
            $btn.prop('disabled', false).html('<i class="fa fa-envelope"></i>');
        }
    });
});

/* ── Detail Modal ───────────────────────────────────────── */
function loadVaxDetail(id) {
    currentDetailId = id;
    $('#vaxDetailBody').html('<div style="text-align:center;padding:40px;"><i class="fa fa-spinner fa-spin fa-2x text-muted"></i></div>');
    $('#vaxDetailTitle').text('Vaccination Record');
    $('#vaxDetailModal').modal('show');

    $.get(vaxBaseUrl + '/' + id + '/edit', function (d) {
        var takenMap   = { taken_in: '<span class="vd-badge" style="background:#27ae60;color:#fff;"><i class="fa fa-hospital"></i> At Clinic</span>',
                           taken_out: '<span class="vd-badge" style="background:#2980b9;color:#fff;"><i class="fa fa-home"></i> External</span>',
                           not_taken: '<span class="vd-badge" style="background:#f39c12;color:#fff;"><i class="fa fa-clock"></i> Not Taken</span>' };
        var catMap = { core_vaccine:'Core Vaccine', non_core_vaccine:'Non-Core', spot_on:'Spot-on', deworming:'Dewormer',
                       oral:'Oral', nasal:'Nasal', topical:'Topical', preventive:'Preventive', other:'Other' };

        if (d.pet_name) $('#vaxDetailTitle').text(d.pet_name + ' — ' + (d.vaccine_type_name || 'Vaccination'));

        var html = '';

        // Pet & Owner
        html += '<div class="vd-section">'
            + '<div class="vd-section-title"><i class="fa fa-paw"></i> Pet & Owner</div>'
            + '<div class="vd-grid">'
            + '<div class="vd-item"><div class="vd-label">Pet</div><div class="vd-value">' + (d.pet_name || '—') + (d.pet_species ? ' <small class="text-muted">· ' + d.pet_species + (d.pet_breed ? ' · ' + d.pet_breed : '') + '</small>' : '') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Owner</div><div class="vd-value">' + (d.owner_name || '—') + (d.owner_mobile ? ' <small class="text-muted"><i class="fa fa-phone"></i> ' + d.owner_mobile + '</small>' : '') + '</div></div>'
            + '</div></div>';

        // Vaccine Info
        html += '<div class="vd-section">'
            + '<div class="vd-section-title"><i class="fas fa-syringe"></i> Vaccine</div>'
            + '<div class="vd-grid">'
            + '<div class="vd-item"><div class="vd-label">Vaccine Type</div><div class="vd-value"><strong>' + (d.vaccine_type_name || '—') + '</strong></div></div>'
            + '<div class="vd-item"><div class="vd-label">Category</div><div class="vd-value">' + (d.vaccine_type_category ? (catMap[d.vaccine_type_category] || d.vaccine_type_category) : '—') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Manufacturer</div><div class="vd-value">' + (d.vaccine_type_manufacturer || '—') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Dose</div><div class="vd-value">' + (d.dose || '—') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Batch No.</div><div class="vd-value">' + (d.batch_no || '—') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Where Taken</div><div class="vd-value">' + (takenMap[d.taken_status] || d.taken_status || '—') + '</div></div>'
            + '</div></div>';

        // Dates & Vitals
        html += '<div class="vd-section">'
            + '<div class="vd-section-title"><i class="fa fa-calendar"></i> Dates & Vitals</div>'
            + '<div class="vd-grid">'
            + '<div class="vd-item"><div class="vd-label">Scheduled / Admin. Date</div><div class="vd-value"><strong>' + (d.administered_date_fmt || d.administered_date_iso || '—') + '</strong></div></div>'
            + '<div class="vd-item"><div class="vd-label">Next Due Date</div><div class="vd-value"><strong style="color:#e67e22;">' + (d.next_due_date_fmt || d.next_due_date_iso || '—') + '</strong></div></div>'
            + '<div class="vd-item"><div class="vd-label">Weight at Time</div><div class="vd-value">' + (d.weight_at_time ? d.weight_at_time + ' kg' : '—') + '</div></div>'
            + '<div class="vd-item"><div class="vd-label">Temperature</div><div class="vd-value">' + (d.temperature_at_time ? d.temperature_at_time + ' °C' : '—') + '</div></div>'
            + '</div></div>';

        // Notes & Reminder
        if (d.notes || d.reminder_sent !== undefined) {
            html += '<div class="vd-section">'
                + '<div class="vd-section-title"><i class="fa fa-sticky-note"></i> Additional</div>'
                + '<div class="vd-grid">'
                + (d.notes ? '<div class="vd-item" style="grid-column:1/-1;"><div class="vd-label">Notes</div><div class="vd-value">' + d.notes + '</div></div>' : '')
                + '<div class="vd-item"><div class="vd-label">Reminder Sent</div><div class="vd-value">' + (d.reminder_sent ? '<span class="vd-badge" style="background:#27ae60;color:#fff;"><i class="fa fa-check"></i> Yes</span>' : '<span class="vd-badge" style="background:#95a5a6;color:#fff;">No</span>') + '</div></div>'
                + '</div></div>';
        }

        $('#vaxDetailBody').html(html);
        $('#btnEditFromDetail').data('id', id);
    }).fail(function () {
        $('#vaxDetailBody').html('<p class="text-danger text-center" style="padding:30px;">Failed to load vaccination details.</p>');
    });
}

$(document).on('click', '.btn-vax-view', function () {
    loadVaxDetail($(this).data('id'));
});

/* ── Edit Modal — open ─────────────────────────────────── */
var _editVaxPending = {};
var _editVaxDpReady = false;

function _isoToLocal(iso) { var p = iso.split('-'); return new Date(+p[0], +p[1]-1, +p[2]); }

function _applyEditVaxData(d) {
    $('#edit_vax_dose').val(d.dose || '');
    $('#edit_vax_batch').val(d.batch_no || '');
    $('#edit_vax_weight').val(d.weight_at_time || '');
    $('#edit_vax_temperature').val(d.temperature_at_time || '');
    $('#edit_vax_notes').val(d.notes || '');
    $('#edit_vax_taken_status').val(d.taken_status || 'taken_in');

    var ai = d.administered_date_iso || '';
    var ni = d.next_due_date_iso     || '';
    if (ai) {
        $('#edit_vax_date_iso').val(ai);
        if (_editVaxDpReady) { try { $('#edit_vax_date_display').datepicker('setDate', _isoToLocal(ai)); } catch(e) {} }
    }
    if (ni) {
        $('#edit_vax_next_due_iso').val(ni);
        if (_editVaxDpReady) { try { $('#edit_vax_next_due_display').datepicker('setDate', _isoToLocal(ni)); } catch(e) {} }
    }
    if (d.vaccine_type_id && d.vaccine_type_name) {
        $('#edit_vax_vaccine_type_id').empty()
            .append(new Option(d.vaccine_type_name, d.vaccine_type_id, true, true))
            .trigger('change');
    }
}

$('#vaxEditModal').on('shown.bs.modal', function () {
    $('#edit_vax_date_display').datepicker('destroy')
        .datepicker({ todayHighlight: true, autoclose: true, format: datepicker_date_format })
        .on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#edit_vax_date_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth() + 1).padStart(2, '0') + '-' +
                    String(d.getDate()).padStart(2, '0')
                );
            }
        });
    $('#edit_vax_next_due_display').datepicker('destroy')
        .datepicker({ todayHighlight: true, autoclose: true, format: datepicker_date_format })
        .on('changeDate', function (e) {
            if (e.dates.length) {
                var d = e.dates[0];
                $('#edit_vax_next_due_iso').val(
                    d.getFullYear() + '-' +
                    String(d.getMonth() + 1).padStart(2, '0') + '-' +
                    String(d.getDate()).padStart(2, '0')
                );
            }
        });

    if (!$('#edit_vax_vaccine_type_id').data('select2')) {
        $('#edit_vax_vaccine_type_id').select2({
            width: '100%', minimumInputLength: 1,
            dropdownParent: $('#vaxEditModal'),
            placeholder: 'Search vaccine…',
            ajax: {
                url: '{{ route('vc.vaccine-types.search') }}',
                dataType: 'json', delay: 250,
                data: function (p) { return { q: p.term }; },
                processResults: function (d) { return { results: d }; }
            },
            templateResult: function (d) {
                if (!d.id) return d.text;
                return $('<span>' + d.text + (d.category_label ? ' <span class="label label-default" style="font-size:9px;">' + d.category_label + '</span>' : '') + '</span>');
            },
            templateSelection: function (d) { return d.text || d.id; }
        });
    }

    _editVaxDpReady = true;
    if (_editVaxPending && _editVaxPending.id) { _applyEditVaxData(_editVaxPending); }
});

$('#vaxEditModal').on('hidden.bs.modal', function () {
    _editVaxDpReady = false;
    _editVaxPending = {};
});

function openEditModal(id) {
    _editVaxPending = {};
    _editVaxDpReady = false;
    $('#edit_vax_id').val(id);
    $('#edit_vax_dose,#edit_vax_batch,#edit_vax_notes').val('');
    $('#edit_vax_weight,#edit_vax_temperature').val('');
    $('#edit_vax_date_iso,#edit_vax_next_due_iso').val('');
    $('#edit_vax_date_display,#edit_vax_next_due_display').val('');
    $('#vaxEditModal').modal('show');

    $.getJSON(vaxBaseUrl + '/' + id + '/edit', function (d) {
        _editVaxPending = d;
        if (_editVaxDpReady) { _applyEditVaxData(d); }
    }).fail(function () {
        toastr.error('Failed to load vaccination data.');
    });
}

$(document).on('click', '.btn-vax-edit', function () {
    openEditModal($(this).data('id'));
});

$('#btnEditFromDetail').on('click', function () {
    $('#vaxDetailModal').modal('hide');
    openEditModal($(this).data('id'));
});

/* ── Edit Modal — save ─────────────────────────────────── */
$('#btn_save_vax_edit').on('click', function () {
    var id   = $('#edit_vax_id').val();
    var $btn = $(this);
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

    $.ajax({
        url: vaxBaseUrl + '/' + id + '/update', method: 'POST',
        data: {
            _token:              csrfToken,
            vaccine_type_id:     $('#edit_vax_vaccine_type_id').val(),
            taken_status:        $('#edit_vax_taken_status').val(),
            dose:                $('#edit_vax_dose').val(),
            administered_date:   $('#edit_vax_date_iso').val(),
            next_due_date:       $('#edit_vax_next_due_iso').val(),
            batch_no:            $('#edit_vax_batch').val(),
            weight_at_time:      $('#edit_vax_weight').val(),
            temperature_at_time: $('#edit_vax_temperature').val(),
            notes:               $('#edit_vax_notes').val(),
        },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg || 'Updated successfully.');
                $('#vaxEditModal').modal('hide');
                table.ajax.reload(null, false);
            } else {
                toastr.error(res.msg || 'Error saving.');
            }
        },
        error: function () { toastr.error('Failed to save.'); },
        complete: function () {
            $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang('vetClinic::lang.update')');
        }
    });
});

/* ── Edit Modal — delete ───────────────────────────────── */
$('#btn_vax_modal_delete').on('click', function () {
    if (!confirm('@lang('vetClinic::lang.confirm_delete')')) return;
    var id = $('#edit_vax_id').val();
    $.ajax({
        url: vaxBaseUrl + '/' + id, method: 'DELETE',
        data: { _token: csrfToken },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg || 'Deleted.');
                $('#vaxEditModal').modal('hide');
                table.ajax.reload(null, false);
            }
        },
        error: function () { toastr.error('Failed to delete.'); }
    });
});

/* ── Delete ─────────────────────────────────────────────── */
$(document).on('click', '.btn-delete-vaccination', function () {
    if (!confirm('@lang('vetClinic::lang.confirm_delete')')) return;
    var id = $(this).data('id');
    $.ajax({
        url:    vaxBaseUrl + '/' + id,
        method: 'DELETE',
        data:   { _token: csrfToken },
        success: function (res) {
            if (res.success) { toastr.success(res.msg); table.ajax.reload(null, false); }
        }
    });
});

/* ── Waive Reason Cards ────────────────────────────────── */
$(document).on('change', 'input[name="waive_reason"]', function () {
    $('.waive-reason-card').css({ borderColor:'#e0e0e0', background:'#fff' });
    $(this).closest('.waive-reason-card').css({ borderColor:'#546e7a', background:'#eceff1' });
    $('#waive_reason_error').hide();
});

/* ── Open Waive Modal ──────────────────────────────────── */
$(document).on('click', '.btn-waive-vax', function () {
    var id      = $(this).data('id');
    var pet     = $(this).data('pet');
    var vaccine = $(this).data('vaccine');
    $('#waive_vax_id').val(id);
    $('#waive_note').val('');
    $('input[name="waive_reason"]').prop('checked', false);
    $('.waive-reason-card').css({ borderColor:'#e0e0e0', background:'#fff' });
    $('#waive_reason_error').hide();
    $('#waiveModal').modal('show');
});

/* ── Submit Waive ──────────────────────────────────────── */
$('#btn_confirm_waive').on('click', function () {
    var reason = $('input[name="waive_reason"]:checked').val();
    if (!reason) { $('#waive_reason_error').show(); return; }

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

    $.ajax({
        url:    vaxBaseUrl + '/' + id + '/waive',
        method: 'POST',
        data:   { _token: csrfToken, reason: reason, note: $('#waive_note').val() },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                $('#waiveModal').modal('hide');
                table.ajax.reload(null, false);
                // Update urgent panel — remove the card if present
                $('.remind-status-' + id).closest('.remind-card').slideUp(200, function(){ $(this).remove(); });
            } else {
                toastr.error(res.msg || 'Failed to waive.');
            }
        },
        error: function () { toastr.error('Failed to waive.'); },
        complete: function () {
            $btn.prop('disabled', false).html('<i class="fa fa-ban"></i> Confirm Waiver');
        }
    });
});

/* ── Unwaive ────────────────────────────────────────────── */
$(document).on('click', '.btn-unwaive-vax', function () {
    if (!confirm('Remove waiver and restore this vaccination to active tracking?')) return;
    var id   = $(this).data('id');
    var $btn = $(this).prop('disabled', true);

    $.ajax({
        url:    vaxBaseUrl + '/' + id + '/unwaive',
        method: 'POST',
        data:   { _token: csrfToken },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                table.ajax.reload(null, false);
            } else {
                toastr.error(res.msg || 'Failed.');
            }
        },
        error: function () { toastr.error('Failed to remove waiver.'); },
        complete: function () { $btn.prop('disabled', false); }
    });
});

/* ── Waive from urgent panel ────────────────────────────── */
$(document).on('click', '.btn-waive-urgent', function () {
    var $card = $(this).closest('.remind-card');
    $('.btn-waive-vax[data-id="' + $(this).data('id') + '"]').trigger('click');
});
</script>
@endsection
