<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use Illuminate\Http\Request;

class AppointmentController extends Controller
{
    public function index(Request $request)
    {
        $appointments = Appointment::with(['doctor.user', 'patient.user'])
            ->when($request->search, fn($q) =>
                $q->whereHas('patient.user', fn($u) =>
                    $u->where('name', 'like', "%{$request->search}%")
                )->orWhereHas('doctor.user', fn($u) =>
                    $u->where('name', 'like', "%{$request->search}%")
                )
            )
            ->when($request->status, fn($q) =>
                $q->where('status', $request->status)
            )
            ->when($request->date, fn($q) =>
                $q->whereDate('appointment_date', $request->date)
            )
            ->latest('appointment_date')
            ->paginate(15)
            ->withQueryString();

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

    public function show($id)
    {
        $appointment = Appointment::with([
            'doctor.user',
            'patient.user',
            'medicalRecord',
        ])->findOrFail($id);

        return view('admin.appointments.show', compact('appointment'));
    }
}
