<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Doctor;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DoctorController extends Controller
{
    public function index(Request $request)
    {
        $query = Doctor::with('user')
            ->when($request->search, fn ($q) =>
                $q->whereHas('user', fn ($u) =>
                    $u->where('name', 'like', "%{$request->search}%")
                      ->orWhere('email', 'like', "%{$request->search}%")
                      ->orWhere('phone', 'like', "%{$request->search}%")
                )
            )
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->when($request->specialty, fn ($q) => $q->where('specialty', $request->specialty))
            ->latest();

        $doctors     = $query->paginate(15)->withQueryString();
        $specialties = Doctor::distinct()->pluck('specialty');

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

    public function create()
    {
        return view('admin.doctors.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'             => 'required|string|max:100',
            'email'            => 'nullable|email|unique:users,email',
            'phone'            => 'required|string|unique:users,phone',
            'specialty'        => 'required|string|max:100',
            'license_number'   => 'required|string|unique:doctors,license_number',
            'clinic_name'      => 'nullable|string|max:100',
            'clinic_address'   => 'nullable|string',
            'city'             => 'nullable|string|max:50',
            'latitude'         => 'nullable|numeric',
            'longitude'        => 'nullable|numeric',
            'experience_years' => 'nullable|integer|min:0',
            'consultation_fee' => 'nullable|numeric|min:0',
            'phone_clinic'     => 'nullable|string|max:20',
        ]);

        $email = ! empty($data['email']) ? $data['email'] : null;

        DB::beginTransaction();
        try {
            $user = User::create([
                'name'      => $data['name'],
                'email'     => $email,
                'phone'     => $data['phone'],
                'password'  => User::randomPasswordHash(),
                'role'      => 'doctor',
                'is_active' => true,
            ]);

            Doctor::create([
                'user_id'          => $user->id,
                'specialty'        => $data['specialty'],
                'license_number'   => $data['license_number'],
                'clinic_name'      => $data['clinic_name']      ?? null,
                'clinic_address'   => $data['clinic_address']   ?? null,
                'city'             => $data['city']             ?? null,
                'latitude'         => $data['latitude']         ?? null,
                'longitude'        => $data['longitude']        ?? null,
                'experience_years' => $data['experience_years'] ?? 0,
                'consultation_fee' => $data['consultation_fee'] ?? 0,
                'phone'            => $data['phone_clinic']     ?? null,
                'status'           => 'active',
                'is_verified'      => true,
                'verified_at'      => now(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            return back()->with('error', 'حدث خطأ: ' . $e->getMessage())->withInput();
        }

        return redirect()->route('admin.doctors.index')
            ->with('success', 'تم إضافة الطبيب ' . $data['name'] . ' بنجاح — الحساب مفعّل ويمكنه الدخول برقم هاتفه');
    }

    public function show($id)
    {
        $doctor = Doctor::with([
            'user', 'activeSubscription.plan',
            'secretaries.user', 'media',
            'reviews' => fn ($q) => $q->with('patient.user')->latest()->take(10),
        ])->findOrFail($id);

        $stats = [
            'total_appointments' => $doctor->appointments()->count(),
            'total_patients'     => $doctor->medicalRecords()->distinct('patient_id')->count('patient_id'),
            'today_queue'        => $doctor->queues()->whereDate('queue_date', today())->count(),
            'completed_today'    => $doctor->queues()->whereDate('queue_date', today())->where('status', 'completed')->count(),
        ];

        return view('admin.doctors.show', compact('doctor', 'stats'));
    }

    public function approve($id)
    {
        Doctor::findOrFail($id)->update(['status' => 'active', 'is_verified' => true, 'verified_at' => now()]);

        return back()->with('success', 'تمت الموافقة على الطبيب');
    }

    public function suspend(Request $request, $id)
    {
        Doctor::findOrFail($id)->update(['status' => 'suspended']);

        return back()->with('success', 'تم إيقاف حساب الطبيب');
    }

    public function destroy($id)
    {
        Doctor::findOrFail($id)->delete();

        return redirect()->route('admin.doctors.index')->with('success', 'تم حذف الطبيب');
    }
}
