@extends('layouts.app')

@section('title', optional($owner->contact)->name . ' — Pet Owner')

@section('css')
<style>
/* ── Profile Header ───────────────────────────────── */
.po-hero {
    background: linear-gradient(135deg,#1e3a5f 0%,#2980b9 60%,#6366f1 100%);
    border-radius:14px; padding:24px 28px 0; margin-bottom:20px;
    position:relative; overflow:hidden; box-shadow:0 8px 32px rgba(0,0,0,.2);
    color:#fff;
}
.po-hero-overlay {
    position:absolute; inset:0; border-radius:14px; pointer-events:none;
    background:radial-gradient(ellipse at 20% 40%,rgba(255,255,255,.18) 0%,transparent 55%);
}
.po-hero-bg { position:absolute;right:-20px;bottom:-30px;font-size:180px;opacity:.08;color:#fff;pointer-events:none;user-select:none; }
.po-hero-top { position:relative; display:flex; align-items:flex-start; gap:20px; }
.po-avatar {
    width:88px; height:88px; border-radius:18px; flex-shrink:0;
    background:rgba(255,255,255,.2); border:3px solid rgba(255,255,255,.4);
    display:flex; align-items:center; justify-content:center;
    font-size:34px; font-weight:800; color:#fff; text-transform:uppercase;
    box-shadow:0 4px 18px rgba(0,0,0,.25);
}
.po-hero-info { flex:1; min-width:0; }
.po-hero-name { font-size:22px; font-weight:800; margin:0 0 4px; text-shadow:0 1px 4px rgba(0,0,0,.2); display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.po-hero-meta { font-size:13px; opacity:.88; margin:3px 0; display:flex; align-items:center; gap:6px; }
.po-hero-meta i { opacity:.7; }
.po-hero-meta a { color:rgba(255,255,255,.9); text-decoration:none; }
.po-hero-meta a:hover { text-decoration:underline; }
.po-hero-actions { display:flex; gap:8px; flex-shrink:0; align-self:flex-start; }
.po-stat-bar {
    position:relative; margin:18px -28px 0; padding:12px 28px;
    background:rgba(0,0,0,.18); border-top:1px solid rgba(255,255,255,.1);
    border-radius:0 0 14px 14px; display:flex; gap:6px; flex-wrap:wrap; align-items:center;
}
.po-stat-pill {
    display:inline-flex; align-items:center; gap:6px; padding:6px 14px;
    border-radius:20px; font-size:12px; font-weight:700;
    background:rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.2);
    backdrop-filter:blur(4px); cursor:default;
}
.po-stat-pill.danger { background:rgba(231,76,60,.4); border-color:rgba(231,76,60,.5); }
.po-stat-pill.warning { background:rgba(243,156,18,.4); border-color:rgba(243,156,18,.5); }
.po-stat-pill.success { background:rgba(39,174,96,.3); border-color:rgba(39,174,96,.4); }
.po-stat-pill.finance { background:rgba(99,102,241,.35); border-color:rgba(99,102,241,.5); }

/* ── Cards ────────────────────────────────────────── */
.vc-card { background:#fff; border-radius:10px; box-shadow:0 1px 5px rgba(0,0,0,.08); margin-bottom:16px; overflow:hidden; border:1px solid #e8ecf1; }
.vc-card-header { padding:10px 16px; border-bottom:1px solid #f1f5f9; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; color:#64748b; display:flex; align-items:center; gap:7px; }
.vc-card-body { padding:14px 16px; }

/* ── Info rows ────────────────────────────────────── */
.info-row { display:flex; justify-content:space-between; align-items:flex-start; padding:6px 0; border-bottom:1px solid #f8f8f8; font-size:12.5px; }
.info-row:last-child { border-bottom:none; }
.info-key { font-weight:600; color:#555; display:flex; align-items:center; gap:5px; flex-shrink:0; min-width:110px; }
.info-val { color:#333; text-align:right; word-break:break-word; }

/* ── Pet cards ────────────────────────────────────── */
.pet-card-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; }
.pet-card {
    border-radius:12px; border:1px solid #e8ecf1; background:#fff;
    overflow:hidden; transition:box-shadow .18s, transform .18s;
    display:flex; flex-direction:column; position:relative;
    box-shadow:0 1px 4px rgba(0,0,0,.07);
}
.pet-card:hover { box-shadow:0 6px 20px rgba(0,0,0,.12); transform:translateY(-2px); }
.pet-card-top { padding:16px 14px 10px; flex:1; }
.pet-card-icon { font-size:28px; margin-bottom:8px; line-height:1; }
.pet-card-name { font-size:14px; font-weight:800; color:#1e293b; margin-bottom:2px; }
.pet-card-sub  { font-size:11px; color:#94a3b8; margin-bottom:6px; }
.pet-card-badges { display:flex; gap:4px; flex-wrap:wrap; margin-top:4px; }
.pet-card-footer { padding:8px 12px; background:#f8fafc; border-top:1px solid #f1f5f9; display:flex; align-items:center; justify-content:space-between; }
.vax-alert-dot { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:700; padding:2px 7px; border-radius:10px; }
.vax-alert-dot.danger  { background:#fef2f2; color:#e74c3c; border:1px solid #fecaca; }
.vax-alert-dot.warning { background:#fffbeb; color:#d97706; border:1px solid #fde68a; }
.vax-alert-dot.ok      { background:#f0fdf4; color:#16a34a; border:1px solid #bbf7d0; }

/* ── Vaccination section ──────────────────────────── */
.vax-section-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:12px; flex-wrap:wrap; gap:8px; }
.vax-toggle-btn { display:inline-flex; align-items:center; gap:5px; font-size:11px; font-weight:700; padding:4px 10px; border-radius:20px; border:1.5px solid #e2e8f0; background:#fff; color:#64748b; cursor:pointer; transition:all .13s; }
.vax-toggle-btn.active { background:#2980b9; border-color:#2980b9; color:#fff; }

.vax-row { display:flex; align-items:center; gap:10px; padding:9px 12px; border-bottom:1px solid #f0f4f8; transition:background .12s; }
.vax-row:last-child { border-bottom:none; }
.vax-row:hover { background:#f8fafc; }
.vax-row-stripe { width:4px; height:34px; border-radius:4px; flex-shrink:0; }
.vax-row-body { flex:1; min-width:0; }
.vax-row-name { font-size:13px; font-weight:700; color:#1e293b; }
.vax-row-pet  { font-size:11px; color:#64748b; }
.vax-row-date { font-size:11px; color:#888; text-align:right; white-space:nowrap; flex-shrink:0; }
.vax-row-badge { font-size:10px; font-weight:700; padding:2px 8px; border-radius:10px; color:#fff; white-space:nowrap; flex-shrink:0; }

.vax-card { display:flex; flex-direction:column; background:#fff; border-radius:10px; border:1px solid #eee; padding:12px 14px; margin-bottom:8px; box-shadow:0 1px 4px rgba(0,0,0,.05); transition:box-shadow .15s; }
.vax-card:hover { box-shadow:0 3px 10px rgba(0,0,0,.1); }
.vax-card-top { display:flex; align-items:center; gap:8px; margin-bottom:6px; flex-wrap:wrap; }
.vax-card-name { font-size:13px; font-weight:700; color:#1e293b; }
.vax-card-meta { font-size:11px; color:#64748b; display:flex; gap:10px; flex-wrap:wrap; }

/* ── Date filter bar ──────────────────────────────── */
.filter-bar { display:flex; gap:8px; flex-wrap:wrap; align-items:center; padding:10px 14px; background:#f8fafc; border-radius:8px; border:1px solid #e8ecf1; margin-bottom:14px; }
.filter-bar label { font-size:10px; font-weight:700; text-transform:uppercase; color:#94a3b8; margin:0; white-space:nowrap; }
.filter-bar .form-control { height:30px; font-size:12px; border-radius:6px; border:1.5px solid #e2e8f0; }

/* ── Finance card ─────────────────────────────────── */
.finance-row { display:flex; justify-content:space-between; align-items:center; padding:7px 0; border-bottom:1px solid #f5f5f5; font-size:12.5px; }
.finance-row:last-child { border-bottom:none; }
.finance-key { color:#64748b; font-weight:600; }
.finance-val { font-weight:700; color:#1e293b; }
.finance-val.due { color:#e74c3c; }
</style>
@include('vetClinic::partials._mobile_responsive')
@endsection

@section('content')
@php
$contact   = $owner->contact;
$name      = optional($contact)->name ?? optional($contact)->supplier_business_name ?? '—';
$initial   = mb_strtoupper(mb_substr($name, 0, 1));
$mobile    = optional($contact)->mobile ?? null;
$email     = optional($contact)->email ?? null;

$totalOverdue  = $overdueVaccinations->count();
$totalDueSoon  = $dueSoonVaccinations->count();
$totalPets     = $pets->count();
$totalMissed   = $pets->sum('missed_apt_count');

$currency = session('currency_symbol', '');
@endphp

<section class="content-header" style="display:none;"></section>
<section class="content">

{{-- Item 2.2 / 3.x — block status banner + manual block/unblock form.
     Bug #10 fix: the modals + script now sit OUTSIDE the if/elseif so
     the unblock modal is ALWAYS in the DOM, regardless of whether the
     owner is currently blocked. Previously the unblock modal lived in
     the @elseif (not-blocked) branch, so when the owner WAS blocked the
     banner's unblock button found no modal and silently did nothing. --}}
@if($owner->is_blocked)
<div style="background:#dc2626;color:#fff;padding:12px 18px;border-radius:8px;margin-bottom:14px;display:flex;align-items:center;gap:12px;">
    <i class="fa fa-ban" style="font-size:24px;"></i>
    <div style="flex:1;">
        <div style="font-weight:800;font-size:14px;">BLOCKED</div>
        <div style="font-size:12px;opacity:.95;">{{ $owner->blocked_reason }}</div>
        @if($owner->blocked_at)
        <div style="font-size:11px;opacity:.8;margin-top:2px;">
            Blocked {{ \Carbon\Carbon::parse($owner->blocked_at)->diffForHumans() }}
            @if($owner->block_avg_rating !== null)
                · cumulative rating at block was {{ number_format($owner->block_avg_rating, 2) }}/5 over {{ $owner->block_rating_count }} ratings
            @endif
        </div>
        @endif
    </div>
    @can('vet_clinic.manage_owner_blocking')
    <button type="button" class="btn btn-sm btn-success vc-unblock-btn"
            data-toggle="modal" data-target="#vcUnblockModal"
            data-form-action="{{ route('vc.owner-blocking.unblock', $owner->id) }}"
            data-owner-name="{{ $name }}"
            data-has-backup="{{ $owner->credit_limit_backup !== null ? '1' : '0' }}"
            data-backup-value="{{ $owner->credit_limit_backup }}">
        <i class="fa fa-lock-open"></i> Unblock
    </button>
    @endcan
</div>
@elseif(auth()->user()->can('vet_clinic.manage_owner_blocking'))
<div style="margin-bottom:8px;text-align:right;">
    <button type="button" class="btn btn-xs btn-default" data-toggle="modal" data-target="#vcBlockModal"
            style="color:#dc2626;border-color:#fecaca;">
        <i class="fa fa-ban"></i> Block this owner-
    </button>
</div>
@endif

{{-- Block + Unblock modals + script.
     #3a deep-fix: render UNCONDITIONALLY (no @can wrapper). The trigger
     buttons are still gated by @can, but the modal markup + click
     handler must always be in the DOM. Symptom report was "Unblock
     button does nothing" which - given the button IS visible - means
     either: (a) JS handler never bound (now defence-in-depth fixed by
     always loading), or (b) the user doesn't have manage_owner_blocking
     yet (fixed by the 2026_05_31_000008 permission backfill migration).
     The controller still enforces the permission server-side on submit. --}}
@unless($owner->is_blocked)
<div class="modal fade" id="vcBlockModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="{{ route('vc.owner-blocking.block', $owner->id) }}">
            @csrf
            <div class="modal-content">
                <div class="modal-header" style="background:#dc2626;color:#fff;">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"><i class="fa fa-ban"></i> Block {{ $name }}</h4>
                </div>
                <div class="modal-body">
                    <p style="color:#7f1d1d;">
                        Blocking this owner will prevent new appointment bookings and zero their
                        credit limit (the prior limit is snapshotted and can be restored on unblock).
                    </p>
                    <div class="form-group">
                        <label>Reason <span class="text-danger">*</span></label>
                        <textarea name="reason" class="form-control" rows="3" required
                                  placeholder="Why is this owner being blocked? This is visible to all managers."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger"><i class="fa fa-ban"></i> Block</button>
                </div>
            </div>
        </form>
    </div>
</div>
@endunless

@include('vetClinic::partials._unblock_modal')
@include('vetClinic::partials._send_message_modal')

@php
    // Item #3 - channel availability for this owner. Computed once so
    // the trigger button below can carry the right data-* flags.
    $vcMsgChannels = app(\Modules\VetClinic\Services\OwnerMessagingService::class)
        ->availableChannels($contact);
    $vcAnyChannel = $vcMsgChannels['wa'] || $vcMsgChannels['sms'] || $vcMsgChannels['email'];
@endphp

{{-- Hero --}}
<div class="po-hero">
    <div class="po-hero-overlay"></div>
    <div class="po-hero-bg"><i class="fas fa-user"></i></div>
    <div class="po-hero-top">
        <div class="po-avatar">{{ $initial }}</div>
        <div class="po-hero-info">
            <div class="po-hero-name">
                {{ $name }}
                @if($owner->email_confirmed)
                    <span class="label label-success" style="font-size:10px;background:rgba(39,174,96,.8);"><i class="fa fa-check"></i> Verified</span>
                @endif
            </div>
            @if($mobile)
            <div class="po-hero-meta"><i class="fa fa-phone"></i> {{ $mobile }}</div>
            @endif
            @if($email)
            <div class="po-hero-meta"><i class="fa fa-envelope"></i> <a href="mailto:{{ $email }}">{{ $email }}</a></div>
            @endif
            @if($owner->occupation)
            <div class="po-hero-meta"><i class="fa fa-briefcase"></i> {{ $owner->occupation }}</div>
            @endif
        </div>
        <div class="po-hero-actions">
            @can('vet_clinic.manage_pet_owners')
            <a href="{{ route('vc.pet-owners.edit', $owner->id) }}" class="btn btn-sm" style="background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.35);border-radius:7px;">
                <i class="fa fa-edit"></i> Edit
            </a>
            @endcan
            @can('vet_clinic.manage_pets')
            <a href="{{ route('vc.pets.create') }}?contact_id={{ $owner->contact_id }}" class="btn btn-sm" style="background:rgba(39,174,96,.7);color:#fff;border:1px solid rgba(39,174,96,.5);border-radius:7px;">
                <i class="fa fa-plus"></i> Add Pet
            </a>
            @endcan
        </div>
    </div>
    <div class="po-stat-bar">
        <span class="po-stat-pill"><i class="fas fa-paw"></i> {{ $totalPets }} Pet{{ $totalPets != 1 ? 's' : '' }}</span>
        @if($totalOverdue > 0)
            <span class="po-stat-pill danger"><i class="fas fa-exclamation-circle"></i> {{ $totalOverdue }} Overdue Vaccine{{ $totalOverdue != 1 ? 's' : '' }}</span>
        @elseif($totalDueSoon > 0)
            <span class="po-stat-pill warning"><i class="fas fa-clock"></i> {{ $totalDueSoon }} Due Soon</span>
        @else
            <span class="po-stat-pill success"><i class="fas fa-check-circle"></i> All Vaccines OK</span>
        @endif
        @if($totalMissed > 0)
            <span class="po-stat-pill warning"><i class="fas fa-calendar-times"></i> {{ $totalMissed }} Missed Apt{{ $totalMissed != 1 ? 's' : '' }}</span>
        @endif
        @if($dueAmount > 0)
            <span class="po-stat-pill danger" style="margin-left:auto;">
                <i class="fas fa-exclamation-triangle"></i> {{ $currency }}{{ number_format($dueAmount, 2) }} Due
            </span>
        @elseif($invoiceCount > 0)
            <span class="po-stat-pill finance" style="margin-left:auto;">
                <i class="fas fa-file-invoice"></i> {{ $invoiceCount }} Invoice{{ $invoiceCount != 1 ? 's' : '' }} · {{ $currency }}{{ number_format($totalSell, 2) }}
            </span>
        @endif
    </div>
</div>

<div class="row">

    {{-- LEFT SIDEBAR ────────────────────────── --}}
    <div class="col-md-3">

        {{-- Contact Info --}}
        <div class="vc-card">
            <div class="vc-card-header" style="display:flex;align-items:center;gap:8px;">
                <i class="fa fa-address-card"></i> Contact Details
                @if($vcAnyChannel)
                @can('vet_clinic.manage_pet_owners')
                <button type="button" class="btn btn-xs btn-info vc-send-msg-btn"
                        style="margin-left:auto;"
                        data-owner-id="{{ $owner->id }}"
                        data-owner-name="{{ $name }}"
                        data-has-wa="{{ $vcMsgChannels['wa']    ? 1 : 0 }}"
                        data-has-sms="{{ $vcMsgChannels['sms']   ? 1 : 0 }}"
                        data-has-email="{{ $vcMsgChannels['email'] ? 1 : 0 }}"
                        data-has-push="{{ ($vcMsgChannels['push'] ?? false) ? 1 : 0 }}"
                        data-push-cats="{{ implode(',', $vcMsgChannels['push_categories'] ?? []) }}"
                        data-send-url="{{ route('vc.pet-owners.send-message', $owner->id) }}">
                    <i class="fa fa-paper-plane"></i> Send Message
                </button>
                @endcan
                @endif
            </div>
            <div class="vc-card-body" style="padding:8px 14px;">
                @if($mobile)
                @php
                    $waState = optional($contact)->vc_has_whatsapp;
                    $waBadge = $waState === 1
                        ? '<span title="WhatsApp confirmed available" style="display:inline-flex;align-items:center;gap:3px;font-size:10.5px;font-weight:700;color:#16a34a;background:#dcfce7;border:1px solid #86efac;border-radius:10px;padding:1px 7px;margin-left:6px;"><i class="fab fa-whatsapp"></i> WA</span>'
                        : ($waState === 0
                            ? '<span title="Confirmed NO WhatsApp" style="display:inline-flex;align-items:center;gap:3px;font-size:10.5px;font-weight:700;color:#dc2626;background:#fef2f2;border:1px solid #fecaca;border-radius:10px;padding:1px 7px;margin-left:6px;"><i class="fas fa-ban"></i> No WA</span>'
                            : '<span title="WhatsApp availability unknown" style="display:inline-flex;align-items:center;gap:3px;font-size:10.5px;font-weight:700;color:#64748b;background:#f1f5f9;border:1px solid #cbd5e1;border-radius:10px;padding:1px 7px;margin-left:6px;"><i class="fas fa-question"></i> WA?</span>');
                @endphp
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-phone fa-fw"></i> Mobile</span>
                    <span class="info-val">
                        <a href="tel:{{ $mobile }}">{{ $mobile }}</a> {!! $waBadge !!}
                    </span>
                </div>
                @can('vet_clinic.manage_pet_owners')
                {{-- Item #2 - WA availability switcher. Three-state cycle:
                     Unknown -> Yes -> No -> Unknown. Buttons are radios
                     dressed up as pills; selected state shows colour. --}}
                <div class="info-row">
                    <span class="info-key"><i class="fab fa-whatsapp fa-fw"></i> WhatsApp</span>
                    <span class="info-val">
                        <span class="vc-wa-toggle" data-owner="{{ $owner->id }}">
                            @foreach(['yes'=>'Yes','no'=>'No','unknown'=>'Unknown'] as $val => $label)
                                @php
                                    $isOn = ($waState === 1 && $val === 'yes')
                                         || ($waState === 0 && $val === 'no')
                                         || ($waState === null && $val === 'unknown');
                                @endphp
                                <button type="button" class="vc-wa-opt {{ $isOn ? 'on' : '' }}" data-val="{{ $val }}">{{ $label }}</button>
                            @endforeach
                        </span>
                    </span>
                </div>
                <script>
                $(function () {
                    $('.vc-wa-toggle .vc-wa-opt').on('click', function () {
                        var $btn = $(this);
                        var $box = $btn.closest('.vc-wa-toggle');
                        var ownerId = $box.data('owner');
                        var val = $btn.data('val');
                        $box.find('.vc-wa-opt').removeClass('on');
                        $btn.addClass('on');
                        $.post('{{ url('vet-clinic/pet-owners') }}/' + ownerId + '/whatsapp', {
                            _token: '{{ csrf_token() }}',
                            state: val
                        }).done(function () {
                            toastr.success('WhatsApp availability saved.');
                        }).fail(function () {
                            toastr.error('Could not save WhatsApp state.');
                        });
                    });
                });
                </script>
                <style>
                .vc-wa-toggle { display:inline-flex; gap:3px; border:1px solid #e2e8f0; border-radius:14px; padding:2px; background:#fff; }
                .vc-wa-opt { font-size:10.5px; font-weight:600; border:none; background:none; color:#64748b; padding:2px 9px; border-radius:11px; cursor:pointer; transition:all .12s; }
                .vc-wa-opt:hover { background:#f1f5f9; }
                .vc-wa-opt.on[data-val="yes"]     { background:#16a34a; color:#fff; }
                .vc-wa-opt.on[data-val="no"]      { background:#dc2626; color:#fff; }
                .vc-wa-opt.on[data-val="unknown"] { background:#64748b; color:#fff; }
                </style>
                @endcan
                @endif
                @if($email)
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-envelope fa-fw"></i> Email</span>
                    <span class="info-val" style="font-size:11.5px;word-break:break-all;"><a href="mailto:{{ $email }}">{{ $email }}</a>
                        @if($owner->email_confirmed)
                            <span class="label label-success" style="font-size:9px;"><i class="fa fa-check"></i></span>
                        @else
                            <span class="label label-default" style="font-size:9px;">Unverified</span>
                        @endif
                    </span>
                </div>
                @endif
                @if($owner->occupation)
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-briefcase fa-fw"></i> Occupation</span>
                    <span class="info-val">{{ $owner->occupation }}</span>
                </div>
                @endif
                @if($owner->referred_by)
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-user-plus fa-fw"></i> Referred By</span>
                    <span class="info-val">{{ $owner->referred_by }}</span>
                </div>
                @endif
                @if($owner->emergency_contact_name)
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-ambulance fa-fw"></i> Emergency</span>
                    <span class="info-val">
                        {{ $owner->emergency_contact_name }}
                        @if($owner->emergency_contact_phone) <br><small>{{ $owner->emergency_contact_phone }}</small>@endif
                        @if($owner->emergency_contact_relation) <br><small class="text-muted">{{ $owner->emergency_contact_relation }}</small>@endif
                    </span>
                </div>
                @endif
                @if($owner->notes)
                <div class="info-row">
                    <span class="info-key"><i class="fa fa-comment fa-fw"></i> Notes</span>
                    <span class="info-val" style="font-size:11.5px;">{{ $owner->notes }}</span>
                </div>
                @endif
            </div>
        </div>

        {{-- Financials --}}
        @if($invoiceCount > 0)
        <div class="vc-card">
            <div class="vc-card-header"><i class="fa fa-file-invoice-dollar"></i> Financials</div>
            <div class="vc-card-body" style="padding:8px 14px;">
                <div class="finance-row">
                    <span class="finance-key">Invoices</span>
                    <span class="finance-val">{{ $invoiceCount }}</span>
                </div>
                <div class="finance-row">
                    <span class="finance-key">Total Billed</span>
                    <span class="finance-val">{{ $currency }}{{ number_format($totalSell, 2) }}</span>
                </div>
                @if($dueAmount > 0)
                <div class="finance-row">
                    <span class="finance-key">Outstanding</span>
                    <span class="finance-val due">{{ $currency }}{{ number_format($dueAmount, 2) }} <i class="fas fa-exclamation-circle" style="font-size:11px;"></i></span>
                </div>
                @endif
            </div>
        </div>
        @endif

        {{-- Item #2 - Preferred Doctor (display + change). Visible to
             everyone with manage_pet_owners perm (the same perm needed
             to reach this page), so a dedicated "change" gate isn't
             added - the inline dropdown is the change UI. --}}
        <div class="vc-card" id="vc_pref_doctor_card">
            <div class="vc-card-header">
                <i class="fa fa-user-md" style="color:#6366f1;"></i> Preferred Doctor
            </div>
            <div class="vc-card-body" style="padding:10px 14px;">
                <div id="vc_pref_doctor_current" style="font-size:13px;color:#334155;margin-bottom:8px;">
                    @if(optional($owner->preferredDoctor)->name)
                        <strong>{{ $owner->preferredDoctor->name }}</strong>
                        @if($owner->preferredDoctor->specialization)
                            <small class="text-muted">· {{ $owner->preferredDoctor->specialization }}</small>
                        @endif
                    @else
                        <span class="text-muted" style="font-style:italic;">No preferred doctor set</span>
                    @endif
                </div>
                @can('vet_clinic.manage_pet_owners')
                <div style="display:flex;gap:6px;align-items:center;">
                    <select id="vc_pref_doctor_select" class="form-control input-sm" style="flex:1;">
                        <option value="">— None —</option>
                        @foreach($doctorsList as $doc)
                            <option value="{{ $doc->id }}" {{ $owner->preferred_doctor_id == $doc->id ? 'selected' : '' }}>
                                {{ $doc->name }}{{ $doc->specialization ? ' — ' . $doc->specialization : '' }}
                            </option>
                        @endforeach
                    </select>
                    <button id="vc_pref_doctor_save" type="button" class="btn btn-sm btn-primary">
                        <i class="fa fa-save"></i>
                    </button>
                </div>
                <script>
                $(function () {
                    $('#vc_pref_doctor_save').on('click', function () {
                        var $btn = $(this).prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
                        $.post('{{ route('vc.pet-owners.set-preferred-doctor', $owner->id) }}', {
                            _token: '{{ csrf_token() }}',
                            preferred_doctor_id: $('#vc_pref_doctor_select').val() || ''
                        }).done(function (res) {
                            if (res.success) {
                                toastr.success('Preferred doctor updated.');
                                var label = res.preferred_doctor || '<span class="text-muted" style="font-style:italic;">No preferred doctor set</span>';
                                $('#vc_pref_doctor_current').html(res.preferred_doctor ? '<strong>' + $('<i>').text(label).html() + '</strong>' : label);
                            }
                        }).fail(function () {
                            toastr.error('Could not save preferred doctor.');
                        }).always(function () {
                            $btn.prop('disabled', false).html('<i class="fa fa-save"></i>');
                        });
                    });
                });
                </script>
                @endcan
            </div>
        </div>

        {{-- Item 2.1 - Owner Ratings (cumulative + history) ------------------
             Cumulative star score across every pet_owner evaluation captured
             for this contact. Empty state shown when there are no ratings
             yet so reviewers still see the section exists. --}}
        <div class="vc-card vc-ratings-card">
            <div class="vc-card-header">
                <i class="fa fa-star" style="color:#f59e0b;"></i> Owner Ratings
                @if($ratingCount)
                <span class="badge" style="background:#475569;margin-left:4px;">{{ $ratingCount }}</span>
                @endif
            </div>
            <div class="vc-card-body" style="padding:10px 14px;">
                @if(!$ratingCount)
                    <div style="text-align:center;color:#94a3b8;font-size:12px;padding:8px 0;">
                        <i class="far fa-star" style="font-size:22px;opacity:.4;display:block;margin-bottom:5px;"></i>
                        No ratings yet.<br>
                        <small>Doctors rate the owner from the appointment page after a completed visit.</small>
                    </div>
                @else
                    {{-- Cumulative score ----------------------------------- --}}
                    @php
                        // Round to nearest half-star for display: 0, .5, 1, 1.5 ... 5
                        $fullStars = floor($ratingAverage);
                        $halfStar  = ($ratingAverage - $fullStars) >= 0.25 && ($ratingAverage - $fullStars) < 0.75;
                        if (($ratingAverage - $fullStars) >= 0.75) { $fullStars++; $halfStar = false; }
                        $emptyStars = 5 - $fullStars - ($halfStar ? 1 : 0);
                        // Colour-code based on percentage band:
                        //   < 50%  red  (poor) | 50-70 amber | > 70 green
                        $scoreColour = $ratingPercent >= 70 ? '#16a34a'
                                     : ($ratingPercent >= 50 ? '#d97706' : '#dc2626');
                    @endphp
                    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
                        <div style="font-size:24px;font-weight:800;color:{{ $scoreColour }};line-height:1;">
                            {{ number_format($ratingAverage, 2) }}
                        </div>
                        <div style="flex:1;">
                            <div style="color:#f59e0b;font-size:14px;letter-spacing:1px;">
                                @for($i = 0; $i < $fullStars; $i++)<i class="fas fa-star"></i>@endfor
                                @if($halfStar)<i class="fas fa-star-half-alt"></i>@endif
                                @for($i = 0; $i < $emptyStars; $i++)<i class="far fa-star" style="color:#cbd5e1;"></i>@endfor
                            </div>
                            <div style="font-size:11px;color:#64748b;margin-top:2px;">
                                {{ $ratingPercent }}% over {{ $ratingCount }} rating{{ $ratingCount > 1 ? 's' : '' }}
                                @if($ratingFlagged)
                                · <span style="color:#dc2626;font-weight:700;"><i class="fa fa-flag"></i> {{ $ratingFlagged }} flagged</span>
                                @endif
                            </div>
                        </div>
                    </div>

                    {{-- Per-rating list -------------------------------------- --}}
                    <div class="vc-ratings-list" style="margin-top:8px;border-top:1px dashed #e2e8f0;padding-top:8px;max-height:280px;overflow-y:auto;">
                        @foreach($ratings as $r)
                            @php
                                $rDate = $r->created_at ? \Carbon\Carbon::parse($r->created_at)->format(session('business.date_format','d M Y')) : '-';
                                $rPct  = $r->avg_rating ? round(($r->avg_rating / 5) * 100) : null;
                                $rCol  = $rPct === null ? '#94a3b8'
                                       : ($rPct >= 70 ? '#16a34a' : ($rPct >= 50 ? '#d97706' : '#dc2626'));
                                $evName = trim(
                                    trim(($r->evaluator->first_name ?? '') . ' ' . ($r->evaluator->last_name ?? ''))
                                    ?: ($r->evaluator->surname ?? '')
                                ) ?: '-';
                            @endphp
                            <div style="display:flex;align-items:flex-start;gap:8px;padding:6px 0;border-bottom:1px dotted #f1f5f9;font-size:11.5px;">
                                <div style="font-size:14px;font-weight:800;color:{{ $rCol }};min-width:32px;text-align:center;">
                                    {{ number_format($r->avg_rating, 1) }}
                                </div>
                                <div style="flex:1;min-width:0;">
                                    <div style="color:#1e293b;">
                                        <strong>{{ $rDate }}</strong>
                                        @if(optional($r->appointment)->ref_no)
                                        · <a href="{{ route('vc.appointments.show', $r->appointment_id) }}"
                                              style="color:#2980b9;text-decoration:none;">#{{ $r->appointment->ref_no }}</a>
                                        @endif
                                        @if($r->flagged_for_review)
                                        · <span style="color:#dc2626;font-weight:700;"><i class="fa fa-flag"></i> Flagged</span>
                                        @endif
                                    </div>
                                    <div style="color:#64748b;font-size:10.5px;">
                                        by {{ $evName }}
                                        @if(optional(optional($r->appointment)->pet)->petname)
                                            · pet: {{ $r->appointment->pet->petname }}
                                        @endif
                                        @if(optional(optional($r->appointment)->doctor)->name)
                                            · dr: {{ $r->appointment->doctor->name }}
                                        @endif
                                    </div>
                                    @if($r->notes)
                                    <div style="color:#475569;font-size:11px;margin-top:2px;font-style:italic;">
                                        "{{ \Illuminate\Support\Str::limit($r->notes, 140) }}"
                                    </div>
                                    @endif
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>

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

    {{-- RIGHT MAIN ──────────────────────────── --}}
    <div class="col-md-9">

        {{-- Pets Section --}}
        <div class="vc-card">
            <div class="vc-card-header">
                <i class="fas fa-paw"></i> Pets
                <span class="badge" style="background:#2980b9;margin-left:4px;">{{ $totalPets }}</span>
            </div>
            <div class="vc-card-body">
                @if($pets->isEmpty())
                    <div style="text-align:center;padding:30px;color:#94a3b8;">
                        <div style="font-size:40px;margin-bottom:10px;">🐾</div>
                        <p style="font-size:13px;">No pets registered yet.</p>
                        @can('vet_clinic.manage_pets')
                        <a href="{{ route('vc.pets.create') }}?contact_id={{ $owner->contact_id }}" class="btn btn-success btn-sm">
                            <i class="fa fa-plus"></i> Add First Pet
                        </a>
                        @endcan
                    </div>
                @else
                    <div class="pet-card-grid">
                        @foreach($pets as $pet)
                        @php
                            $speciesIcons = ['dog'=>'🐕','cat'=>'🐈','rabbit'=>'🐇','bird'=>'🦜','fish'=>'🐟'];
                            $icon = $speciesIcons[strtolower($pet->species ?? '')] ?? '🐾';
                            $hasOverdue  = $pet->overdue_vax_count > 0;
                            $hasDueSoon  = $pet->due_soon_vax_count > 0;
                            $hasMissed   = $pet->missed_apt_count > 0;
                            $borderColor = $hasOverdue ? '#fca5a5' : ($hasDueSoon ? '#fde68a' : '#e8ecf1');
                        @endphp
                        <div class="pet-card" style="border-color:{{ $borderColor }};">
                            @if($hasOverdue)
                            <div style="height:3px;background:#e74c3c;"></div>
                            @elseif($hasDueSoon)
                            <div style="height:3px;background:#f39c12;"></div>
                            @else
                            <div style="height:3px;background:#27ae60;"></div>
                            @endif
                            <div class="pet-card-top">
                                <div class="pet-card-icon">{{ $icon }}</div>
                                <div class="pet-card-name">{{ $pet->petname }}</div>
                                <div class="pet-card-sub">
                                    {{ $pet->species }}{{ $pet->breed ? ' · '.$pet->breed : '' }}
                                    @if($pet->dob) · {{ $pet->age }} yrs @endif
                                </div>
                                <div class="pet-card-badges">
                                    <span class="label label-{{ $pet->status === 'active' ? 'success' : 'danger' }}" style="font-size:10px;">{{ ucfirst($pet->status) }}</span>
                                    @if($pet->deceased)
                                        <span class="label label-danger" style="font-size:10px;">Deceased</span>
                                    @endif
                                </div>
                                @if($hasOverdue)
                                <div class="vax-alert-dot danger" style="margin-top:6px;">
                                    <i class="fas fa-exclamation-circle"></i> {{ $pet->overdue_vax_count }} overdue
                                </div>
                                @elseif($hasDueSoon)
                                <div class="vax-alert-dot warning" style="margin-top:6px;">
                                    <i class="fas fa-clock"></i> {{ $pet->due_soon_vax_count }} due soon
                                </div>
                                @endif
                                @if($hasMissed)
                                <div class="vax-alert-dot warning" style="margin-top:4px;">
                                    <i class="fas fa-calendar-times"></i> {{ $pet->missed_apt_count }} missed
                                </div>
                                @endif
                            </div>
                            <div class="pet-card-footer">
                                <a href="{{ route('vc.pets.show', $pet->id) }}" class="btn btn-xs btn-info"><i class="fa fa-eye"></i> Profile</a>
                                @can('vet_clinic.manage_pets')
                                <a href="{{ route('vc.pets.edit', $pet->id) }}" class="btn btn-xs btn-default"><i class="fa fa-edit"></i></a>
                                @endcan
                            </div>
                        </div>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>

        {{-- Vaccinations Section --}}
        @if($overdueVaccinations->isNotEmpty() || $dueSoonVaccinations->isNotEmpty())
        <div class="vc-card">
            <div class="vc-card-header">
                <i class="fas fa-syringe"></i> Vaccination Alerts
                @if($totalOverdue > 0)
                <span class="label label-danger" style="font-size:10px;margin-left:4px;">{{ $totalOverdue }} Overdue</span>
                @endif
                @if($totalDueSoon > 0)
                <span class="label label-warning" style="font-size:10px;margin-left:4px;">{{ $totalDueSoon }} Due Soon</span>
                @endif
                <div style="margin-left:auto;display:flex;gap:5px;">
                    <button class="vax-toggle-btn active" id="vax-list-btn" data-view="list"><i class="fa fa-list"></i> List</button>
                    <button class="vax-toggle-btn" id="vax-card-btn" data-view="card"><i class="fa fa-th-large"></i> Cards</button>
                </div>
            </div>
            <div class="vc-card-body" style="padding:0;">

                {{-- Filter bar --}}
                <div class="filter-bar" style="border-radius:0;border-left:none;border-right:none;border-top:none;">
                    <label><i class="fa fa-filter"></i> Filter:</label>
                    <button class="btn btn-xs vax-filter-btn active" data-filter="all" style="border-radius:12px;border:1.5px solid #e74c3c;color:#e74c3c;background:transparent;">All ({{ $totalOverdue + $totalDueSoon }})</button>
                    @if($totalOverdue > 0)
                    <button class="btn btn-xs vax-filter-btn" data-filter="overdue" style="border-radius:12px;border:1.5px solid #e74c3c;color:#e74c3c;background:transparent;"><i class="fa fa-exclamation-circle"></i> Overdue ({{ $totalOverdue }})</button>
                    @endif
                    @if($totalDueSoon > 0)
                    <button class="btn btn-xs vax-filter-btn" data-filter="due_soon" style="border-radius:12px;border:1.5px solid #f39c12;color:#f39c12;background:transparent;"><i class="fa fa-clock"></i> Due Soon ({{ $totalDueSoon }})</button>
                    @endif
                    <div style="margin-left:auto;">
                        <input type="text" id="vax_date_filter" class="form-control" placeholder="Filter by date range" readonly style="width:220px;">
                    </div>
                </div>

                {{-- List view --}}
                <div id="vax-list-view">
                    @foreach($overdueVaccinations as $v)
                    @php $daysOver = (int)\Carbon\Carbon::parse($v->administered_date)->diffInDays(now(), false); @endphp
                    <div class="vax-row" data-vax-type="overdue" data-vax-date="{{ optional($v->administered_date)->format('Y-m-d') }}">
                        <div class="vax-row-stripe" style="background:#e74c3c;"></div>
                        <div class="vax-row-body">
                            <div class="vax-row-name">{{ optional($v->vaccineType)->name ?? '—' }}</div>
                            <div class="vax-row-pet"><i class="fas fa-paw"></i> {{ optional($v->pet)->petname ?? '—' }}</div>
                        </div>
                        <span class="vax-row-badge" style="background:#e74c3c;">{{ $daysOver }} days overdue</span>
                        <div class="vax-row-date">{{ optional($v->administered_date)->format('d M Y') ?? '—' }}</div>
                        @if($v->pet)
                        <a href="{{ route('vc.pets.show', $v->pet->id) }}#tab-vaccinations" class="btn btn-xs btn-danger" title="Go to pet"><i class="fa fa-paw"></i></a>
                        @endif
                    </div>
                    @endforeach

                    @foreach($dueSoonVaccinations as $v)
                    @php $daysLeft = (int)\Carbon\Carbon::parse($v->administered_date)->diffInDays(now(), false) * -1; @endphp
                    <div class="vax-row" data-vax-type="due_soon" data-vax-date="{{ optional($v->administered_date)->format('Y-m-d') }}">
                        <div class="vax-row-stripe" style="background:#f39c12;"></div>
                        <div class="vax-row-body">
                            <div class="vax-row-name">{{ optional($v->vaccineType)->name ?? '—' }}</div>
                            <div class="vax-row-pet"><i class="fas fa-paw"></i> {{ optional($v->pet)->petname ?? '—' }}</div>
                        </div>
                        <span class="vax-row-badge" style="background:#f39c12;">In {{ $daysLeft }} days</span>
                        <div class="vax-row-date">{{ optional($v->administered_date)->format('d M Y') ?? '—' }}</div>
                        @if($v->pet)
                        <a href="{{ route('vc.pets.show', $v->pet->id) }}#tab-vaccinations" class="btn btn-xs btn-warning" title="Go to pet"><i class="fa fa-paw"></i></a>
                        @endif
                    </div>
                    @endforeach
                </div>

                {{-- Card view --}}
                <div id="vax-card-view" style="display:none;padding:14px;">
                    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;" id="vax-card-grid">
                        @foreach($overdueVaccinations->merge($dueSoonVaccinations) as $v)
                        @php
                            $isOverdue = \Carbon\Carbon::parse($v->administered_date)->isPast();
                            $bg  = $isOverdue ? '#fef2f2' : '#fffbeb';
                            $bc  = $isOverdue ? '#fecaca' : '#fde68a';
                            $bk  = $isOverdue ? '#e74c3c' : '#f39c12';
                            $label = $isOverdue
                                ? (int)\Carbon\Carbon::parse($v->administered_date)->diffInDays(now()).' days overdue'
                                : 'In '.(int)\Carbon\Carbon::parse($v->administered_date)->diffInDays(now(), false) * -1 .' days';
                        @endphp
                        <div class="vax-card" style="background:{{ $bg }};border-color:{{ $bc }};"
                             data-vax-type="{{ $isOverdue ? 'overdue' : 'due_soon' }}" data-vax-date="{{ optional($v->administered_date)->format('Y-m-d') }}">
                            <div class="vax-card-top">
                                <span style="font-size:12px;font-weight:800;color:{{ $bk }};">{{ optional($v->vaccineType)->name ?? '—' }}</span>
                                <span style="margin-left:auto;font-size:10px;font-weight:700;padding:2px 8px;border-radius:10px;background:{{ $bk }};color:#fff;">{{ $label }}</span>
                            </div>
                            <div class="vax-card-meta">
                                <span><i class="fas fa-paw"></i> {{ optional($v->pet)->petname ?? '—' }}</span>
                                <span><i class="fas fa-calendar"></i> {{ optional($v->administered_date)->format('d M Y') }}</span>
                            </div>
                            @if($v->pet)
                            <div style="margin-top:8px;">
                                <a href="{{ route('vc.pets.show', $v->pet->id) }}#tab-vaccinations" class="btn btn-xs" style="border-radius:6px;background:{{ $bk }};color:#fff;font-size:11px;">
                                    <i class="fa fa-paw"></i> View Pet
                                </a>
                            </div>
                            @endif
                        </div>
                        @endforeach
                    </div>
                </div>

            </div>
        </div>
        @endif

    </div>{{-- /col-md-9 --}}
</div>{{-- /row --}}

@include('vetClinic::partials.notes_panel', [
    'subjectType' => 'owner',
    'subjectId'   => $owner->id,
])

</section>
@endsection

@section('javascript')
<script>
$(document).ready(function () {

    /* ── Vax view toggle ─────────────────────── */
    $('#vax-list-btn, #vax-card-btn').on('click', function () {
        var view = $(this).data('view');
        $('#vax-list-btn, #vax-card-btn').removeClass('active');
        $(this).addClass('active');
        if (view === 'list') { $('#vax-list-view').show(); $('#vax-card-view').hide(); }
        else { $('#vax-list-view').hide(); $('#vax-card-view').show(); }
    });

    /* ── Filter buttons ──────────────────────── */
    var activeFilter = 'all';
    $('.vax-filter-btn').on('click', function () {
        activeFilter = $(this).data('filter');
        $('.vax-filter-btn').css({ background:'transparent' }).removeClass('fw-active');
        $(this).css({ background: activeFilter === 'overdue' ? '#e74c3c' : (activeFilter === 'due_soon' ? '#f39c12' : '#64748b'), color:'#fff' });
        applyVaxFilter();
    });

    /* ── Date range filter ───────────────────── */
    var drpActive = false;
    if (typeof dateRangeSettings !== 'undefined') {
        $('#vax_date_filter').daterangepicker(dateRangeSettings, function(start, end) {
            drpActive = true;
            applyVaxFilter();
        });
        $('#vax_date_filter').on('cancel.daterangepicker', function() {
            $(this).val(''); drpActive = false; applyVaxFilter();
        });
    }

    function applyVaxFilter() {
        var drp = $('#vax_date_filter').data('daterangepicker');
        var fromDate = (drp && drpActive) ? drp.startDate.format('YYYY-MM-DD') : null;
        var toDate   = (drp && drpActive) ? drp.endDate.format('YYYY-MM-DD')   : null;

        $('[data-vax-type]').each(function () {
            var type     = $(this).data('vax-type');
            var dateStr  = $(this).data('vax-date');
            var typeOk   = (activeFilter === 'all' || type === activeFilter);
            var dateOk   = !fromDate || (dateStr >= fromDate && dateStr <= toDate);
            $(this).toggle(typeOk && dateOk);
        });
    }
});
</script>
@endsection
