<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class PatientAuthMiddleware
{
    public function handle(Request $request, Closure $next): mixed
    {
        if (! session('patient_id')) {
            return redirect()->route('patient.login')
                ->with('error', 'يجب تسجيل الدخول أولاً');
        }

        $patient = \App\Models\Patient::with('user')->find(session('patient_id'));

        if (! $patient || ! $patient->user->is_active) {
            session()->forget('patient_id');
            return redirect()->route('patient.login')
                ->with('error', 'الحساب غير نشط');
        }

        view()->share('authPatient', $patient);
        return $next($request);
    }
}
