@extends('secretary.layouts.app')
@section('title', 'الاستقبال')
@section('page-title', 'لوحة الاستقبال')

@section('content')

{{-- إحصائيات --}}
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#f0fdf4;color:#16a34a"><i class="bi bi-hourglass-split"></i></div>
            <div><div class="stat-val text-success">{{ $stats['waiting'] }}</div><div class="stat-lbl">ينتظرون</div></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#fefce8;color:#ca8a04"><i class="bi bi-person-check"></i></div>
            <div><div class="stat-val text-warning">{{ $stats['in_progress'] }}</div><div class="stat-lbl">عند الطبيب</div></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb"><i class="bi bi-calendar-check"></i></div>
            <div><div class="stat-val text-primary">{{ $stats['appointments'] }}</div><div class="stat-lbl">مواعيد اليوم</div></div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#f5f3ff;color:#7c3aed"><i class="bi bi-check2-circle"></i></div>
            <div><div class="stat-val" style="color:#7c3aed">{{ $stats['completed'] }}</div><div class="stat-lbl">أنهوا اليوم</div></div>
        </div>
    </div>
</div>

<div class="row g-3">

    {{-- بحث مريض --}}
    <div class="col-lg-5">
        <div class="card h-100">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="bi bi-search me-2"></i>بحث سريع عن مريض</span>
                <a href="{{ route('secretary.patients.create') }}" class="btn btn-sm btn-success">
                    <i class="bi bi-plus-lg"></i> مريض جديد
                </a>
            </div>
            <div class="card-body">
                <div class="position-relative mb-3" id="search-wrap">
                    <div class="input-group input-group-lg">
                        <span class="input-group-text bg-white border-end-0">
                            <i class="bi bi-search text-muted"></i>
                        </span>
                        <input type="text" id="patient-search"
                               class="form-control border-start-0 fs-6"
                               placeholder="ابحث بالاسم أو الهاتف..."
                               autocomplete="off">
                        <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    </div>
                    <div id="patient-results" style="position:absolute;top:100%;right:0;left:0;background:#fff;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.12);z-index:9999;max-height:300px;overflow-y:auto;display:none"></div>
                </div>

                <div id="selected-patient" style="display:none">
                    <div class="border rounded-3 p-3 bg-light position-relative">
                        <button type="button" class="btn-close position-absolute" style="top:10px;left:10px" onclick="clearSelected()"></button>
                        <div class="d-flex align-items-center gap-3 mb-3">
                            <div style="width:46px;height:46px;background:#0f766e;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:1.3rem;flex-shrink:0">
                                <i class="bi bi-person-fill"></i>
                            </div>
                            <div>
                                <div class="fw-bold" id="sp-name">—</div>
                                <div class="text-muted small" id="sp-phone">—</div>
                            </div>
                        </div>
                        <div class="row g-2 mb-3 small">
                            <div class="col-4"><span class="text-muted d-block">الجنس</span><span id="sp-gender" class="fw-semibold">—</span></div>
                            <div class="col-4"><span class="text-muted d-block">العمر</span><span id="sp-age" class="fw-semibold">—</span></div>
                            <div class="col-4"><span class="text-muted d-block">الدم</span><span id="sp-blood" class="fw-semibold text-danger">—</span></div>
                            <div class="col-12" id="sp-chronic-wrap" style="display:none">
                                <span class="text-muted d-block">أمراض مزمنة</span>
                                <span id="sp-chronic" class="fw-semibold text-warning small"></span>
                            </div>
                            <div class="col-12" id="sp-allergy-wrap" style="display:none">
                                <span class="text-muted d-block">الحساسية</span>
                                <span id="sp-allergy" class="fw-semibold text-danger small"></span>
                            </div>
                        </div>
                        <form method="POST" id="add-queue-form" action="">
                            @csrf
                            <div class="mb-2">
                                <input type="text" name="reason" class="form-control form-control-sm" placeholder="سبب الزيارة (اختياري)">
                            </div>
                            <button type="submit" class="btn btn-success w-100 fw-semibold">
                                <i class="bi bi-person-plus-fill me-1"></i> إضافة إلى الطابور
                            </button>
                        </form>
                        <a href="#" id="sp-profile-link" class="btn btn-outline-secondary btn-sm w-100 mt-2">
                            <i class="bi bi-eye me-1"></i> الملف الكامل
                        </a>
                    </div>
                </div>

                <div id="search-empty" class="text-center py-4 text-muted" style="display:none">
                    <i class="bi bi-person-x fs-2 d-block mb-2"></i>
                    لم يُعثر على مريض مطابق
                    <div class="mt-2">
                        <a href="{{ route('secretary.patients.create') }}" class="btn btn-sm btn-success">
                            <i class="bi bi-plus me-1"></i> تسجيل مريض جديد
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- الطابور --}}
    <div class="col-lg-7">
        <div class="card h-100">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="bi bi-list-ol me-2 text-primary"></i>طابور اليوم</span>
                <a href="{{ route('secretary.queue.index') }}" class="btn btn-sm btn-outline-primary">إدارة الطابور</a>
            </div>
            <div class="card-body p-0" style="overflow-y:auto;max-height:400px">
                @forelse($queue as $item)
                <div class="q-item">
                    <div class="queue-num {{ $item->status }}">{{ $item->queue_number }}</div>
                    <div class="flex-grow-1">
                        <div class="fw-semibold">{{ $item->patient->user->name }}</div>
                        <div class="text-muted small">
                            <i class="bi bi-clock me-1"></i>{{ $item->arrived_at?->format('H:i') }}
                            @if($item->estimated_wait_minutes)
                                · ~{{ $item->estimated_wait_minutes }} د
                            @endif
                        </div>
                    </div>
                    <div>
                        @if($item->status==='waiting')     <span class="badge b-waiting">ينتظر</span>
                        @elseif($item->status==='in_progress') <span class="badge b-in_progress">عند الطبيب</span>
                        @elseif($item->status==='called')  <span class="badge b-called">استُدعي</span>
                        @endif
                    </div>
                    <form method="POST" action="{{ route('secretary.queue.remove', $item->id) }}">
                        @csrf @method('DELETE')
                        <button class="btn btn-sm btn-outline-danger" onclick="return confirm('إزالة من الطابور؟')">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    </form>
                </div>
                @empty
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-inbox fs-2 d-block mb-2"></i>الطابور فارغ
                </div>
                @endforelse
            </div>
        </div>
    </div>

    {{-- مواعيد اليوم --}}
    @if($todayAppointments->count())
    <div class="col-12">
        <div class="card">
            <div class="card-header"><i class="bi bi-calendar-event me-2 text-primary"></i>مواعيد اليوم المحجوزة</div>
            <div class="table-responsive">
                <table class="table tbl mb-0">
                    <thead><tr><th>الوقت</th><th>المريض</th><th>سبب الزيارة</th><th>الحالة</th><th>إجراء</th></tr></thead>
                    <tbody>
                        @foreach($todayAppointments as $appt)
                        <tr>
                            <td><span class="fw-bold text-primary">{{ $appt->appointment_time }}</span></td>
                            <td>
                                <div class="fw-semibold">{{ $appt->patient->user->name }}</div>
                                <small class="text-muted">{{ $appt->patient->user->phone }}</small>
                            </td>
                            <td><small class="text-muted">{{ $appt->reason ?? '—' }}</small></td>
                            <td>
                                @if($appt->status==='confirmed')
                                    <span class="badge b-waiting">مؤكد</span>
                                @else
                                    <span class="badge bg-light text-dark">بانتظار</span>
                                @endif
                            </td>
                            <td>
                                <form method="POST" action="{{ route('secretary.queue.add', $appt->patient_id) }}">
                                    @csrf
                                    <input type="hidden" name="appointment_id" value="{{ $appt->id }}">
                                    <input type="hidden" name="reason" value="{{ $appt->reason }}">
                                    <button class="btn btn-sm btn-success"><i class="bi bi-person-plus me-1"></i>أضف للطابور</button>
                                </form>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    @endif
</div>
@endsection

@push('scripts')
<script>
const searchInput = document.getElementById('patient-search');
const resultsBox  = document.getElementById('patient-results');
const selectedBox = document.getElementById('selected-patient');
const emptyBox    = document.getElementById('search-empty');
let timer = null;

// تحديث تلقائي كل دقيقة
setInterval(() => location.reload(), 60000);

searchInput.addEventListener('input', function () {
    clearTimeout(timer);
    const q = this.value.trim();
    if (q.length < 2) { hideResults(); return; }
    timer = setTimeout(() => doSearch(q), 350);
});

async function doSearch(q) {
    resultsBox.innerHTML = '<div class="p-3 text-center text-muted small"><div class="spinner-border spinner-border-sm me-2"></div>جارٍ البحث...</div>';
    resultsBox.style.display = 'block';
    selectedBox.style.display = 'none';
    emptyBox.style.display    = 'none';

    const res  = await fetch(`{{ route('secretary.patients.search') }}?q=${encodeURIComponent(q)}`);
    const data = await res.json();

    if (!data.length) { hideResults(); emptyBox.style.display = 'block'; return; }

    resultsBox.innerHTML = data.map(p => `
        <div class="pr-item" onclick='selectPatient(${JSON.stringify(p)})' style="padding:.65rem 1rem;cursor:pointer;border-bottom:1px solid #f3f4f6;transition:background .1s">
            <div class="d-flex align-items-center gap-2">
                <div style="width:32px;height:32px;background:#0f766e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0;font-size:.9rem">
                    <i class="bi bi-person"></i>
                </div>
                <div class="flex-grow-1">
                    <div class="fw-semibold small">${p.name}</div>
                    <div class="text-muted" style="font-size:.75rem">${p.phone ?? ''}
                        ${p.blood_type ? `<span class="badge bg-danger ms-1" style="font-size:.6rem">${p.blood_type}</span>` : ''}
                        ${p.age ? `· ${p.age}` : ''}
                    </div>
                </div>
                ${p.chronic ? `<span class="badge bg-warning text-dark" style="font-size:.65rem">مزمن</span>` : ''}
            </div>
        </div>
    `).join('');
    resultsBox.style.display = 'block';
}

function selectPatient(p) {
    hideResults();
    searchInput.value = p.name;
    document.getElementById('sp-name').textContent   = p.name;
    document.getElementById('sp-phone').textContent  = p.phone ?? '—';
    document.getElementById('sp-gender').textContent = p.gender ?? '—';
    document.getElementById('sp-age').textContent    = p.age ?? '—';
    document.getElementById('sp-blood').textContent  = p.blood_type ?? '—';

    const cw = document.getElementById('sp-chronic-wrap');
    if (p.chronic) { cw.style.display='block'; document.getElementById('sp-chronic').textContent = p.chronic; }
    else cw.style.display='none';

    const aw = document.getElementById('sp-allergy-wrap');
    if (p.allergies) { aw.style.display='block'; document.getElementById('sp-allergy').textContent = p.allergies; }
    else aw.style.display='none';

    document.getElementById('add-queue-form').action = `{{ url('secretary/queue/add') }}/${p.id}`;
    document.getElementById('sp-profile-link').href  = `{{ url('secretary/patients') }}/${p.id}`;

    selectedBox.style.display = 'block';
    emptyBox.style.display    = 'none';
}

function hideResults()  { resultsBox.style.display='none'; resultsBox.innerHTML=''; }
function clearSearch()  { searchInput.value=''; hideResults(); clearSelected(); }
function clearSelected(){ selectedBox.style.display='none'; emptyBox.style.display='none'; }

document.addEventListener('click', e => {
    if (!document.getElementById('search-wrap').contains(e.target)) hideResults();
});
</script>
@endpush
