<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Patient;
use App\Models\User;
use Illuminate\Http\Request;

class PatientController extends Controller
{
    public function index(Request $request)
    {
        $patients = User::where('role', 'patient')
            ->with('patient')
            ->when($request->search, fn($q) =>
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%")
                  ->orWhere('phone', 'like', "%{$request->search}%")
            )
            ->latest()
            ->paginate(15)
            ->withQueryString();

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

    public function show($id)
    {
        $patient = Patient::with([
            'user',
            'medicalRecords' => fn($q) => $q->with('doctor.user')->latest()->take(10),
            'appointments'   => fn($q) => $q->with('doctor.user')->latest()->take(10),
        ])->findOrFail($id);

        $stats = [
            'total_appointments' => $patient->appointments()->count(),
            'total_records'      => $patient->medicalRecords()->count(),
            'doctors_visited'    => $patient->medicalRecords()->distinct('doctor_id')->count('doctor_id'),
        ];

        return view('admin.patients.show', compact('patient', 'stats'));
    }

    public function toggleActive($user)
    {
        $patientUser = User::where('role', 'patient')->findOrFail($user);
        $patientUser->update(['is_active' => ! $patientUser->is_active]);

        return back()->with('success', $patientUser->is_active ? 'تم تفعيل حساب المريض' : 'تم إيقاف حساب المريض');
    }

    public function destroy($id)
    {
        $patient = Patient::findOrFail($id);
        $patient->user()->delete();
        $patient->delete();

        return redirect()->route('admin.patients.index')
            ->with('success', 'تم حذف المريض بنجاح');
    }
}
