@extends('doctor.layouts.app')
@section('title','أدويتي وتحاليلي')
@section('page-title','الأدوية والتحاليل المفضلة')

@section('content')

<div class="row g-3">

    {{-- ══ الأدوية ══ --}}
    <div class="col-lg-7">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="bi bi-capsule me-2 text-primary"></i>الأدوية المفضلة</span>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addMedModal">
                    <i class="bi bi-plus-lg me-1"></i>إضافة دواء
                </button>
            </div>
            <div class="card-body">
                @if($medicines->isEmpty())
                    <div class="text-center py-4 text-muted">
                        <i class="bi bi-capsule fs-2 d-block mb-2"></i>
                        لم تضف أي أدوية بعد
                    </div>
                @else
                    @foreach($medicines as $category => $group)
                    <div class="mb-3">
                        <div class="text-muted small fw-bold mb-2 text-uppercase" style="letter-spacing:.05em">
                            {{ $category ?: 'عام' }}
                            <span class="badge bg-light text-dark ms-1">{{ $group->count() }}</span>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            @foreach($group as $med)
                            <div class="position-relative">
                                <div class="d-flex align-items-center gap-1 border rounded-3 px-3 py-2"
                                     style="background:#f8faff;border-color:#dbeafe!important;cursor:default">
                                    <div>
                                        <div class="fw-semibold small">{{ $med->name }}</div>
                                        @if($med->default_dose || $med->default_times)
                                        <div class="text-muted" style="font-size:.7rem">
                                            {{ $med->default_dose }} {{ $med->default_times ? '· '.$med->default_times : '' }}
                                        </div>
                                        @endif
                                    </div>
                                    @if($med->usage_count > 0)
                                    <span class="badge bg-primary bg-opacity-10 text-primary ms-1" style="font-size:.65rem">
                                        {{ $med->usage_count }}×
                                    </span>
                                    @endif
                                    <div class="d-flex gap-1 ms-1">
                                        <button class="btn btn-xs p-0" style="color:#94a3b8;font-size:.8rem"
                                                onclick="editMed({{ $med->toJson() }})" title="تعديل">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <form method="POST" action="{{ route('doctor.medicines.destroy',$med->id) }}" class="d-inline">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn btn-xs p-0" style="color:#f87171;font-size:.8rem"
                                                    onclick="return confirm('حذف الدواء؟')" title="حذف">
                                                <i class="bi bi-x-lg"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    </div>
                    @endforeach
                @endif
            </div>
        </div>
    </div>

    {{-- ══ التحاليل ══ --}}
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="bi bi-droplet-half me-2 text-danger"></i>التحاليل المفضلة</span>
                <button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#addTestModal">
                    <i class="bi bi-plus-lg me-1"></i>إضافة تحليل
                </button>
            </div>
            <div class="card-body">
                @if($tests->isEmpty())
                    <div class="text-center py-4 text-muted">
                        <i class="bi bi-droplet fs-2 d-block mb-2"></i>
                        لم تضف أي تحاليل بعد
                    </div>
                @else
                    @foreach($tests as $category => $group)
                    <div class="mb-3">
                        <div class="text-muted small fw-bold mb-2 text-uppercase" style="letter-spacing:.05em">
                            {{ $category ?: 'عام' }}
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            @foreach($group as $test)
                            <div class="d-flex align-items-center gap-1 border rounded-3 px-3 py-2"
                                 style="background:#fff5f5;border-color:#fecaca!important">
                                <div>
                                    <div class="fw-semibold small">{{ $test->name }}</div>
                                    @if($test->name_en)
                                        <div class="text-muted" style="font-size:.7rem">{{ $test->name_en }}</div>
                                    @endif
                                </div>
                                @if($test->usage_count > 0)
                                <span class="badge bg-danger bg-opacity-10 text-danger ms-1" style="font-size:.65rem">
                                    {{ $test->usage_count }}×
                                </span>
                                @endif
                                <div class="d-flex gap-1 ms-1">
                                    <button class="btn btn-xs p-0" style="color:#94a3b8;font-size:.8rem"
                                            onclick="editTest({{ $test->toJson() }})" title="تعديل">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <form method="POST" action="{{ route('doctor.tests.destroy',$test->id) }}" class="d-inline">
                                        @csrf @method('DELETE')
                                        <button type="submit" class="btn btn-xs p-0" style="color:#f87171;font-size:.8rem"
                                                onclick="return confirm('حذف التحليل؟')">
                                            <i class="bi bi-x-lg"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    </div>
                    @endforeach
                @endif
            </div>
        </div>
    </div>
</div>

{{-- ══ Modal إضافة دواء ══ --}}
<div class="modal fade" id="addMedModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="medModalTitle"><i class="bi bi-capsule me-2"></i>إضافة دواء</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="medForm" action="{{ route('doctor.medicines.store') }}">
                @csrf
                <input type="hidden" name="_method" id="medMethod" value="POST">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-7">
                            <label class="form-label">اسم الدواء (عربي) <span class="text-danger">*</span></label>
                            <input type="text" name="name" id="med_name" class="form-control" required placeholder="مثال: أموكسيسيلين">
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">الاسم العلمي</label>
                            <input type="text" name="name_en" id="med_name_en" class="form-control" placeholder="Amoxicillin">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">التصنيف</label>
                            <input type="text" name="category" id="med_category" class="form-control" placeholder="مضاد حيوي، مسكن...">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">الشكل الدوائي</label>
                            <select name="form" id="med_form" class="form-select">
                                <option value="">—</option>
                                <option value="حبوب">حبوب</option>
                                <option value="كبسول">كبسول</option>
                                <option value="شراب">شراب</option>
                                <option value="حقن">حقن</option>
                                <option value="كريم">كريم</option>
                                <option value="قطرة">قطرة</option>
                                <option value="تحميلة">تحميلة</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">الجرعة الافتراضية</label>
                            <input type="text" name="default_dose" id="med_dose" class="form-control" placeholder="500mg">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">مرات الاستخدام</label>
                            <input type="text" name="default_times" id="med_times" class="form-control" placeholder="3 مرات يومياً">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">المدة الافتراضية</label>
                            <input type="text" name="default_duration" id="med_duration" class="form-control" placeholder="7 أيام">
                        </div>
                        <div class="col-12">
                            <label class="form-label">تعليمات الاستخدام</label>
                            <textarea name="default_instructions" id="med_instructions" rows="2"
                                      class="form-control" placeholder="يؤخذ بعد الطعام، مع الماء..."></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-save me-1"></i>حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- ══ Modal إضافة تحليل ══ --}}
<div class="modal fade" id="addTestModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="testModalTitle"><i class="bi bi-droplet-half me-2"></i>إضافة تحليل</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="testForm" action="{{ route('doctor.tests.store') }}">
                @csrf
                <input type="hidden" name="_method" id="testMethod" value="POST">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-7">
                            <label class="form-label">اسم التحليل <span class="text-danger">*</span></label>
                            <input type="text" name="name" id="test_name" class="form-control" required placeholder="صورة دم كاملة CBC">
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">الاسم الإنجليزي</label>
                            <input type="text" name="name_en" id="test_name_en" class="form-control" placeholder="CBC">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label fw-semibold">نوع الإجراء <span class="text-danger">*</span></label>
                            <div class="d-flex flex-wrap gap-2" id="ref-type-group">
                                @foreach([
                                    'lab'        => ['🔬','تحليل مختبري','#991b1b','#fff5f5'],
                                    'xray'       => ['🩻','أشعة سينية','#1e40af','#eff6ff'],
                                    'ultrasound' => ['🫀','سونار','#065f46','#ecfdf5'],
                                    'mri'        => ['🧲','رنين مغناطيسي','#4c1d95','#f5f3ff'],
                                    'ct'         => ['🖥','CT Scan','#92400e','#fffbeb'],
                                    'ecg'        => ['💓','تخطيط قلب','#9d174d','#fdf2f8'],
                                    'other'      => ['📋','إجراء آخر','#374151','#f9fafb'],
                                ] as $val => [$icon, $lbl, $clr, $bg])
                                <label style="cursor:pointer">
                                    <input type="radio" name="referral_type" id="test_ref_{{ $val }}"
                                           value="{{ $val }}" {{ $val==='lab' ? 'checked' : '' }}
                                           style="display:none"
                                           onchange="selectRefType('{{ $val }}','{{ $clr }}','{{ $bg }}')">
                                    <span class="ref-type-btn" id="rtb-{{ $val }}"
                                          style="display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:20px;font-size:.78rem;font-weight:600;border:1.5px solid {{ $clr }};background:{{ $val==='lab' ? $bg : '#fff' }};color:{{ $clr }};transition:all .15s"
                                          onclick="selectRefType('{{ $val }}','{{ $clr }}','{{ $bg }}')">
                                        {{ $icon }} {{ $lbl }}
                                    </span>
                                </label>
                                @endforeach
                            </div>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">التصنيف</label>
                            <input type="text" name="category" id="test_category" class="form-control" placeholder="تحاليل دم، بول، أشعة...">
                        </div>
                        <div class="col-12">
                            <label class="form-label">تعليمات التحضير</label>
                            <textarea name="instructions" id="test_instructions" rows="2"
                                      class="form-control" placeholder="صيام 8 ساعات قبل التحليل..."></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-danger"><i class="bi bi-save me-1"></i>حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
function editMed(m) {
    document.getElementById('medModalTitle').innerHTML = '<i class="bi bi-pencil me-2"></i>تعديل: '+m.name;
    document.getElementById('medForm').action = '/doctor/medicines/medicine/'+m.id;
    document.getElementById('medMethod').value = 'PUT';
    document.getElementById('med_name').value         = m.name || '';
    document.getElementById('med_name_en').value      = m.name_en || '';
    document.getElementById('med_category').value     = m.category || '';
    document.getElementById('med_form').value         = m.form || '';
    document.getElementById('med_dose').value         = m.default_dose || '';
    document.getElementById('med_times').value        = m.default_times || '';
    document.getElementById('med_duration').value     = m.default_duration || '';
    document.getElementById('med_instructions').value = m.default_instructions || '';
    new bootstrap.Modal(document.getElementById('addMedModal')).show();
}

function selectRefType(val, clr, bg) {
    document.querySelectorAll('.ref-type-btn').forEach(b => {
        b.style.background = '#fff';
    });
    const btn = document.getElementById('rtb-' + val);
    if (btn) btn.style.background = bg;
    const radio = document.getElementById('test_ref_' + val);
    if (radio) radio.checked = true;
}

function editTest(t) {
    document.getElementById('testModalTitle').innerHTML = '<i class="bi bi-pencil me-2"></i>تعديل: '+t.name;
    document.getElementById('testForm').action = '/doctor/medicines/test/'+t.id;
    document.getElementById('testMethod').value = 'PUT';
    document.getElementById('test_name').value         = t.name || '';
    document.getElementById('test_name_en').value      = t.name_en || '';
    document.getElementById('test_category').value     = t.category || '';
    document.getElementById('test_instructions').value = t.instructions || '';
    new bootstrap.Modal(document.getElementById('addTestModal')).show();
}
</script>
@endpush
