@extends('patient.layouts.app')
@section('title','ملفي الشخصي')
@section('tb-sub','إعدادات الحساب')

@push('styles')
<style>
.profile-hero{
    background:linear-gradient(135deg,var(--c1),var(--c2));
    padding:2rem 1rem 3.5rem;
    text-align:center;color:#fff;
}
.p-av{
    width:80px;height:80px;border-radius:50%;
    background:rgba(255,255,255,.25);
    border:3px solid rgba(255,255,255,.4);
    display:flex;align-items:center;justify-content:center;
    font-size:1.8rem;font-weight:700;color:#fff;
    margin:0 auto .7rem;
}
.p-name{font-size:1.2rem;font-weight:800;margin-bottom:.2rem}
.p-phone{font-size:.8rem;opacity:.8}
.p-badges{display:flex;justify-content:center;gap:.5rem;margin-top:.6rem;flex-wrap:wrap}
.p-badge{background:rgba(255,255,255,.2);border-radius:20px;padding:3px 12px;font-size:.72rem;font-weight:700}

.profile-card{
    margin:-2.5rem 1rem 0;
    background:#fff;border-radius:var(--r);
    box-shadow:0 8px 30px rgba(0,0,0,.12);
    overflow:hidden;margin-bottom:.8rem;
}
.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);text-align:center;border-bottom:1px solid #f1f5f9}
.stat-cell{padding:.9rem .5rem}
.stat-cell .sv{font-size:1.3rem;font-weight:800;color:var(--c1)}
.stat-cell .sl{font-size:.62rem;color:var(--t3)}

/* Section card */
.sec-card{
    margin:0 1rem .7rem;
    background:#fff;border-radius:var(--r);
    box-shadow:var(--sh);overflow:hidden;
}
.sec-card-head{
    display:flex;align-items:center;gap:.6rem;
    padding:.9rem 1rem;font-weight:700;font-size:.88rem;
    border-bottom:1px solid #f8faff;
    cursor:pointer;
}
.sec-card-head .hi{
    width:34px;height:34px;border-radius:10px;
    display:flex;align-items:center;justify-content:center;
    font-size:.95rem;flex-shrink:0;
}
.sec-card-body{padding:.9rem 1rem}

/* Fields */
.field-row{margin-bottom:.9rem}
.field-row:last-child{margin-bottom:0}
.field-label{font-size:.72rem;font-weight:700;color:var(--t2);margin-bottom:.35rem;display:block}
.field-inp{
    width:100%;padding:.65rem 1rem;
    border:1.5px solid #e5e7eb;border-radius:var(--rs);
    font-size:.88rem;color:var(--t1);background:#fff;
    outline:none;transition:border-color .15s;
    font-family:inherit;
}
.field-inp:focus{border-color:var(--c1);box-shadow:0 0 0 3px rgba(109,40,217,.1)}
.field-inp.danger{border-color:#ef4444}
.field-sel{
    width:100%;padding:.65rem 1rem;
    border:1.5px solid #e5e7eb;border-radius:var(--rs);
    font-size:.88rem;color:var(--t1);background:#fff;
    outline:none;appearance:none;cursor:pointer;
}
.field-sel:focus{border-color:var(--c1)}

/* Medical info */
.med-item{
    display:flex;align-items:flex-start;gap:.7rem;
    padding:.7rem 0;border-bottom:1px solid #f8faff;
}
.med-item:last-child{border-bottom:none}
.med-item .mi-icon{font-size:1.1rem;flex-shrink:0;margin-top:1px}
.med-item .mi-lbl{font-size:.7rem;color:var(--t3);font-weight:600;margin-bottom:2px}
.med-item .mi-val{font-size:.85rem;font-weight:600;color:var(--t1)}
.med-item .mi-empty{font-size:.82rem;color:var(--t3);font-style:italic}

/* Password strength */
.pwd-bar{height:4px;border-radius:2px;background:#e5e7eb;overflow:hidden;margin-top:5px}
.pwd-fill{height:100%;border-radius:2px;transition:width .3s,background .3s;width:0%}

/* Quick links */
.qlink{
    display:flex;align-items:center;gap:.9rem;
    padding:.85rem 1rem;border-bottom:.5px solid #f8faff;
    text-decoration:none;color:var(--t1);
    transition:background .15s;
}
.qlink:last-child{border-bottom:none}
.qlink:active{background:var(--cL)}
.qlink .ql-icon{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:.95rem;flex-shrink:0}
.qlink .ql-text{flex:1}
.qlink .ql-title{font-size:.88rem;font-weight:600}
.qlink .ql-sub{font-size:.72rem;color:var(--t3)}
.qlink i.arrow{color:var(--t3);font-size:.85rem}

/* Edit panels */
.edit-panel{display:none;padding:1rem;border-top:1px solid #f1f5f9}
.edit-panel.open{display:block}

.save-btn{
    background:var(--c1);color:#fff;border:none;border-radius:var(--rs);
    padding:.72rem;width:100%;font-weight:700;font-size:.9rem;
    cursor:pointer;margin-top:.8rem;display:flex;align-items:center;justify-content:center;gap:.4rem;
}
.save-btn:active{opacity:.85}
</style>
@endpush

@section('content')

@php
$p = $patient;
$u = $patient->user;
$apptCount   = \App\Models\Appointment::where('patient_id',$p->id)->count();
$recordCount = \App\Models\MedicalRecord::where('patient_id',$p->id)->count();
$docCount    = \App\Models\Appointment::where('patient_id',$p->id)->distinct('doctor_id')->count('doctor_id');
@endphp

{{-- ══ Hero ══ --}}
<div class="profile-hero">
    <div class="p-av">{{ strtoupper(mb_substr($u->name,0,1)) }}</div>
    <div class="p-name">{{ $u->name }}</div>
    <div class="p-phone">{{ $u->phone }}</div>
    <div class="p-badges">
        @if($p->blood_type)<span class="p-badge">🩸 {{ $p->blood_type }}</span>@endif
        @if($p->gender)<span class="p-badge">{{ $p->gender==='male'?'👨 ذكر':'👩 أنثى' }}</span>@endif
        @if($p->date_of_birth)<span class="p-badge">🎂 {{ $p->date_of_birth->age }} سنة</span>@endif
    </div>
</div>

{{-- ══ Stats ══ --}}
<div class="profile-card">
    <div class="stat-grid">
        <div class="stat-cell"><div class="sv">{{ $apptCount }}</div><div class="sl">موعد</div></div>
        <div class="stat-cell"><div class="sv">{{ $recordCount }}</div><div class="sl">زيارة</div></div>
        <div class="stat-cell"><div class="sv">{{ $docCount }}</div><div class="sl">طبيب</div></div>
    </div>
</div>

{{-- ══ Quick Links ══ --}}
<div class="sec-card">
    <a href="{{ route('patient.appointments.index') }}" class="qlink">
        <span class="ql-icon" style="background:#dbeafe;color:#1e40af"><i class="bi bi-calendar2-check-fill"></i></span>
        <div class="ql-text"><div class="ql-title">مواعيدي</div><div class="ql-sub">{{ $apptCount }} موعد مسجل</div></div>
        <i class="bi bi-chevron-left arrow"></i>
    </a>
    <a href="{{ route('patient.records.index') }}" class="qlink">
        <span class="ql-icon" style="background:#d1fae5;color:#065f46"><i class="bi bi-clipboard2-pulse-fill"></i></span>
        <div class="ql-text"><div class="ql-title">سجلاتي الطبية</div><div class="ql-sub">{{ $recordCount }} زيارة طبية</div></div>
        <i class="bi bi-chevron-left arrow"></i>
    </a>
    <a href="{{ route('patient.notifications.index') }}" class="qlink">
        <span class="ql-icon" style="background:#fef9c3;color:#854d0e"><i class="bi bi-bell-fill"></i></span>
        <div class="ql-text"><div class="ql-title">الإشعارات</div><div class="ql-sub">عرض كل الإشعارات</div></div>
        <i class="bi bi-chevron-left arrow"></i>
    </a>
</div>

{{-- ══ المعلومات الطبية ══ --}}
<div class="sec-card">
    <div class="sec-card-head" onclick="toggleSection('medical')">
        <span class="hi" style="background:#fee2e2;color:#991b1b"><i class="bi bi-heart-pulse-fill"></i></span>
        <span style="flex:1">المعلومات الطبية</span>
        <i class="bi bi-chevron-down" id="ico-medical" style="color:var(--t3);transition:transform .2s"></i>
    </div>
    <div class="edit-panel" id="sec-medical">
        @if($p->chronic_diseases || $p->allergies || $p->current_medications)
        <div>
            @if($p->chronic_diseases)
            <div class="med-item">
                <span class="mi-icon">⚠️</span>
                <div><div class="mi-lbl">أمراض مزمنة</div><div class="mi-val">{{ $p->chronic_diseases }}</div></div>
            </div>
            @endif
            @if($p->allergies)
            <div class="med-item">
                <span class="mi-icon">🚨</span>
                <div><div class="mi-lbl">الحساسية</div><div class="mi-val" style="color:#dc2626">{{ $p->allergies }}</div></div>
            </div>
            @endif
            @if($p->current_medications)
            <div class="med-item">
                <span class="mi-icon">💊</span>
                <div><div class="mi-lbl">الأدوية الحالية</div><div class="mi-val">{{ $p->current_medications }}</div></div>
            </div>
            @endif
        </div>
        @else
        <div style="text-align:center;padding:1rem 0;color:var(--t3)">
            <i class="bi bi-clipboard-x" style="font-size:1.5rem;display:block;margin-bottom:.4rem"></i>
            <div style="font-size:.82rem">لا توجد معلومات طبية مضافة</div>
        </div>
        @endif
        <button class="btn-sm" style="margin-top:.6rem" onclick="toggleSection('edit-info')">
            <i class="bi bi-pencil me-1"></i>تعديل المعلومات
        </button>
    </div>
</div>

{{-- ══ تعديل البيانات الشخصية ══ --}}
<div class="sec-card">
    <div class="sec-card-head" onclick="toggleSection('edit-info')">
        <span class="hi" style="background:var(--cM);color:var(--c1)"><i class="bi bi-person-fill"></i></span>
        <span style="flex:1">تعديل البيانات الشخصية</span>
        <i class="bi bi-chevron-down" id="ico-edit-info" style="color:var(--t3);transition:transform .2s"></i>
    </div>
    <div class="edit-panel" id="sec-edit-info">
        <form method="POST" action="{{ route('patient.profile.update') }}">
            @csrf @method('PUT')

            <div class="field-row">
                <label class="field-label">الاسم الكامل</label>
                <input type="text" name="name" value="{{ old('name',$u->name) }}" class="field-inp @error('name') danger @enderror" required>
                @error('name')<div style="font-size:.7rem;color:#ef4444;margin-top:3px">{{ $message }}</div>@enderror
            </div>
            <div class="field-row">
                <label class="field-label">رقم الهاتف</label>
                <input type="text" name="phone" value="{{ old('phone',$u->phone) }}" class="field-inp @error('phone') danger @enderror" required>
                @error('phone')<div style="font-size:.7rem;color:#ef4444;margin-top:3px">{{ $message }}</div>@enderror
            </div>
            <div class="field-row">
                <label class="field-label">البريد الإلكتروني (اختياري)</label>
                <input type="email" name="email" value="{{ old('email',$u->email) }}" class="field-inp @error('email') danger @enderror">
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.6rem">
                <div class="field-row">
                    <label class="field-label">الجنس</label>
                    <select name="gender" class="field-sel">
                        <option value="">—</option>
                        <option value="male" {{ $p->gender==='male'?'selected':'' }}>ذكر</option>
                        <option value="female" {{ $p->gender==='female'?'selected':'' }}>أنثى</option>
                    </select>
                </div>
                <div class="field-row">
                    <label class="field-label">فصيلة الدم</label>
                    <select name="blood_type" class="field-sel">
                        <option value="">—</option>
                        @foreach(['A+','A-','B+','B-','AB+','AB-','O+','O-'] as $bt)
                        <option value="{{ $bt }}" {{ $p->blood_type===$bt?'selected':'' }}>{{ $bt }}</option>
                        @endforeach
                    </select>
                </div>
            </div>

            <div class="field-row">
                <label class="field-label">تاريخ الميلاد</label>
                <input type="date" name="date_of_birth" value="{{ old('date_of_birth',$p->date_of_birth?->format('Y-m-d')) }}" class="field-inp">
            </div>

            <div class="field-row">
                <label class="field-label">أمراض مزمنة</label>
                <textarea name="chronic_diseases" rows="2" class="field-inp" style="resize:none" placeholder="السكري، ضغط الدم...">{{ old('chronic_diseases',$p->chronic_diseases) }}</textarea>
            </div>
            <div class="field-row">
                <label class="field-label" style="color:#dc2626">⚠ الحساسية</label>
                <textarea name="allergies" rows="2" class="field-inp" style="resize:none;border-color:#fecaca" placeholder="البنسلين، الأسبرين...">{{ old('allergies',$p->allergies) }}</textarea>
            </div>
            <div class="field-row">
                <label class="field-label">الأدوية الحالية</label>
                <textarea name="current_medications" rows="2" class="field-inp" style="resize:none">{{ old('current_medications',$p->current_medications) }}</textarea>
            </div>

            <button type="submit" class="save-btn">
                <i class="bi bi-check-circle-fill"></i>حفظ التغييرات
            </button>
        </form>
    </div>
</div>

{{-- ══ تغيير كلمة المرور ══ --}}
<div class="sec-card">
    <div class="sec-card-head" onclick="toggleSection('pwd')">
        <span class="hi" style="background:#fef3c7;color:#92400e"><i class="bi bi-shield-lock-fill"></i></span>
        <span style="flex:1">تغيير كلمة المرور</span>
        <i class="bi bi-chevron-down" id="ico-pwd" style="color:var(--t3);transition:transform .2s"></i>
    </div>
    <div class="edit-panel" id="sec-pwd">
        <form method="POST" action="{{ route('patient.profile.update') }}">
            @csrf @method('PUT')
            <input type="hidden" name="name" value="{{ $u->name }}">
            <input type="hidden" name="phone" value="{{ $u->phone }}">
            <div class="field-row">
                <label class="field-label">كلمة المرور الجديدة</label>
                <input type="password" name="new_password" class="field-inp" placeholder="8 أحرف على الأقل" oninput="checkPwd(this.value)">
                <div class="pwd-bar"><div class="pwd-fill" id="pf"></div></div>
            </div>
            <div class="field-row">
                <label class="field-label">تأكيد كلمة المرور</label>
                <input type="password" name="new_password_confirmation" class="field-inp" placeholder="أعد كتابة كلمة المرور">
            </div>
            <button type="submit" class="save-btn" style="background:#92400e">
                <i class="bi bi-shield-check"></i>تغيير كلمة المرور
            </button>
        </form>
    </div>
</div>

{{-- ══ تسجيل الخروج ══ --}}
<div style="margin:0 1rem 1.5rem">
    <form method="POST" action="{{ route('patient.logout') }}">
        @csrf
        <button type="submit"
                style="width:100%;padding:.8rem;background:#fee2e2;color:#dc2626;border:none;border-radius:var(--rs);font-weight:700;font-size:.9rem;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:.5rem">
            <i class="bi bi-box-arrow-right"></i>تسجيل الخروج
        </button>
    </form>
</div>

@endsection

@push('scripts')
<script>
function toggleSection(id){
    const panel = document.getElementById('sec-'+id);
    const icon  = document.getElementById('ico-'+id);
    const isOpen = panel.classList.contains('open');
    // Close all
    document.querySelectorAll('.edit-panel').forEach(p=>p.classList.remove('open'));
    document.querySelectorAll('[id^="ico-"]').forEach(i=>i.style.transform='rotate(0)');
    // Toggle
    if(!isOpen){
        panel.classList.add('open');
        if(icon) icon.style.transform='rotate(180deg)';
    }
}

function checkPwd(v){
    let s=0;
    if(v.length>=8)s++;if(/[A-Z]/.test(v))s++;if(/[0-9]/.test(v))s++;if(/[^A-Za-z0-9]/.test(v))s++;
    const clrs=['#e5e7eb','#ef4444','#f59e0b','#10b981','#059669'];
    const pcts=[0,25,50,75,100];
    document.getElementById('pf').style.width=pcts[s]+'%';
    document.getElementById('pf').style.background=clrs[s];
}

// Auto-open if errors
@if($errors->any())
toggleSection('edit-info');
@endif
</script>
@endpush
