<?php
namespace App\Http\Controllers\Patient;
use App\Http\Controllers\Controller;
use App\Models\{Doctor,Queue,Review,Patient};
use Illuminate\Http\Request;

class DoctorController extends Controller
{
    public function index(Request $request)
    {
        $patient     = Patient::with('user')->find(session('patient_id'));
        $patientCity = $patient->user->city ?? null;

        $doctors = Doctor::with('user')
            ->where('status','active')
            ->when($request->search, fn($q) =>
                $q->whereHas('user', fn($u) =>
                    $u->where('name','like',"%{$request->search}%")
                )->orWhere('specialty','like',"%{$request->search}%")
                 ->orWhere('clinic_name','like',"%{$request->search}%")
                 ->orWhere('city','like',"%{$request->search}%")
            )
            ->when($request->specialty, fn($q) => $q->where('specialty',$request->specialty))
            ->when($request->city, fn($q) => $q->where('city',$request->city))
            ->orderByDesc('rating')
            ->paginate(12)->withQueryString();

        $specialties = Doctor::where('status','active')->distinct()->pluck('specialty')->sort()->values();
        $cities      = Doctor::where('status','active')->whereNotNull('city')->distinct()->pluck('city')->sort()->values();

        return view('patient.doctors.index', compact('doctors','specialties','cities','patientCity'));
    }

    public function show($id)
    {
        $doctor = Doctor::with([
            'user',
            'media' => fn ($q) => $q->where('is_approved', true)->orderBy('sort_order'),
            'reviews' => fn($q) => $q->where('is_approved',true)->with('patient.user')->latest()->take(10),
        ])->where('status','active')->findOrFail($id);

        $pid = session('patient_id');

        $todayQueue = Queue::where('doctor_id',$id)->today()
            ->whereIn('status',['waiting','called','in_progress'])->count();

        $patientInQueue = Queue::where('doctor_id',$id)
            ->where('patient_id',$pid)->today()
            ->whereIn('status',['waiting','called','in_progress'])->exists();

        $myReview = Review::where('doctor_id',$id)
            ->where('patient_id',$pid)->first();

        $ratingBreakdown = [];
        for($i=5;$i>=1;$i--){
            $count = Review::where('doctor_id',$id)->where('is_approved',true)->where('rating',$i)->count();
            $ratingBreakdown[$i] = [
                'count' => $count,
                'pct'   => $doctor->total_reviews > 0 ? round($count/$doctor->total_reviews*100) : 0,
            ];
        }

        return view('patient.doctors.show', compact(
            'doctor','todayQueue','patientInQueue','myReview','ratingBreakdown'
        ));
    }

    public function storeReview(Request $request, $id)
    {
        $pid = session('patient_id');
        $data = $request->validate([
            'rating'       => 'required|integer|between:1,5',
            'comment'      => 'nullable|string|max:500',
            'is_anonymous' => 'nullable|boolean',
        ]);

        // هل زار هذا الطبيب؟
        $hasVisit = \App\Models\MedicalRecord::where('doctor_id',$id)
            ->where('patient_id',$pid)->exists()
            || Queue::where('doctor_id',$id)->where('patient_id',$pid)
               ->where('status','completed')->exists();

        if (!$hasVisit) {
            return back()->with('error','يجب أن تزور الطبيب قبل تقييمه');
        }

        Review::updateOrCreate(
            ['doctor_id'=>$id,'patient_id'=>$pid],
            ['rating'=>$data['rating'],'comment'=>$data['comment']??null,'is_anonymous'=>$request->boolean('is_anonymous'),'is_approved'=>true]
        );

        return back()->with('success','شكراً! تم إرسال تقييمك بنجاح');
    }
}
