@extends('layouts.app')
@section('title', __('clinicCore::lang.imgrep_report'))

@section('css')
@include('clinicCore::partials._mobile_responsive')
<style>
    .imr-wrap { max-width:1000px; }
    .imr-meta { background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:12px 14px; margin-bottom:16px; display:flex; gap:24px; flex-wrap:wrap; }
    .imr-meta div small { display:block; color:#94a3b8; text-transform:uppercase; font-size:10px; letter-spacing:.5px; }
    .imr-sf-row { display:flex; gap:8px; margin-bottom:6px; align-items:center; }
    .imr-sf-row input[type=text] { flex:1; }
    .imr-crit { border:1px solid #fecaca; background:#fef2f2; border-radius:8px; padding:12px; margin-top:8px; }
    .imr-dose { font-size:12px; color:#475569; }
    .imr-locked { background:#fffbeb; border:1px solid #fde68a; border-radius:6px; padding:8px 12px; margin-bottom:14px; color:#92400e; }
</style>
@endsection

@section('content')
@php
    $r        = $report;                       // may be null
    $status   = $r->report_status ?? 'draft';
    $finalised = $r ? in_array($status, ['final','amended'], true) : false;
    $sf       = $r && is_array($r->structured_findings) ? $r->structured_findings : [];
    $canReport = auth()->user()->can('clinic.imaging.report');
    $canVerify = auth()->user()->can('clinic.imaging.verify');
@endphp

<section class="content-header">
    <h1><i class="fa fa-file-medical"></i> {{ __('clinicCore::lang.imgrep_report') }}
        <small>{{ $imagingRequest->ref_no }}</small></h1>
</section>

<section class="content imr-wrap">
    <div class="imr-meta">
        <div><small>{{ __('clinicCore::lang.patient') }}</small><strong>{{ optional($imagingRequest->pet)->patient_name }}</strong></div>
        <div><small>{{ __('clinicCore::lang.modality') }}</small>{{ optional($imagingRequest->modality)->code }} · {{ optional($imagingRequest->modality)->name }}</div>
        <div><small>{{ __('clinicCore::lang.body_region') }}</small>{{ $imagingRequest->body_region ?: '—' }}</div>
        <div><small>{{ __('clinicCore::lang.priority') }}</small>{{ ucfirst($imagingRequest->priority) }}</div>
        <div><small>{{ __('clinicCore::lang.imgrep_report') }}</small>
            <span id="imr-status-badge" class="label label-{{ $finalised ? 'success' : 'default' }}">{{ __('clinicCore::lang.imgrep_rstatus_'.$status) }}</span></div>
        <div class="imr-dose"><small>{{ __('clinicCore::lang.imgrep_cumulative_dose') }}</small>
            @php
                $doseParts = [];
                if (!is_null($cumulativeDose['dap']))     $doseParts[] = 'DAP '.number_format($cumulativeDose['dap'], 2).' Gy·cm²';
                if (!is_null($cumulativeDose['dlp']))     $doseParts[] = 'DLP '.number_format($cumulativeDose['dlp'], 2).' mGy·cm';
                if (!is_null($cumulativeDose['ctdivol'])) $doseParts[] = 'CTDIvol '.number_format($cumulativeDose['ctdivol'], 2).' mGy';
            @endphp
            {{ count($doseParts) ? implode(' · ', $doseParts) : __('clinicCore::lang.imgrep_no_dose') }}
        </div>
    </div>

    @if($finalised)
        <div class="imr-locked">
            <i class="fa fa-lock"></i> {{ __('clinicCore::lang.imgrep_locked_use_amend') }}
            @if($status === 'amended' && $r->amendment_reason)
                <div><small>{{ __('clinicCore::lang.imgrep_amendment_reason') }}: {{ $r->amendment_reason }}</small></div>
            @endif
        </div>
    @endif

    <form id="imr-form">
        <div class="row">
            <div class="col-sm-6 form-group">
                <label>{{ __('clinicCore::lang.radiologist') }}</label>
                <select name="radiologist_id" class="form-control">
                    <option value="">—</option>
                    @foreach($radiologists as $d)
                        <option value="{{ $d->id }}" @selected(($r->radiologist_id ?? null) == $d->id)>{{ $d->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>

        <div class="form-group">
            <label>{{ __('clinicCore::lang.imgrep_structured_findings') }}</label>
            <div id="imr-sf-list">
                @forelse($sf as $row)
                    <div class="imr-sf-row">
                        <input type="text" class="form-control input-sm imr-sf-region" placeholder="{{ __('clinicCore::lang.imgrep_region') }}" value="{{ $row['region'] ?? '' }}">
                        <input type="text" class="form-control input-sm imr-sf-finding" placeholder="{{ __('clinicCore::lang.imgrep_finding') }}" value="{{ $row['finding'] ?? '' }}">
                        <label style="white-space:nowrap;font-weight:normal;"><input type="checkbox" class="imr-sf-abn" @checked(!empty($row['abnormality']))> {{ __('clinicCore::lang.imgrep_abnormal') }}</label>
                        <button type="button" class="btn btn-xs btn-default imr-sf-del">&times;</button>
                    </div>
                @empty
                    <div class="imr-sf-row">
                        <input type="text" class="form-control input-sm imr-sf-region" placeholder="{{ __('clinicCore::lang.imgrep_region') }}">
                        <input type="text" class="form-control input-sm imr-sf-finding" placeholder="{{ __('clinicCore::lang.imgrep_finding') }}">
                        <label style="white-space:nowrap;font-weight:normal;"><input type="checkbox" class="imr-sf-abn"> {{ __('clinicCore::lang.imgrep_abnormal') }}</label>
                        <button type="button" class="btn btn-xs btn-default imr-sf-del">&times;</button>
                    </div>
                @endforelse
            </div>
            <button type="button" class="btn btn-xs btn-default" id="imr-sf-add"><i class="fa fa-plus"></i> {{ __('clinicCore::lang.imgrep_add_finding') }}</button>
        </div>

        <div class="form-group">
            <label>{{ __('clinicCore::lang.imgrep_narrative') }}</label>
            <textarea name="narrative_findings" class="form-control" rows="4">{{ $r->narrative_findings ?? '' }}</textarea>
        </div>
        <div class="form-group">
            <label>{{ __('clinicCore::lang.imgrep_impression') }} <span class="text-danger">*</span></label>
            <textarea name="impression" class="form-control" rows="3">{{ $r->impression ?? '' }}</textarea>
        </div>
        <div class="row">
            <div class="col-sm-6 form-group">
                <label>{{ __('clinicCore::lang.imgrep_recommendation') }}</label>
                <textarea name="recommendation" class="form-control" rows="2">{{ $r->recommendation ?? '' }}</textarea>
            </div>
            <div class="col-sm-6 form-group">
                <label>{{ __('clinicCore::lang.imgrep_comparison') }}</label>
                <textarea name="comparison" class="form-control" rows="2">{{ $r->comparison ?? '' }}</textarea>
            </div>
        </div>

        <div class="form-group">
            <label><input type="checkbox" id="imr-has-critical" name="has_critical" value="1" @checked($r->has_critical ?? false)> {{ __('clinicCore::lang.imgrep_has_critical') }}</label>
            <div class="imr-crit" id="imr-crit-block" style="{{ ($r->has_critical ?? false) ? '' : 'display:none;' }}">
                <div class="form-group">
                    <label>{{ __('clinicCore::lang.imgrep_critical_description') }}</label>
                    <textarea name="critical_description" class="form-control" rows="2">{{ $r->critical_description ?? '' }}</textarea>
                </div>
                <div class="form-group">
                    <label>{{ __('clinicCore::lang.imgrep_critical_communicated_to') }} <span class="text-danger">*</span></label>
                    <input type="text" name="critical_communicated_to" class="form-control" value="{{ $r->critical_communicated_to ?? '' }}" placeholder="{{ __('clinicCore::lang.imgrep_critical_comm_placeholder') }}">
                    <small class="text-muted">{{ __('clinicCore::lang.imgrep_critical_comm_hint') }}</small>
                </div>
            </div>
        </div>

        @if($finalised)
        <div class="form-group" id="imr-amend-reason-block">
            <label>{{ __('clinicCore::lang.imgrep_amendment_reason') }} <span class="text-danger">*</span></label>
            <textarea name="amendment_reason" class="form-control" rows="2"></textarea>
        </div>
        @endif

        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            @if(!$finalised && $canReport)
                <button type="button" class="btn btn-default" id="imr-save" data-status="draft"><i class="fa fa-save"></i> {{ __('clinicCore::lang.imgrep_save_draft') }}</button>
                <button type="button" class="btn btn-info" id="imr-save-prelim" data-status="preliminary"><i class="fa fa-save"></i> {{ __('clinicCore::lang.imgrep_save_preliminary') }}</button>
            @endif
            @if(!$finalised && $canVerify)
                <button type="button" class="btn btn-success" id="imr-finalise"><i class="fa fa-check-circle"></i> {{ __('clinicCore::lang.imgrep_finalise') }}</button>
            @endif
            @if($finalised && $canVerify)
                <button type="button" class="btn btn-warning" id="imr-amend"><i class="fa fa-edit"></i> {{ __('clinicCore::lang.imgrep_amend') }}</button>
            @endif
            <a href="{{ route('clinic.imaging.worklist') }}" class="btn btn-link">{{ __('clinicCore::lang.imgrep_back_to_worklist') }}</a>
        </div>
    </form>
</section>
@endsection

@section('javascript')
<script>
(function () {
    var token   = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    var baseUrl = '{{ url('/clinic/imaging/requests/'.$imagingRequest->id.'/report') }}';
    var form    = document.getElementById('imr-form');

    // Critical block toggle.
    var critChk = document.getElementById('imr-has-critical');
    var critBlk = document.getElementById('imr-crit-block');
    if (critChk) critChk.addEventListener('change', function () { critBlk.style.display = critChk.checked ? '' : 'none'; });

    // Structured-findings add/remove.
    var sfList = document.getElementById('imr-sf-list');
    function bindDel(row) { row.querySelector('.imr-sf-del').addEventListener('click', function () { row.remove(); }); }
    Array.prototype.forEach.call(sfList.querySelectorAll('.imr-sf-row'), bindDel);
    document.getElementById('imr-sf-add') && document.getElementById('imr-sf-add').addEventListener('click', function () {
        var row = sfList.querySelector('.imr-sf-row').cloneNode(true);
        row.querySelectorAll('input[type=text]').forEach(function (i) { i.value = ''; });
        var c = row.querySelector('.imr-sf-abn'); if (c) c.checked = false;
        sfList.appendChild(row); bindDel(row);
    });

    function collect() {
        var data = {
            radiologist_id:      (form.querySelector('[name=radiologist_id]') || {}).value || null,
            narrative_findings:  (form.querySelector('[name=narrative_findings]') || {}).value || null,
            impression:          (form.querySelector('[name=impression]') || {}).value || null,
            recommendation:      (form.querySelector('[name=recommendation]') || {}).value || null,
            comparison:          (form.querySelector('[name=comparison]') || {}).value || null,
            has_critical:        critChk && critChk.checked ? 1 : 0,
            critical_description: (form.querySelector('[name=critical_description]') || {}).value || null,
            critical_communicated_to: (form.querySelector('[name=critical_communicated_to]') || {}).value || null,
            structured_findings: []
        };
        Array.prototype.forEach.call(sfList.querySelectorAll('.imr-sf-row'), function (row) {
            var region = row.querySelector('.imr-sf-region').value.trim();
            var finding = row.querySelector('.imr-sf-finding').value.trim();
            if (region || finding) {
                data.structured_findings.push({ region: region, finding: finding, abnormality: row.querySelector('.imr-sf-abn').checked ? 1 : 0 });
            }
        });
        var ar = form.querySelector('[name=amendment_reason]');
        if (ar) data.amendment_reason = ar.value || null;
        return data;
    }

    function post(url, payload, btn) {
        if (btn) btn.disabled = true;
        fetch(url, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify(payload)
        }).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, body: j }; }); })
          .then(function (res) {
              if (btn) btn.disabled = false;
              if (res.ok && res.body.success) { window.location.reload(); }
              else { alert((res.body && res.body.msg) || 'Save failed'); }
          }).catch(function () { if (btn) btn.disabled = false; alert('Save failed'); });
    }

    var saveBtn = document.getElementById('imr-save');
    if (saveBtn) saveBtn.addEventListener('click', function () { var p = collect(); p.report_status = 'draft'; post(baseUrl, p, saveBtn); });
    var prelimBtn = document.getElementById('imr-save-prelim');
    if (prelimBtn) prelimBtn.addEventListener('click', function () { var p = collect(); p.report_status = 'preliminary'; post(baseUrl, p, prelimBtn); });
    var finBtn = document.getElementById('imr-finalise');
    if (finBtn) finBtn.addEventListener('click', function () { post(baseUrl + '/finalise', collect(), finBtn); });
    var amendBtn = document.getElementById('imr-amend');
    if (amendBtn) amendBtn.addEventListener('click', function () { post(baseUrl + '/amend', collect(), amendBtn); });
})();
</script>
@endsection
