@extends('doctor.layouts.app')
@section('title', $patient->user->name)
@section('page-title','الأرشيف الطبي')

@push('styles')
<style>
#newRecordModal .modal-content { height:92vh; max-height:92vh; }
#newRecordModal .modal-body     { overflow-y:auto !important; flex:1 1 auto; min-height:0; }
#prescTable thead.sticky-top th { position:sticky;top:0;z-index:2; }

.med-auto-btn {
    background:#eff6ff; border:1.5px solid #bfdbfe; color:#1e40af;
    border-radius:20px; padding:4px 14px; font-size:.8rem; font-weight:600;
    cursor:pointer; transition:all .15s; white-space:nowrap;
    display:inline-flex; align-items:center; gap:5px;
}
.med-auto-btn:hover { background:#1d4ed8; color:#fff; border-color:#1d4ed8; }

.test-quick-btn {
    border-radius:20px; padding:4px 12px; font-size:.78rem; font-weight:600;
    cursor:pointer; transition:all .15s; white-space:nowrap; border-width:1.5px; border-style:solid;
}

.ref-tab { border-radius:10px; padding:8px 16px; border:1.5px solid; cursor:pointer; font-size:.82rem; font-weight:600; transition:all .15s; text-align:center; }
.ref-tab.active { color:#fff !important; }
.ref-tab:hover  { opacity:.85; }

.test-tag {
    display:inline-flex; align-items:center; gap:6px;
    border-radius:20px; padding:5px 14px; font-size:.82rem; font-weight:600;
    border-width:1.5px; border-style:solid;
}
</style>
@endpush

@section('content')

{{-- زر ثابت --}}
<button class="btn btn-primary fw-semibold"
        style="position:fixed;bottom:24px;left:24px;z-index:998;border-radius:50px;padding:.7rem 1.5rem;box-shadow:0 4px 16px rgba(29,78,216,.4)"
        data-bs-toggle="modal" data-bs-target="#newRecordModal">
    <i class="bi bi-plus-lg me-1"></i>تشخيص جديد
</button>

<div class="row g-3">
    {{-- بطاقة المريض --}}
    <div class="col-lg-3">
        <div class="card mb-2">
            <div class="card-body text-center pt-3 pb-3">
                <div style="width:52px;height:52px;background:{{ $patient->gender==='female'?'#ec4899':'#1d4ed8' }};border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:#fff;margin:0 auto .8rem">
                    <i class="bi bi-person-fill"></i>
                </div>
                <h6 class="fw-bold mb-0">{{ $patient->user->name }}</h6>
                <div class="text-muted small">{{ $patient->user->phone }}</div>
                @if($patient->blood_type)<span class="badge bg-danger mt-1">{{ $patient->blood_type }}</span>@endif
                @if($patient->date_of_birth)<div class="text-muted small mt-1">{{ $patient->date_of_birth->age }} سنة</div>@endif
            </div>
        </div>
        @if($patient->allergies)
        <div class="card border-danger mb-2">
            <div class="card-header text-danger py-2 small"><i class="bi bi-shield-exclamation me-1"></i>حساسية</div>
            <div class="card-body py-2 small fw-semibold text-danger">{{ $patient->allergies }}</div>
        </div>
        @endif
        @if($patient->chronic_diseases)
        <div class="card border-warning mb-2">
            <div class="card-header text-warning py-2 small"><i class="bi bi-exclamation-triangle me-1"></i>مزمنة</div>
            <div class="card-body py-2 small">{{ $patient->chronic_diseases }}</div>
        </div>
        @endif
    </div>

    {{-- السجلات --}}
    <div class="col-lg-9">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="bi bi-file-medical me-2"></i>السجلات الطبية</span>
                <span class="badge bg-secondary">{{ $records->total() }} زيارة</span>
            </div>
            @forelse($records as $record)
            <div class="border-bottom p-3">
                <div class="d-flex align-items-start justify-content-between">
                    <div class="flex-grow-1">
                        <div class="d-flex align-items-center gap-2 mb-1">
                            <span class="fw-bold text-primary">{{ $record->visit_date->format('Y/m/d') }}</span>
                            <span class="text-muted small">{{ $record->visit_date->locale('ar')->diffForHumans() }}</span>
                        </div>
                        @if($record->chief_complaint)
                        <div class="small text-muted mb-1"><i class="bi bi-chat-text me-1"></i>{{ $record->chief_complaint }}</div>
                        @endif
                        <div class="fw-semibold mb-1"><i class="bi bi-clipboard2-pulse me-1 text-primary"></i>{{ $record->diagnosis }}</div>
                        @if($record->prescriptions && count($record->prescriptions))
                        <div class="small text-muted"><i class="bi bi-capsule me-1"></i>{{ collect($record->prescriptions)->pluck('medicine')->filter()->join(' · ') }}</div>
                        @endif
                        @if($record->lab_tests && count($record->lab_tests))
                        <div class="small text-muted mt-1"><i class="bi bi-droplet-half me-1 text-danger"></i>{{ collect($record->lab_tests)->pluck('test')->filter()->join(' · ') }}</div>
                        @endif
                        @if($record->next_visit_date)
                        <div class="small mt-1 {{ $record->next_visit_date->isPast() ? 'text-danger' : 'text-success' }}">
                            <i class="bi bi-calendar-check me-1"></i>متابعة: {{ $record->next_visit_date->format('Y/m/d') }}
                        </div>
                        @endif
                    </div>
                    <div class="d-flex gap-1 ms-2 flex-shrink-0">
                        <a href="{{ route('doctor.archive.record',$record->id) }}" class="btn btn-sm btn-outline-primary" title="عرض"><i class="bi bi-eye"></i></a>
                        <a href="{{ route('doctor.archive.print',$record->id) }}" target="_blank" class="btn btn-sm btn-outline-success" title="وصفة"><i class="bi bi-printer"></i></a>
                        {{-- زر تحويل جديد لهذه الزيارة --}}
                        <button class="btn btn-sm btn-outline-danger" title="تحويل/تحليل"
                                onclick="openReferral({{ $record->id }})">
                            <i class="bi bi-arrow-right-circle"></i>
                        </button>
                    </div>
                </div>
            </div>
            @empty
            <div class="text-center py-5 text-muted">
                <i class="bi bi-file-earmark-x fs-2 d-block mb-2"></i>لا توجد زيارات سابقة
            </div>
            @endforelse
            @if($records->hasPages())
            <div class="card-footer bg-transparent">{{ $records->links('pagination::bootstrap-5') }}</div>
            @endif
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════
     MODAL التشخيص الجديد
═══════════════════════════════════════════ --}}
<div class="modal fade" id="newRecordModal" tabindex="-1">
    <div class="modal-dialog modal-xl" style="max-width:960px;margin:1rem auto">
        <div class="modal-content" style="height:92vh;display:flex;flex-direction:column">
            <div class="modal-header flex-shrink-0" style="background:#eff6ff;border-bottom:2px solid #bfdbfe">
                <div>
                    <h5 class="modal-title fw-bold text-primary mb-0"><i class="bi bi-file-medical me-2"></i>تشخيص جديد</h5>
                    <div class="text-muted small">{{ $patient->user->name }}</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body" style="overflow-y:auto;flex:1 1 auto;min-height:0;padding:1.25rem">
                <form method="POST" action="{{ route('doctor.archive.store') }}" id="diagForm">
                    @csrf
                    <input type="hidden" name="patient_id" value="{{ $patient->id }}">
                    <input type="hidden" name="print_after" id="printAfterInput" value="0">

                    {{-- المؤشرات الحيوية --}}
                    <div class="rounded-3 p-3 mb-3" style="background:#f0f9ff;border:1px solid #bae6fd">
                        <div class="fw-semibold small text-primary mb-2"><i class="bi bi-activity me-1"></i>المؤشرات الحيوية</div>
                        <div class="row g-2">
                            <div class="col-6 col-md-2"><label class="form-label small mb-1 fw-semibold">التاريخ</label><input type="date" name="visit_date" class="form-control form-control-sm" value="{{ date('Y-m-d') }}" required></div>
                            <div class="col-6 col-md-2"><label class="form-label small mb-1">الضغط</label><input type="text" name="blood_pressure" class="form-control form-control-sm" placeholder="120/80"></div>
                            <div class="col-6 col-md-2"><label class="form-label small mb-1">الحرارة °م</label><input type="number" name="temperature" class="form-control form-control-sm" step="0.1" placeholder="36.5"></div>
                            <div class="col-6 col-md-2"><label class="form-label small mb-1">النبض</label><input type="number" name="pulse" class="form-control form-control-sm" placeholder="80"></div>
                            <div class="col-6 col-md-2"><label class="form-label small mb-1">O₂ %</label><input type="number" name="oxygen_saturation" class="form-control form-control-sm" placeholder="98"></div>
                            <div class="col-6 col-md-2"><label class="form-label small mb-1">الوزن كغ</label><input type="number" name="weight" class="form-control form-control-sm" step="0.1" placeholder="70"></div>
                        </div>
                    </div>

                    {{-- الشكوى والتشخيص --}}
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">الشكوى الرئيسية</label>
                            <textarea name="chief_complaint" rows="2" class="form-control" placeholder="ما الذي يشكو منه المريض؟"></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">التشخيص <span class="text-danger">*</span></label>
                            <textarea name="diagnosis" rows="2" class="form-control" required placeholder="التشخيص الطبي..."></textarea>
                        </div>
                    </div>

                    {{-- ══ الوصفة الطبية ══ --}}
                    <div class="mb-3">
                        <div class="d-flex align-items-center justify-content-between mb-2">
                            <span class="fw-bold"><i class="bi bi-capsule me-1 text-primary"></i>الوصفة الطبية</span>
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="addPrescRow()">
                                <i class="bi bi-plus-lg me-1"></i>دواء يدوي
                            </button>
                        </div>

                        {{-- أزرار الأدوية المقترحة تلقائياً (3+ استخدامات) --}}
                        <div id="auto-suggest-area" style="display:none" class="rounded-3 p-2 mb-2" style="background:#fefce8;border:1px solid #fde68a">
                            <div class="text-muted" style="font-size:.7rem;margin-bottom:4px">
                                <i class="bi bi-star-fill text-warning me-1"></i>
                                أدوية مستخدمة كثيراً — انقر للإضافة الفورية:
                            </div>
                            <div id="auto-suggest-btns" class="d-flex flex-wrap gap-2"></div>
                        </div>

                        {{-- باقي الأدوية المفضلة --}}
                        <div class="rounded-3 p-2 mb-2" style="background:#eff6ff;border:1px solid #bfdbfe;min-height:42px">
                            <div class="text-muted" style="font-size:.7rem;margin-bottom:4px">
                                <i class="bi bi-lightning-charge me-1 text-primary"></i>
                                أدويتك المفضلة:
                            </div>
                            <div id="quick-meds-btns" class="d-flex flex-wrap gap-2">
                                <span class="text-muted small"><span class="spinner-border spinner-border-sm me-1"></span>جارٍ التحميل...</span>
                            </div>
                        </div>

                        <div class="table-responsive" style="max-height:190px;overflow-y:auto">
                            <table class="table table-sm table-bordered mb-0" id="prescTable">
                                <thead class="table-primary sticky-top">
                                    <tr>
                                        <th style="width:26%">الدواء</th>
                                        <th style="width:15%">الجرعة</th>
                                        <th style="width:20%">طريقة الاستخدام</th>
                                        <th style="width:15%">المدة</th>
                                        <th style="width:19%">تعليمات</th>
                                        <th style="width:5%"></th>
                                    </tr>
                                </thead>
                                <tbody id="presc-rows"></tbody>
                            </table>
                        </div>
                    </div>

                    {{-- ══ التحاليل ══ --}}
                    <div class="mb-3">
                        <div class="d-flex align-items-center justify-content-between mb-2">
                            <span class="fw-bold"><i class="bi bi-droplet-half me-1 text-danger"></i>طلبات التحليل والإجراءات</span>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="addTestManual()">
                                <i class="bi bi-plus-lg me-1"></i>إضافة يدوي
                            </button>
                        </div>
                        <div class="rounded-3 p-2 mb-2" style="background:#fff5f5;border:1px solid #fecaca;min-height:42px">
                            <div class="text-muted" style="font-size:.7rem;margin-bottom:4px">
                                <i class="bi bi-lightning-charge me-1 text-danger"></i>
                                تحاليلك المفضلة:
                            </div>
                            <div id="quick-tests-btns" class="d-flex flex-wrap gap-2">
                                <span class="text-muted small"><span class="spinner-border spinner-border-sm me-1"></span>جارٍ التحميل...</span>
                            </div>
                        </div>
                        <div id="tests-rows" class="d-flex flex-wrap gap-2"></div>
                    </div>

                    {{-- التعليمات والمتابعة --}}
                    <div class="row g-3">
                        <div class="col-md-5"><label class="form-label">تعليمات للمريض</label><textarea name="instructions" rows="2" class="form-control" placeholder="إرشادات..."></textarea></div>
                        <div class="col-md-4"><label class="form-label">ملاحظات المتابعة</label><textarea name="follow_up_notes" rows="2" class="form-control"></textarea></div>
                        <div class="col-md-3"><label class="form-label">موعد المتابعة</label><input type="date" name="next_visit_date" class="form-control" min="{{ date('Y-m-d', strtotime('+1 day')) }}"></div>
                    </div>
                </form>
            </div>

            <div class="modal-footer flex-shrink-0" style="background:#f8faff;border-top:2px solid #bfdbfe">
                <div class="d-flex align-items-center justify-content-between w-100 flex-wrap gap-2">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg me-1"></i>إلغاء
                    </button>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-primary fw-semibold px-4" onclick="submitDiag(0)">
                            <i class="bi bi-save me-1"></i>حفظ فقط
                        </button>
                        <button type="button" class="btn btn-success fw-semibold px-4" onclick="submitDiag(1)">
                            <i class="bi bi-printer me-1"></i>حفظ وطباعة الوصفة
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════
     MODAL التحويل الطبي
═══════════════════════════════════════════ --}}
<div class="modal fade" id="referralModal" tabindex="-1">
    <div class="modal-dialog modal-lg" style="max-width:720px;margin:2rem auto">
        <div class="modal-content">
            <div class="modal-header" style="background:#fff5f5;border-bottom:2px solid #fecaca">
                <div>
                    <h5 class="modal-title fw-bold" style="color:#991b1b">
                        <i class="bi bi-arrow-right-circle me-2"></i>تحويل طبي
                    </h5>
                    <div class="text-muted small">{{ $patient->user->name }}</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ route('doctor.referral.store') }}" id="refForm">
                @csrf
                <input type="hidden" name="patient_id" value="{{ $patient->id }}">
                <input type="hidden" name="medical_record_id" id="refRecordId" value="">
                <input type="hidden" name="print_now" id="refPrintNow" value="0">

                <div class="modal-body">

                    {{-- اختيار نوع التحويل --}}
                    <div class="mb-3">
                        <label class="form-label fw-semibold">نوع الإجراء <span class="text-danger">*</span></label>
                        <div class="d-flex flex-wrap gap-2" id="ref-type-tabs">
                            @foreach(\App\Models\MedicalReferral::typeConfig() as $val => $cfg)
                            <div class="ref-tab" id="rt-{{ $val }}"
                                 style="color:{{ $cfg['color'] }};border-color:{{ $cfg['color'] }};background:{{ $val==='lab'?$cfg['bg']:'#fff' }}"
                                 onclick="selectReferralType('{{ $val }}')">
                                {{ $cfg['icon'] }} {{ $cfg['label'] }}
                                <input type="radio" name="referral_type" value="{{ $val }}"
                                       {{ $val==='lab'?'checked':'' }} style="display:none"
                                       id="rtype-{{ $val }}">
                            </div>
                            @endforeach
                        </div>
                    </div>

                    {{-- عنوان التحويل --}}
                    <div class="mb-3">
                        <label class="form-label fw-semibold">عنوان التحويل</label>
                        <input type="text" name="title" id="refTitle" class="form-control"
                               value="طلب تحاليل مختبرية" placeholder="مثال: طلب تحاليل دم">
                    </div>

                    {{-- أزرار التحاليل السريعة حسب النوع --}}
                    <div class="mb-2">
                        <div class="text-muted small mb-2">
                            <i class="bi bi-lightning-charge me-1"></i>
                            <span id="refQuickLabel">تحاليلك المفضلة — انقر لإضافة:</span>
                        </div>
                        <div id="ref-quick-btns" class="d-flex flex-wrap gap-2 p-2 rounded-3" style="background:#fff5f5;border:1px solid #fecaca;min-height:42px">
                            <span class="text-muted small">جارٍ التحميل...</span>
                        </div>
                    </div>

                    {{-- العناصر المضافة --}}
                    <div class="mb-3">
                        <label class="form-label fw-semibold">العناصر المطلوبة</label>
                        <div id="ref-items-list" class="mb-2"></div>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="addRefItemManual()">
                            <i class="bi bi-plus-lg me-1"></i>إضافة يدوي
                        </button>
                    </div>

                    {{-- ملاحظات سريرية --}}
                    <div class="row g-2">
                        <div class="col-md-8">
                            <label class="form-label">ملاحظات سريرية للمختبر</label>
                            <textarea name="clinical_notes" rows="2" class="form-control"
                                      placeholder="معلومات مفيدة للمختبر أو مركز التصوير..."></textarea>
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="is_urgent"
                                       id="refUrgent" value="1">
                                <label class="form-check-label fw-semibold text-danger" for="refUrgent">
                                    🔴 عاجل
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer" style="background:#fafafa">
                    <div class="d-flex justify-content-between w-100 flex-wrap gap-2">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-danger fw-semibold px-4" onclick="submitRef(0)">
                                <i class="bi bi-save me-1"></i>حفظ فقط
                            </button>
                            <button type="button" class="btn btn-success fw-semibold px-4" onclick="submitRef(1)">
                                <i class="bi bi-printer me-1"></i>حفظ وطباعة التحويل
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
// ══ بيانات محملة مسبقاً ══
let allMedicines   = [];
let allTests       = [];
let autoSuggest    = [];
let prescCount     = 0;
let selectedTests  = [];
let refItems       = [];
let currentRefType = 'lab';

const typeConfig = @json(\App\Models\MedicalReferral::typeConfig());
const titleMap   = {
    lab:'طلب تحاليل مختبرية', xray:'طلب أشعة سينية',
    ultrasound:'طلب سونار', mri:'طلب رنين مغناطيسي',
    ct:'طلب CT Scan', ecg:'طلب تخطيط قلب', other:'تحويل طبي'
};

// ══ تحميل عند فتح modal التشخيص ══
document.getElementById('newRecordModal').addEventListener('show.bs.modal', () => {
    if (!allMedicines.length) loadMedicines();
    if (!allTests.length)     loadTests();
    if (prescCount === 0)     addPrescRow();
});

async function loadMedicines() {
    try {
        const r = await fetch('{{ route("doctor.medicines.api") }}');
        allMedicines = await r.json();
    } catch(e) { allMedicines = []; }

    try {
        const r = await fetch('{{ route("doctor.medicines.auto-suggest") }}');
        autoSuggest = await r.json();
    } catch(e) { autoSuggest = []; }

    renderMedBtns();
}

async function loadTests() {
    try {
        const r = await fetch('{{ route("doctor.tests.api") }}');
        allTests = await r.json();
    } catch(e) { allTests = []; }
    renderTestBtns();
    renderRefQuickBtns();
}

// ══ رسم الأزرار ══

function renderMedBtns() {
    // الاقتراحات التلقائية (3+ استخدامات)
    const autoArea = document.getElementById('auto-suggest-area');
    const autoBtns = document.getElementById('auto-suggest-btns');
    if (autoSuggest.length) {
        autoArea.style.display = 'block';
        autoBtns.innerHTML = autoSuggest.map(m => `
            <button type="button" class="med-auto-btn" onclick='addMedFromBtn(${esc(m)})'>
                ⭐ ${m.name}
                ${m.default_dose ? `<span style="opacity:.6;font-size:.7rem">${m.default_dose}</span>` : ''}
                <span style="opacity:.45;font-size:.65rem">${m.usage_count}×</span>
            </button>`).join('');
    }

    // كل الأدوية المفضلة
    const c = document.getElementById('quick-meds-btns');
    if (!allMedicines.length) {
        c.innerHTML = '<a href="{{ route("doctor.medicines.index") }}" class="text-muted small">أضف أدوية مفضلة</a>';
        return;
    }
    c.innerHTML = allMedicines.map(m => `
        <button type="button" class="med-auto-btn" style="background:#eff6ff" onclick='addMedFromBtn(${esc(m)})'>
            💊 ${m.name}
            ${m.default_dose ? `<small style="opacity:.6">${m.default_dose}</small>` : ''}
        </button>`).join('');
}

function renderTestBtns() {
    const c = document.getElementById('quick-tests-btns');
    if (!allTests.length) {
        c.innerHTML = '<a href="{{ route("doctor.medicines.index") }}" class="text-muted small">أضف تحاليل مفضلة</a>';
        return;
    }
    c.innerHTML = allTests.map(t => {
        const cfg = typeConfig[t.referral_type] || typeConfig.lab;
        return `<button type="button" class="test-quick-btn"
                    style="background:${cfg.bg};border-color:${cfg.border};color:${cfg.color}"
                    onclick='addTestFromBtn(${esc(t)})'>
                    ${cfg.icon} ${t.name}
                    ${t.usage_count >= 3 ? `<span style="opacity:.5;font-size:.65rem">${t.usage_count}×</span>` : ''}
                </button>`;
    }).join('');
}

function renderRefQuickBtns() {
    const c = document.getElementById('ref-quick-btns');
    const filtered = allTests.filter(t => t.referral_type === currentRefType);
    const cfg = typeConfig[currentRefType];
    if (!filtered.length) {
        c.innerHTML = `<a href="{{ route("doctor.medicines.index") }}" class="text-muted small">أضف ${cfg.label} مفضلة</a>`;
        c.style.background = cfg.bg;
        c.style.borderColor = cfg.border;
        return;
    }
    c.style.background  = cfg.bg;
    c.style.borderColor = cfg.border;
    c.innerHTML = filtered.map(t =>
        `<button type="button" class="test-quick-btn"
                 style="background:#fff;border-color:${cfg.border};color:${cfg.color}"
                 onclick='addRefItemFromBtn(${esc(t)})'>
             ${cfg.icon} ${t.name}
             ${t.usage_count >= 3 ? `<span style="opacity:.5;font-size:.65rem">${t.usage_count}×</span>` : ''}
         </button>`
    ).join('');
}

// ══ إضافة دواء للوصفة ══
function addMedFromBtn(m) { addPrescRow(m); }

function addPrescRow(med = {}) {
    const idx = prescCount++;
    document.getElementById('presc-rows').insertAdjacentHTML('beforeend', `
    <tr id="pr-${idx}">
        <td><input type="hidden" name="prescriptions[${idx}][medicine_id]" value="${med.id||''}">
            <input type="text" name="prescriptions[${idx}][medicine]" class="form-control form-control-sm fw-semibold"
                   value="${h(med.name||'')}" placeholder="اسم الدواء" required></td>
        <td><input type="text" name="prescriptions[${idx}][dose]"     class="form-control form-control-sm" value="${h(med.default_dose||'')}" placeholder="500mg"></td>
        <td><input type="text" name="prescriptions[${idx}][times]"    class="form-control form-control-sm" value="${h(med.default_times||'')}" placeholder="3× يومياً"></td>
        <td><input type="text" name="prescriptions[${idx}][duration]" class="form-control form-control-sm" value="${h(med.default_duration||'')}" placeholder="7 أيام"></td>
        <td><input type="text" name="prescriptions[${idx}][instructions]" class="form-control form-control-sm" value="${h(med.default_instructions||'')}" placeholder="بعد الطعام"></td>
        <td><button type="button" class="btn btn-sm btn-outline-danger p-1 lh-1"
                    onclick="document.getElementById('pr-${idx}').remove()"><i class="bi bi-x"></i></button></td>
    </tr>`);
}

// ══ إضافة تحليل للوصفة ══
function addTestFromBtn(t) {
    if (t.id && selectedTests.find(x => x.id === t.id)) return;
    selectedTests.push(t);
    renderTestTags(); rebuildTestInputs();
}
function addTestManual() {
    const n = prompt('اسم التحليل:');
    if (!n?.trim()) return;
    selectedTests.push({id:null, name:n.trim(), instructions:'', referral_type:'lab'});
    renderTestTags(); rebuildTestInputs();
}
function removeTest(i) { selectedTests.splice(i,1); renderTestTags(); rebuildTestInputs(); }
function renderTestTags() {
    document.getElementById('tests-rows').innerHTML = selectedTests.map((t,i) => {
        const cfg = typeConfig[t.referral_type] || typeConfig.lab;
        return `<div class="test-tag" style="background:${cfg.bg};border-color:${cfg.border};color:${cfg.color}">
            ${cfg.icon} ${h(t.name)}
            <button type="button" onclick="removeTest(${i})"
                    style="background:none;border:none;color:inherit;cursor:pointer;padding:0;font-size:.9rem;opacity:.6">✕</button>
        </div>`;
    }).join('');
}
function rebuildTestInputs() {
    document.querySelectorAll('.lab-inp').forEach(e=>e.remove());
    const f = document.getElementById('diagForm');
    selectedTests.forEach((t,i) => {
        [['test',t.name],['test_id',t.id||''],['instructions',t.instructions||''],['referral_type',t.referral_type||'lab']]
        .forEach(([field,val]) => {
            const inp = Object.assign(document.createElement('input'),{type:'hidden',className:'lab-inp',name:`lab_tests[${i}][${field}]`,value:val});
            f.appendChild(inp);
        });
    });
}

// ══ إرسال التشخيص ══
function submitDiag(print) {
    document.getElementById('printAfterInput').value = print;
    document.getElementById('diagForm').submit();
}

// ══ فتح modal التحويل ══
function openReferral(recordId) {
    document.getElementById('refRecordId').value = recordId;
    refItems = [];
    renderRefItems();
    selectReferralType('lab');
    if (!allTests.length) loadTests();
    const m = new bootstrap.Modal(document.getElementById('referralModal'));
    m.show();
}

// ══ اختيار نوع التحويل ══
function selectReferralType(type) {
    currentRefType = type;
    const cfg = typeConfig[type];

    // تحديث الأزرار
    Object.keys(typeConfig).forEach(t => {
        const el = document.getElementById('rt-'+t);
        if (el) el.style.background = t===type ? typeConfig[t].bg : '#fff';
    });
    document.getElementById('rtype-'+type).checked = true;

    // تحديث العنوان
    document.getElementById('refTitle').value = titleMap[type] || 'تحويل طبي';

    // تحديث الأزرار السريعة
    renderRefQuickBtns();
}

// ══ إضافة عنصر للتحويل ══
function addRefItemFromBtn(t) {
    if (t.id && refItems.find(x => x.id === t.id)) return;
    refItems.push({...t, urgent: false});
    renderRefItems(); rebuildRefInputs();
}
function addRefItemManual() {
    const n = prompt('اسم الإجراء المطلوب:');
    if (!n?.trim()) return;
    const inst = prompt('تعليمات (اختياري):') || '';
    refItems.push({id:null, name:n.trim(), instructions:inst, urgent:false});
    renderRefItems(); rebuildRefInputs();
}
function removeRefItem(i) { refItems.splice(i,1); renderRefItems(); rebuildRefInputs(); }
function renderRefItems() {
    const cfg = typeConfig[currentRefType] || typeConfig.lab;
    document.getElementById('ref-items-list').innerHTML = refItems.length ? `
        <div class="table-responsive">
            <table class="table table-sm table-bordered mb-0">
                <thead class="table-light"><tr><th>#</th><th>الإجراء المطلوب</th><th>تعليمات</th><th>عاجل</th><th></th></tr></thead>
                <tbody>
                ${refItems.map((item,i) => `
                <tr>
                    <td><span style="width:20px;height:20px;background:${cfg.color};color:#fff;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:.65rem;font-weight:700">${i+1}</span></td>
                    <td class="fw-semibold">${cfg.icon} ${h(item.name)}</td>
                    <td><small class="text-muted">${h(item.instructions||'—')}</small></td>
                    <td>${item.urgent ? '<span class="badge bg-danger">عاجل</span>' : '—'}</td>
                    <td><button type="button" class="btn btn-xs btn-outline-danger p-0 px-1" onclick="removeRefItem(${i})"><i class="bi bi-x"></i></button></td>
                </tr>`).join('')}
                </tbody>
            </table>
        </div>` : '<div class="text-muted small py-2">لم تُضف أي إجراءات بعد</div>';
}
function rebuildRefInputs() {
    document.querySelectorAll('.ref-inp').forEach(e=>e.remove());
    const f = document.getElementById('refForm');
    refItems.forEach((item,i) => {
        [['name',item.name],['instructions',item.instructions||''],['urgent',item.urgent?1:0],['test_id',item.id||'']]
        .forEach(([field,val]) => {
            const inp = Object.assign(document.createElement('input'),{type:'hidden',className:'ref-inp',name:`items[${i}][${field}]`,value:val});
            f.appendChild(inp);
        });
    });
}
function submitRef(print) {
    if (!refItems.length) { alert('أضف إجراءاً واحداً على الأقل'); return; }
    document.getElementById('refPrintNow').value = print;
    document.getElementById('refForm').submit();
}

// ══ مساعدات ══
function h(s) { return String(s).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function esc(o) { return JSON.stringify(o).replace(/"/g,'&quot;'); }
</script>
@endpush
