<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\PatientRequest;
use App\Models\Patient;

class PatientController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', Patient::class);

        return view('patients.index', [
            'patients' => Patient::search(request('q'))
                ->orderByDesc('updated_at')
                ->paginate(25)
                ->withQueryString(),
            'q' => request('q'),
        ]);
    }

    public function create()
    {
        $this->authorize('create', Patient::class);

        return view('patients.form', ['patient' => new Patient()]);
    }

    public function store(PatientRequest $request)
    {
        $this->authorize('create', Patient::class);

        $patient = Patient::create($request->validated());

        return redirect()
            ->route('tenant.patients.show', $patient)
            ->with('status', __('Patient created.'));
    }

    public function show(Patient $patient)
    {
        $this->authorize('view', $patient);

        return view('patients.show', [
            'patient' => $patient,
            'appointments' => $patient->appointments()
                ->with('dentist')
                ->orderByDesc('starts_at')
                ->paginate(15),
        ]);
    }

    public function edit(Patient $patient)
    {
        $this->authorize('update', $patient);

        return view('patients.form', compact('patient'));
    }

    public function update(PatientRequest $request, Patient $patient)
    {
        $this->authorize('update', $patient);
        $patient->update($request->validated());

        return redirect()
            ->route('tenant.patients.show', $patient)
            ->with('status', __('Changes saved.'));
    }

    public function destroy(Patient $patient)
    {
        $this->authorize('delete', $patient);
        $patient->delete();

        return redirect()->route('tenant.patients.index')
            ->with('status', __('Patient removed.'));
    }
}
