<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RiderMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!session()->has('rider_id')) {
            return redirect()->route('rider.login')->with('error', 'Please login to access the rider portal.');
        }

        // Fetch active delivery man
        $rider = \App\Models\DeliveryMan::find(session('rider_id'));
        if (!$rider || $rider->status !== 'active') {
            session()->forget('rider_id');
            return redirect()->route('rider.login')->with('error', 'Account inactive or not found.');
        }

        return $next($request);
    }
}
