<?php
namespace App\Http\Controllers\Patient;
use App\Http\Controllers\Controller;
use App\Models\{Appointment,Queue,PatientNotification,Doctor};
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class DashboardController extends Controller
{
    public function index()
    {
        $pid     = session('patient_id');
        $patient = \App\Models\Patient::with('user')->find($pid);

        $currentQueue = Queue::with('doctor.user')
            ->where('patient_id',$pid)->today()
            ->whereIn('status',['waiting','called','in_progress'])->first();

        $queueAhead = $currentQueue
            ? Queue::where('doctor_id',$currentQueue->doctor_id)->today()->waiting()
                ->where('position','<',$currentQueue->position)->count()
            : 0;

        $upcomingAppointments = Appointment::with('doctor.user')
            ->where('patient_id',$pid)->whereDate('appointment_date','>=',today())
            ->whereIn('status',['confirmed','pending'])
            ->orderBy('appointment_date')->orderBy('appointment_time')->take(3)->get();

        // إعلانات السلايدر (أعلى الرئيسية) — صورة / GIF / فيديو قصير
        $advertisements = \App\Models\Advertisement::active()
            ->patientHomeSlider()
            ->orderBy('sort_order')
            ->take(5)
            ->get();

        // News
        $news = \App\Models\News::published()->latest('published_at')->take(5)->get();

        // Cities list
        $allCities = Doctor::where('status','active')->whereNotNull('city')->distinct()->pluck('city');

        // Patient city
        $patientCity = $patient->user->city ?? null;

        // Nearby doctors
        $nearbyDoctors = Doctor::with('user')
            ->where('status','active')
            ->when($patientCity, fn($q) => $q->where('city',$patientCity))
            ->orderByDesc('rating')->take(6)->get();

        if ($nearbyDoctors->count() < 3) {
            $nearbyDoctors = Doctor::with('user')->where('status','active')
                ->orderByDesc('rating')->take(6)->get();
        }

        $unreadCount   = PatientNotification::where('patient_id',$pid)->where('is_read',false)->count();
        $upcomingCount = Appointment::where('patient_id',$pid)->whereDate('appointment_date','>=',today())->whereIn('status',['confirmed','pending'])->count();
        $recordsCount  = \App\Models\MedicalRecord::where('patient_id',$pid)->count();

        return view('patient.dashboard.index', compact(
            'currentQueue','queueAhead','upcomingAppointments',
            'advertisements','news','allCities','patientCity',
            'nearbyDoctors','unreadCount','upcomingCount','recordsCount','patient'
        ));
    }

    public function profile()
    {
        $patient = \App\Models\Patient::with('user')->find(session('patient_id'));
        return view('patient.profile.index', compact('patient'));
    }

    public function updateProfile(Request $request)
    {
        $patient = \App\Models\Patient::with('user')->find(session('patient_id'));
        $data = $request->validate([
            'name'               => 'required|string|max:100',
            'phone'              => 'required|string|unique:users,phone,'.$patient->user_id,
            'email'              => 'nullable|email|unique:users,email,'.$patient->user_id,
            'gender'             => 'nullable|in:male,female',
            'date_of_birth'      => 'nullable|date',
            'blood_type'         => 'nullable|in:A+,A-,B+,B-,AB+,AB-,O+,O-',
            'chronic_diseases'   => 'nullable|string|max:500',
            'allergies'          => 'nullable|string|max:500',
            'current_medications'=> 'nullable|string|max:500',
            'new_password'       => 'nullable|string|min:8|confirmed',
        ]);
        $patient->user->update(['name'=>$data['name'],'phone'=>$data['phone'],'email'=>$data['email']??null]);
        $patient->update(\Illuminate\Support\Arr::except($data,['name','phone','email','new_password','new_password_confirmation']));
        if (!empty($data['new_password'])) $patient->user->update(['password'=>Hash::make($data['new_password'])]);
        return back()->with('success','تم تحديث ملفك الشخصي');
    }
}
