@extends('layouts.app')

@section('title', 'Test Session — ' . $session->sample_no)

@section('css')
<style>
    .nx-results .nx-abnormal { background:#fcf3e3; }
    .nx-meta dt { color:#64748b; font-weight:600; }
    .nx-meta dd { margin-bottom:8px; }
</style>
@endsection

@section('content')
<section class="content-header">
    <h1>
        <i class="fas fa-flask"></i> Test Session
        <small>{{ $session->sample_no }}</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="{{ route('nx.results.index') }}">{{ __('nx600Lab::lang.test_results') }}</a></li>
        <li class="active">{{ $session->sample_no }}</li>
    </ol>
</section>

<section class="content">
    <div class="row" style="margin-bottom:10px;">
        <div class="col-md-12">
            <a href="{{ route('nx.results.print', $session->id) }}" target="_blank" class="btn btn-default pull-right">
                <i class="fa fa-print"></i> Print Report
            </a>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Sample / Patient'])
                @php
                    // When linked to a VetClinic pet, the pet record is authoritative —
                    // the device-reported fields may be stale or operator-entered.
                    $dispName    = $pet ? $pet->petname : ($session->patient_name ?: '—');
                    $dispId      = $pet ? ($pet->serial_no ?: ($pet->microchip_no ?: 'P' . $pet->id)) : ($session->patient_id ?: '—');
                    $dispSpecies = ($pet && $pet->species) ? ucfirst($pet->species) : $session->species_name;
                    $dispSex     = $pet ? ucfirst($pet->gender) : $session->sex_label;
                    $dispAge     = $pet
                        ? (!is_null($pet->age) ? $pet->age . ' yr' : 'N/A')
                        : ($session->age === 999 ? 'N/A' : $session->age);
                @endphp
                <dl class="nx-meta">
                    <dt>Sample No</dt><dd>{{ $session->sample_no }}</dd>
                    <dt>Patient</dt><dd>{{ $dispName }}</dd>
                    <dt>Patient ID</dt><dd>{{ $dispId }}</dd>
                    <dt>Species / Sex / Age</dt>
                    <dd>{{ $dispSpecies }} / {{ $dispSex }} / {{ $dispAge }}</dd>
                    <dt>Sample Type</dt><dd>{{ $session->sample_type_label }}</dd>
                    <dt>Condition</dt><dd>{{ $session->test_condition }}</dd>
                    @if($pet)
                        <dt>VetClinic Pet</dt>
                        <dd>
                            <a href="{{ route('vc.pets.show', $pet->id) }}">
                                <i class="fas fa-paw"></i> {{ $pet->petname }}
                            </a>
                            @if($pet->owner)
                                <br><small class="text-muted">Owner: {{ $pet->owner->name ?? trim(($pet->owner->first_name ?? '') . ' ' . ($pet->owner->last_name ?? '')) }}</small>
                            @endif
                        </dd>
                    @endif
                </dl>
            @endcomponent
        </div>
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Test Run'])
                <dl class="nx-meta">
                    <dt>Date</dt><dd>{{ $session->test_date?->format('Y-m-d') }}</dd>
                    <dt>Time</dt><dd>{{ $session->test_time }}</dd>
                    <dt>Sample Position</dt><dd>{{ $session->sample_position }}</dd>
                    <dt>Emergency</dt><dd>{{ $session->emergency_test ? 'Yes' : 'No' }}</dd>
                    <dt>Operator</dt><dd>{{ $session->operator_id ?: '—' }}</dd>
                </dl>
            @endcomponent
        </div>
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Device'])
                <dl class="nx-meta">
                    <dt>Comm Type</dt><dd>{{ $session->comm_type }}</dd>
                    <dt>Analyzer ID</dt><dd>{{ $session->analyzer_id ?: '—' }}</dd>
                    <dt>Slide Lot</dt><dd>{{ $session->slide_lot ?: '—' }}</dd>
                    <dt>Device IP</dt><dd>{{ $session->device_ip ?: '—' }}</dd>
                    <dt>Received</dt><dd>{{ $session->created_at?->format('Y-m-d H:i') }}</dd>
                </dl>
            @endcomponent
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Results (' . $session->testResults->count() . ' parameters)'])
                @if(class_exists(\Modules\AiCore\Entities\Services\AiClient::class) && $session->testResults->count())
                <div style="margin-bottom:10px;">
                    <button type="button" class="btn btn-info btn-sm" id="lab_ai_interpret"><i class="fa fa-brain"></i> AI interpret results</button>
                    <div id="lab_ai_panel" style="margin-top:10px;"></div>
                </div>
                @endif
                @include('nx600Lab::sessions._results_table', ['session' => $session])
            @endcomponent
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
var LAB_URL   = '{{ route('aicore.interpret-lab') }}';
var LAB_TOKEN = '{{ csrf_token() }}';
@php
    $labResultsData = $session->testResults->map(function ($r) {
        $flag = '';
        if ($r->is_abnormal) { $flag = $r->warn_high ? 'High' : ($r->warn_low ? 'Low' : 'Abnormal'); }
        return [
            'test'  => trim($r->base_name . $r->sample_suffix),
            'value' => $r->result_display,
            'unit'  => $r->unit,
            'ref'   => trim(($r->ref_lower ?? '') . ' - ' . ($r->ref_upper ?? '')),
            'flag'  => $flag,
        ];
    })->values();
    $labContext = trim('Species: ' . (($pet && $pet->species) ? ucfirst($pet->species) : ($session->species_name ?: 'unknown')) . ', Sex: ' . ($pet ? ucfirst($pet->gender) : ($session->sex_label ?: 'unknown')));
@endphp
var LAB_RESULTS = @json($labResultsData);
var LAB_CONTEXT = @json($labContext);
@include('aiCore::partials._lab_interpret_js')
</script>
@endsection
