<?php

namespace App\Http\Controllers\Doctors;

use App\DataTables\DoctorsDataTable;
use App\Http\Controllers\Controller;
use App\Models\Prescriptions;
use App\Models\Specialties;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class DoctorController extends Controller
{
    public function index(DoctorsDataTable $dataTable)
    {
        return $dataTable->render('admin.doctors.index');
    }

    public function create(Request $request)
    {
        $user = Auth::user();

        $specialties = Specialties::orderBy('name')->get();
        $selectedSpecialtyId = $request->get('specialty_id');
        if (!$user || !$user->clinic_id) {
            abort(403, 'لا يمكنك إضافة دكتور بدون عيادة مرتبطة بحسابك.');
        }

        return view('admin.doctors.create', compact('specialties', 'user','selectedSpecialtyId'));
    }

    public function store(Request $request)
    {
        $authUser = Auth::user();

        if (!$authUser || !$authUser->clinic_id) {
            abort(403, 'لا يمكنك إضافة دكتور بدون عيادة مرتبطة بحسابك.');
        }

        $data = $request->validate([
            'name'         => ['required', 'string', 'max:255'],
            'email'        => ['required', 'email', 'max:255', 'unique:users,email'],
            'phone'        => ['nullable', 'string', 'max:50'],
            'password'     => ['required', 'string', 'min:6'],
            'specialty_id' => ['required', 'exists:specialties,id'],
            'is_active'    => ['nullable', 'boolean'],
        ], [
            'name.required'         => 'من فضلك أدخل اسم الدكتور.',
            'email.required'        => 'من فضلك أدخل البريد الإلكتروني.',
            'email.email'           => 'البريد الإلكتروني غير صالح.',
            'email.unique'          => 'هذا البريد مستخدم بالفعل.',
            'password.required'     => 'من فضلك أدخل كلمة المرور.',
            'specialty_id.required' => 'من فضلك اختر تخصص الدكتور.',
            'specialty_id.exists'   => 'التخصص المختار غير موجود.',
        ]);

        $isActive = $request->has('is_active') ? (bool)$data['is_active'] : true;

        $doctorUser = User::create([
            'name'      => $data['name'],
            'email'     => $data['email'],
            'phone'     => $data['phone'] ?? null,
            'password'  => Hash::make($data['password']),
            'role'      => 'doctor',
            'clinic_id' => $authUser->clinic_id,
            'branch_id' => $authUser->branch_id,
            'is_active' => $isActive,
        ]);

        $doctorUser->doctorProfile()->create([
            'clinic_id'    => $authUser->clinic_id,
            'branch_id'    => $authUser->branch_id,
            'specialty_id' => $data['specialty_id'],
        ]);

        return redirect()
            ->route('doctors.show', $doctorUser->id)
            ->with('success', 'تم إضافة الدكتور بنجاح.');
    }





    protected function authorizeDoctor(User $doctor): void
    {
        $user = Auth::user();

        if (!$user || !$user->clinic_id) {
            abort(403, 'غير مصرح لك بالوصول إلى هذا الطبيب.');
        }

        if ($doctor->clinic_id !== $user->clinic_id) {
            abort(404);
        }

        if ($user->role !== 'owner' && $user->branch_id && $doctor->branch_id !== $user->branch_id) {
            abort(404);
        }
    }

    public function show($id)
    {
        $doctor = User::with([
            'doctorProfile.specialty',
            'clinic',
            'branch',
        ])
            ->where('role', 'doctor')
            ->findOrFail($id);

        $profile = $doctor->doctorProfile;

        if (!$profile) {
            $appointments = collect();
            $visits = collect();
            $prescriptions = collect();
        } else {
            $appointments = $profile->appointments()
                ->with('patient')
                ->orderByDesc('appointment_date')
                ->paginate(20, ['*'], 'appointments_page');

            $visits = $profile->visits()
                ->with('patient')
                ->orderByDesc('visit_date')
                ->paginate(20, ['*'], 'visits_page');

            $prescriptions = $profile->prescriptions()
                ->with('patient')
                ->orderByDesc('created_at')
                ->paginate(10, ['*'], 'prescriptions_page');
        }

        return view('admin.doctors.show', [
            'doctor' => $doctor,
            'profile' => $profile,
            'appointments' => $appointments,
            'visits' => $visits,
            'prescriptions' => $prescriptions,
        ]);
    }

    public function edit($id)
    {
        $doctor = User::with([
            'doctorProfile.specialty',
            'clinic',
            'branch',
        ])
            ->where('role', 'doctor')
            ->findOrFail($id);

        $this->authorizeDoctor($doctor);

        $specialties = Specialties::orderBy('name')->get();

        return view('admin.doctors.edit', compact('doctor', 'specialties'));
    }



    public function update(Request $request, $id)
    {
        $doctor = User::with('doctorProfile')
            ->where('role', 'doctor')
            ->findOrFail($id);

        $this->authorizeDoctor($doctor);

        $data = $request->validate([
            'name'         => ['required', 'string', 'max:255'],
            'email'        => ['required', 'email', 'max:255', 'unique:users,email,' . $doctor->id],
            'phone'        => ['nullable', 'string', 'max:50'],
            'password'     => ['nullable', 'string', 'min:6'],
            'specialty_id' => ['required', 'exists:specialties,id'],

        ], [
            'name.required'         => 'من فضلك أدخل اسم الدكتور.',
            'email.required'        => 'من فضلك أدخل البريد الإلكتروني.',
            'email.email'           => 'البريد الإلكتروني غير صالح.',
            'email.unique'          => 'هذا البريد مستخدم بالفعل.',
            'specialty_id.required' => 'من فضلك اختر تخصص الدكتور.',
            'specialty_id.exists'   => 'التخصص المختار غير موجود.',
            'is_active.required'    => 'من فضلك اختر حالة الدكتور.',
        ]);

        $doctor->name      = $data['name'];
        $doctor->email     = $data['email'];
        $doctor->phone     = $data['phone'] ?? null;


        if (!empty($data['password'])) {
            $doctor->password = Hash::make($data['password']);
        }

        $doctor->save();

        $profile = $doctor->doctorProfile;

        if (!$profile) {
            $profile = $doctor->doctorProfile()->create([
                'clinic_id'    => $doctor->clinic_id,
                'branch_id'    => $doctor->branch_id,
                'specialty_id' => $data['specialty_id'],
            ]);
        } else {
            $profile->specialty_id = $data['specialty_id'];
            $profile->save();
        }

        return redirect()
            ->route('doctors.show', $doctor->id)
            ->with('success', 'تم تحديث بيانات الدكتور بنجاح.');
    }

    public function toggleStatus(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:users,id',
            'is_active' => 'required|boolean',
        ]);

        $doctor = User::where('role', 'doctor')->where('id', $request->id)->firstOrFail();

        $doctor->is_active = $request->is_active;
        $doctor->save();

        return response()->json([
            'status' => true,
            'message' => 'تم تحديث حالة الدكتور بنجاح'
        ]);
    }

    public function destroy($id)
    {
        $doctor = User::findorfail($id);
        $this->authorizeDoctor($doctor);
        $checkDoctor = Prescriptions::where('doctor_id', $doctor->doctorProfile->id)->first();
        if ($checkDoctor) {
            return redirect()->route('doctors.index')->with('error', 'لا يمكن حذف الطبيب لانه لديه مرضي مسجله');
        }

        User::deleted($id);
        return redirect()->route('doctors.index')->with('success', 'تم حذف الطبيب بنجاح');
    }

}
