@extends('layouts.app')
@section('title', __('Photos & X-rays').' — '.$patient->full_name)

@section('content')
<h1 class="h4 fw-bold mb-2">📷 {{ $patient->full_name }}</h1>
@include('patients._tabs')

@can('files.manage')
<div class="mb-card p-4 mb-3">
    <h2 class="h6 fw-semibold mb-3">+ {{ __('Upload file') }}</h2>
    <form method="POST" action="{{ route('tenant.patients.files.store', $patient) }}"
          enctype="multipart/form-data" class="row g-2 align-items-end">
        @csrf
        <div class="col-md-3">
            <label class="form-label small">{{ __('File') }}</label>
            <input type="file" name="file" class="form-control form-control-sm @error('file') is-invalid @enderror"
                   accept=".jpg,.jpeg,.png,.webp,.pdf,.dcm" required>
            @error('file')<div class="invalid-feedback">{{ $message }}</div>@enderror
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label small">{{ __('Type') }}</label>
            <select name="type" class="form-select form-select-sm">
                <option value="photo_before">{{ __('Before photo') }}</option>
                <option value="photo_after">{{ __('After photo') }}</option>
                <option value="xray">{{ __('X-ray') }}</option>
                <option value="other">{{ __('Other') }}</option>
            </select>
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label small">{{ __('Teeth (FDI)') }}</label>
            <input name="teeth_csv" id="teethCsv" class="form-control form-control-sm" dir="ltr" placeholder="16, 26">
        </div>
        <div class="col-md-3">
            <label class="form-label small">{{ __('Caption') }}</label>
            <input name="caption" class="form-control form-control-sm">
        </div>
        <div class="col-md-2">
            <button class="btn mb-btn-primary btn-sm w-100">{{ __('Upload') }}</button>
        </div>
        @if($plans->isNotEmpty())
        <div class="col-md-4">
            <label class="form-label small">{{ __('Link to treatment plan') }}</label>
            <select name="treatment_plan_id" class="form-select form-select-sm">
                <option value="">—</option>
                @foreach($plans as $tp)<option value="{{ $tp->id }}">{{ $tp->title }}</option>@endforeach
            </select>
        </div>
        @endif
        <div id="teethHidden"></div>
    </form>
</div>
@endcan

{{-- ===== Before / After ===== --}}
<h2 class="h6 fw-semibold">{{ __('Before / After') }}</h2>
@php($pairs = $afters->filter(fn ($a) => $a->paired_with_id))
@if($pairs->isEmpty() && $befores->isEmpty() && $afters->isEmpty())
    <p class="mb-muted small">{{ __('No photos yet.') }}</p>
@endif

<div class="row g-3 mb-3">
    @foreach($pairs as $after)
        @php($before = $befores->firstWhere('id', $after->paired_with_id))
        @continue(! $before)
        <div class="col-md-6 col-xl-4">
            <div class="mb-card p-3">
                <div class="ba-compare" data-ba>
                    <img src="{{ route('tenant.files.serve', $before) }}" alt="before" loading="lazy">
                    <img class="after-img" src="{{ route('tenant.files.serve', $after) }}" alt="after" loading="lazy">
                    <span class="ba-tag" style="left:.5rem">{{ __('Before') }}</span>
                    <span class="ba-tag" style="right:.5rem">{{ __('After') }}</span>
                    <div class="ba-handle"></div>
                </div>
                <input type="range" class="ba-range form-range mt-2" min="0" max="100" value="50">
                <div class="d-flex justify-content-between align-items-center">
                    <span class="mb-muted small">
                        {{ $after->caption ?? $before->caption }}
                        @if($after->teeth ?? $before->teeth) · 🦷 {{ implode('، ', $after->teeth ?? $before->teeth) }}@endif
                    </span>
                    @can('files.manage')
                    <form method="POST" action="{{ route('tenant.patients.files.destroy', [$patient, $after]) }}"
                          onsubmit="return confirm('{{ __('Delete this file?') }}')">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm mb-btn-ghost">✕</button>
                    </form>
                    @endcan
                </div>
            </div>
        </div>
    @endforeach
</div>

{{-- Unpaired photos --}}
@php($unpairedAfters = $afters->whereNull('paired_with_id'))
@if($befores->isNotEmpty() || $unpairedAfters->isNotEmpty())
<div class="row g-3 mb-4">
    @foreach($befores->whereNotIn('id', $pairs->pluck('paired_with_id')) as $file)
        <div class="col-6 col-md-3">
            <div class="mb-card p-2">
                <img class="xray-thumb" src="{{ route('tenant.files.serve', [$file, 'thumb']) }}" alt="" loading="lazy"
                     onclick="openViewer('{{ route('tenant.files.serve', $file) }}')">
                <div class="small mt-1">
                    <span class="badge text-bg-secondary">{{ __('Before photo') }}</span>
                    @if($file->teeth) 🦷 {{ implode('، ', $file->teeth) }} @endif
                </div>
                @can('files.manage')
                @if($unpairedAfters->isNotEmpty())
                <form method="POST" class="mt-1 d-flex gap-1" id="pairForm{{ $file->id }}"
                      action="" onsubmit="return submitPair(this, {{ $file->id }})">
                    @csrf
                    <select class="form-select form-select-sm pair-after">
                        <option value="">{{ __('Pair with after…') }}</option>
                        @foreach($unpairedAfters as $a)
                            <option value="{{ $a->id }}">{{ $a->caption ?? $a->original_name }}</option>
                        @endforeach
                    </select>
                    <button class="btn btn-sm mb-btn-primary">⇄</button>
                </form>
                @endif
                @endcan
            </div>
        </div>
    @endforeach
    @foreach($unpairedAfters as $file)
        <div class="col-6 col-md-3">
            <div class="mb-card p-2">
                <img class="xray-thumb" src="{{ route('tenant.files.serve', [$file, 'thumb']) }}" alt="" loading="lazy"
                     onclick="openViewer('{{ route('tenant.files.serve', $file) }}')">
                <div class="small mt-1"><span class="badge text-bg-info">{{ __('After photo') }}</span></div>
            </div>
        </div>
    @endforeach
</div>
@endif

{{-- ===== X-rays ===== --}}
<h2 class="h6 fw-semibold">🩻 {{ __('X-rays') }}</h2>
@if($xrays->isEmpty())<p class="mb-muted small">{{ __('No X-rays yet.') }}</p>@endif
<div class="row g-3 mb-4">
    @foreach($xrays as $file)
        <div class="col-6 col-md-3">
            <div class="mb-card p-2">
                @if($file->isImage())
                    <img class="xray-thumb" src="{{ route('tenant.files.serve', [$file, 'thumb']) }}" alt="" loading="lazy"
                         onclick="openViewer('{{ route('tenant.files.serve', $file) }}')">
                @else
                    <a class="btn mb-btn-ghost w-100" target="_blank" href="{{ route('tenant.files.serve', $file) }}">📄 {{ $file->original_name }}</a>
                @endif
                <div class="d-flex justify-content-between align-items-center small mt-1">
                    <span class="mb-muted">
                        {{ $file->caption ?? $file->created_at->format('d M Y') }}
                        @if($file->teeth) · 🦷 {{ implode('، ', $file->teeth) }} @endif
                    </span>
                    @can('files.manage')
                    <form method="POST" action="{{ route('tenant.patients.files.destroy', [$patient, $file]) }}"
                          onsubmit="return confirm('{{ __('Delete this file?') }}')">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm mb-btn-ghost py-0">✕</button>
                    </form>
                    @endcan
                </div>
            </div>
        </div>
    @endforeach
</div>

{{-- ===== Viewer modal (zoom & pan) ===== --}}
<div class="modal fade" id="viewer" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content mb-card">
            <div class="modal-header" style="border-color:var(--mb-line)">
                <input type="range" class="form-range w-50" id="zoomRange" min="1" max="5" step="0.1" value="1">
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-2">
                <div class="xray-stage" id="stage"><img id="viewerImg" src="" alt=""></div>
            </div>
        </div>
    </div>
</div>

@push('page-scripts')
<script>
// Teeth CSV → teeth[] inputs
document.querySelector('form[enctype]')?.addEventListener('submit', () => {
    const holder = document.getElementById('teethHidden');
    holder.innerHTML = '';
    (document.getElementById('teethCsv')?.value || '').split(/[,، ]+/).filter(Boolean).forEach(t => {
        const i = document.createElement('input');
        i.type = 'hidden'; i.name = 'teeth[]'; i.value = t.trim();
        holder.appendChild(i);
    });
});

// Before/after comparison sliders
document.querySelectorAll('[data-ba]').forEach(box => {
    const range = box.parentElement.querySelector('.ba-range');
    range.addEventListener('input', () => box.style.setProperty('--split', range.value + '%'));
});

// Pair form (route is /files/{before}/pair/{after})
const PAIR_BASE = @json(route('tenant.patients.files', $patient));
function submitPair(form, beforeId) {
    const afterId = form.querySelector('.pair-after').value;
    if (!afterId) return false;
    form.action = `${PAIR_BASE}/${beforeId}/pair/${afterId}`;
    return true;
}

// X-ray viewer: zoom slider + drag pan + wheel zoom
const viewerEl = document.getElementById('viewer');
const img = document.getElementById('viewerImg');
const zoom = document.getElementById('zoomRange');
let pan = { x: 0, y: 0 }, drag = null;

function openViewer(src) {
    img.src = src;
    zoom.value = 1; pan = { x: 0, y: 0 };
    apply();
    bootstrap.Modal.getOrCreateInstance(viewerEl).show();
}
function apply() {
    img.style.setProperty('--zoom', zoom.value);
    img.style.translate = `${pan.x}px ${pan.y}px`;
}
zoom.addEventListener('input', apply);
img.addEventListener('pointerdown', e => { drag = { x: e.clientX - pan.x, y: e.clientY - pan.y }; img.setPointerCapture(e.pointerId); });
img.addEventListener('pointermove', e => { if (drag) { pan = { x: e.clientX - drag.x, y: e.clientY - drag.y }; apply(); } });
img.addEventListener('pointerup', () => drag = null);
document.getElementById('stage').addEventListener('wheel', e => {
    e.preventDefault();
    zoom.value = Math.min(5, Math.max(1, parseFloat(zoom.value) - Math.sign(e.deltaY) * 0.25));
    apply();
}, { passive: false });
</script>
@endpush
@endsection
