<?php

namespace App\Http\Controllers\Patient;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Doctor;
use App\Models\Queue;
use App\Models\PatientNotification;
use Illuminate\Http\Request;

class AppointmentController extends Controller
{
    // ===== قائمة المواعيد =====
    public function index()
    {
        $patientId = session('patient_id');

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

        $past = Appointment::with('doctor.user')
            ->where('patient_id', $patientId)
            ->where(fn($q) =>
                $q->whereDate('appointment_date', '<', today())
                  ->orWhereIn('status', ['completed','cancelled','no_show'])
            )
            ->latest('appointment_date')
            ->paginate(10);

        return view('patient.appointments.index', compact('upcoming', 'past'));
    }

    // ===== حجز موعد =====
    public function store(Request $request)
    {
        $data = $request->validate([
            'doctor_id'        => 'required|exists:doctors,id',
            'appointment_date' => 'required|date|after_or_equal:today',
            'appointment_time' => 'required|string',
            'reason'           => 'nullable|string|max:300',
        ]);

        $doctor = Doctor::findOrFail($data['doctor_id']);

        // التحقق: هل يوجد موعد في نفس الوقت
        $exists = Appointment::where('doctor_id', $data['doctor_id'])
            ->where('appointment_date', $data['appointment_date'])
            ->where('appointment_time', $data['appointment_time'])
            ->whereIn('status', ['pending','confirmed'])->exists();

        if ($exists) {
            return back()->with('error', 'هذا الوقت محجوز مسبقاً، اختر وقتاً آخر');
        }

        $appointment = Appointment::create([
            'doctor_id'        => $data['doctor_id'],
            'patient_id'       => session('patient_id'),
            'appointment_date' => $data['appointment_date'],
            'appointment_time' => $data['appointment_time'],
            'reason'           => $data['reason'] ?? null,
            'status'           => 'pending',
            'fee'              => $doctor->consultation_fee,
        ]);

        PatientNotification::send(
            session('patient_id'),
            'appointment_confirmed',
            'تم حجز موعدك',
            'تم حجز موعدك عند د. ' . $doctor->user->name . ' بتاريخ ' . $data['appointment_date'] . ' الساعة ' . $data['appointment_time'],
            ['appointment_id' => $appointment->id],
            $doctor->id
        );

        return redirect()->route('patient.appointments.index')
            ->with('success', 'تم حجز الموعد بنجاح — في انتظار التأكيد');
    }

    // ===== إلغاء موعد =====
    public function cancel($id)
    {
        $appt = Appointment::where('patient_id', session('patient_id'))
            ->whereIn('status', ['pending','confirmed'])
            ->findOrFail($id);

        $appt->update(['status' => 'cancelled', 'cancelled_at' => now()]);

        return back()->with('success', 'تم إلغاء الموعد');
    }

    // ===== الانضمام للطابور =====
    public function joinQueue(Request $request, $doctorId)
    {
        $patientId = session('patient_id');
        $doctor    = Doctor::findOrFail($doctorId);

        if ($doctor->status !== 'active') {
            return back()->with('error', 'الطبيب غير متاح حالياً');
        }

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

        if ($exists) {
            return back()->with('error', 'أنت مسجل بالفعل في طابور هذا الطبيب');
        }

        $todayCount = Queue::where('doctor_id', $doctorId)->today()->count();
        if ($todayCount >= $doctor->max_daily_patients) {
            return back()->with('error', 'الطابور ممتلئ لهذا اليوم');
        }

        $lastNum = Queue::where('doctor_id', $doctorId)->today()->max('queue_number') ?? 0;
        $waitPos = Queue::where('doctor_id', $doctorId)->today()
                        ->whereIn('status',['waiting','called'])->count();

        $queue = Queue::create([
            'doctor_id'              => $doctorId,
            'patient_id'             => $patientId,
            'queue_date'             => today(),
            'queue_number'           => $lastNum + 1,
            'position'               => $waitPos + 1,
            'status'                 => 'waiting',
            'arrived_at'             => now(),
            'estimated_wait_minutes' => ($waitPos + 1) * ($doctor->appointment_duration ?? 15),
        ]);

        PatientNotification::send(
            $patientId,
            'queue_position',
            'تم تسجيلك في الطابور',
            'رقمك في الطابور عند د. ' . $doctor->user->name . ' هو: ' . $queue->queue_number . ' — الانتظار المتوقع: ' . $queue->estimated_wait_minutes . ' دقيقة',
            ['queue_id' => $queue->id, 'doctor_id' => $doctorId],
            $doctorId
        );

        return back()->with('success', 'تم تسجيلك في الطابور برقم ' . $queue->queue_number);
    }

    // ===== حالة الطابور =====
    public function queueStatus()
    {
        $patientId = session('patient_id');

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

        if (! $queue) {
            return view('patient.appointments.queue_status', ['queue' => null]);
        }

        $ahead = Queue::where('doctor_id', $queue->doctor_id)
            ->today()->waiting()
            ->where('position', '<', $queue->position)->count();

        return view('patient.appointments.queue_status', compact('queue', 'ahead'));
    }

    // ===== مغادرة الطابور =====
    public function leaveQueue()
    {
        $queue = Queue::where('patient_id', session('patient_id'))
            ->today()->whereIn('status', ['waiting','called'])->first();

        if ($queue) {
            $pos = $queue->position;
            $queue->update(['status' => 'left']);
            Queue::where('doctor_id', $queue->doctor_id)
                ->today()->waiting()
                ->where('position', '>', $pos)->decrement('position');
        }

        return back()->with('success', 'تم الخروج من الطابور');
    }
}
