@extends('layouts.app')
@section('title', 'Medical Critical Check Report')

@section('content')
<section class="content-header">
    <h1>
        <i class="fa fa-exclamation-triangle" style="color:#dc2626;"></i>
        Medical Critical Check Report
        <small>Visits with out-of-range vitals or critical body-system findings</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('clinic.reports.index') }}"><i class="fa fa-chart-bar"></i> Reports</a></li>
        <li class="active">Critical Check</li>
    </ol>
</section>

<section class="content">
    {{-- ── KPI band ─────────────────────────────────────────── --}}
    <div class="row">
        <div class="col-md-3">
            <div class="info-box bg-red">
                <span class="info-box-icon"><i class="fa fa-heartbeat"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Visits flagged</span>
                    <span class="info-box-number">{{ $kpi['total'] }}</span>
                    <span class="progress-description">{{ $kpi['date_range'] }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-orange">
                <span class="info-box-icon"><i class="fa fa-thermometer-three-quarters"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Critical vitals</span>
                    <span class="info-box-number">{{ $kpi['critical_vitals'] }}</span>
                    <span class="progress-description">vital sign outside critical bounds</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-purple">
                <span class="info-box-icon"><i class="fa fa-flag"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Critical findings</span>
                    <span class="info-box-number">{{ $kpi['critical_finds'] }}</span>
                    <span class="progress-description">body-system finding flagged</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-aqua">
                <span class="info-box-icon"><i class="fa fa-info-circle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">About this report</span>
                    <span class="info-box-number" style="font-size:14px;">Auto-populated</span>
                    <span class="progress-description">re-runs on every consultation save</span>
                </div>
            </div>
        </div>
    </div>

    {{-- ── Filter row ───────────────────────────────────────── --}}
    <div class="box box-default">
        <div class="box-body">
            <form method="GET" action="{{ route('clinic.reports.critical-check') }}" class="form-inline">
                <div class="form-group" style="margin-right:10px;">
                    <label style="margin-right:4px;">From</label>
                    <input type="date" name="from" value="{{ $from }}" class="form-control input-sm">
                </div>
                <div class="form-group" style="margin-right:10px;">
                    <label style="margin-right:4px;">To</label>
                    <input type="date" name="to" value="{{ $to }}" class="form-control input-sm">
                </div>
                <div class="form-group" style="margin-right:10px;">
                    <label style="margin-right:4px;">Doctor</label>
                    <select name="doctor_id" class="form-control input-sm">
                        <option value="">All doctors</option>
                        @foreach($doctors as $d)
                            <option value="{{ $d->id }}" {{ request('doctor_id') == $d->id ? 'selected' : '' }}>
                                {{ $d->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group" style="margin-right:10px;">
                    <label style="margin-right:4px;">Severity</label>
                    <select name="severity" class="form-control input-sm">
                        <option value="any" {{ $minSeverity == 'any' ? 'selected' : '' }}>Any abnormal</option>
                        <option value="critical_only" {{ $minSeverity == 'critical_only' ? 'selected' : '' }}>Critical only</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary btn-sm">
                    <i class="fa fa-filter"></i> Apply
                </button>
                <a href="{{ route('clinic.reports.critical-check') }}" class="btn btn-default btn-sm">
                    <i class="fa fa-times"></i> Reset
                </a>
            </form>
        </div>
    </div>

    {{-- ── Table ────────────────────────────────────────────── --}}
    <div class="box box-danger">
        <div class="box-header">
            <h3 class="box-title">
                <i class="fa fa-list"></i> Flagged Appointments
                <span class="badge bg-red" style="margin-left:6px;">{{ $rows->count() }}</span>
            </h3>
        </div>
        <div class="box-body">
            @if($rows->isEmpty())
                <div style="text-align:center;color:#94a3b8;padding:40px;">
                    <i class="fa fa-check-circle" style="font-size:48px;color:#16a34a;opacity:.6;"></i>
                    <p style="margin-top:12px;">No critical or abnormal findings in this date range. All visits look healthy.</p>
                </div>
            @else
            <table class="table table-condensed table-striped" style="font-size:12.5px;">
                <thead style="background:#fef2f2;">
                    <tr>
                        <th>Date</th>
                        <th>Ref #</th>
                        <th>Patient</th>
                        <th>Contact</th>
                        <th>Doctor</th>
                        <th>Vital flags</th>
                        <th>Critical findings</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                @foreach($rows as $r)
                    @php
                        $vitalsAnn = $r->vitals_critical_json
                            ? (is_array($r->vitals_critical_json) ? $r->vitals_critical_json : json_decode($r->vitals_critical_json, true))
                            : [];
                        $rFindings = $findings->get($r->id, collect());
                        $hasCritical = $r->vitals_critical_count > 0 || $r->findings_critical_count > 0;
                        $vitalCells = [];
                        $vitalMap = [
                            'temperature'      => ['T',  '°C'],
                            'heart_rate'       => ['HR', 'bpm'],
                            'respiratory_rate' => ['RR', '/min'],
                            'weight_kg'        => ['Wt', 'kg'],
                        ];
                        foreach ($vitalMap as $key => [$short, $unit]) {
                            $sev = $vitalsAnn[$key] ?? 'unknown';
                            if (!in_array($sev, ['critical', 'low', 'high'], true)) continue;
                            $val = $r->{$key};
                            if ($val === null || $val === '') continue;
                            $colour = $sev === 'critical' ? '#dc2626' : '#d97706';
                            $icon   = $sev === 'critical' ? 'fa-exclamation-triangle' : 'fa-arrow-' . ($sev === 'low' ? 'down' : 'up');
                            $vitalCells[] = '<span style="display:inline-block;padding:2px 8px;margin:1px;border-radius:10px;background:'
                                . ($sev === 'critical' ? '#fef2f2' : '#fffbeb')
                                . ';border:1px solid ' . $colour . ';color:' . $colour . ';font-weight:600;font-size:11px;">'
                                . '<i class="fa ' . $icon . '"></i> '
                                . $short . ' ' . $val . ' ' . $unit . '</span>';
                        }
                    @endphp
                    <tr style="{{ $hasCritical ? 'border-left:4px solid #dc2626;' : 'border-left:4px solid #d97706;' }}">
                        <td>{{ \Carbon\Carbon::parse($r->appointment_date)->format(session('business.date_format', 'd M Y')) }}</td>
                        <td><span style="font-family:monospace;">{{ $r->ref_no ?? '—' }}</span></td>
                        <td>
                            @if($r->pet)
                            <a href="{{ route('clinic.patients.show', $r->patient_id) }}" style="font-weight:700;">{{ $r->pet->patient_name }}</a>
                            @if(config('cliniccore.show_animal_fields', false))
                            <br><small class="text-muted">{{ ucfirst($r->pet->species ?? '') }}</small>
                            @endif
                            @else — @endif
                        </td>
                        <td><small>{{ optional($r->owner)->name ?? '—' }}</small></td>
                        <td><small>{{ optional($r->doctor)->name ?? '—' }}</small></td>
                        <td>{!! count($vitalCells) ? implode(' ', $vitalCells) : '<span class="text-muted" style="font-size:11px;">—</span>' !!}</td>
                        <td style="max-width:260px;">
                            @if($rFindings->count())
                                @foreach($rFindings as $f)
                                <div style="font-size:11px;line-height:1.4;color:#991b1b;">
                                    <i class="fa fa-flag"></i>
                                    <strong>{{ $f->region_snapshot }}:</strong>
                                    {{ $f->item_label_snapshot }}
                                    @if($f->side) <span style="color:#94a3b8;">({{ strtoupper($f->side) }})</span> @endif
                                    @if($f->value) <em style="color:#7f1d1d;"> — {{ $f->value }}</em> @endif
                                </div>
                                @endforeach
                            @else
                                <span class="text-muted" style="font-size:11px;">—</span>
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('clinic.appointments.show', $r->id) }}" class="btn btn-xs btn-default" target="_blank">
                                <i class="fa fa-eye"></i> Open
                            </a>
                        </td>
                    </tr>
                @endforeach
                </tbody>
            </table>
            @endif
        </div>
    </div>
</section>
@endsection
