<?php
namespace App\Http\Middleware;

use App\Models\Admin;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AdminPermission
{
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            return redirect()->route('admin.login')->with('error', 'Please login first.');
        }

        $admin = Admin::find($adminId);
        if (!$admin || $admin->status !== 'Active') {
            $request->session()->flush();
            return redirect()->route('admin.login')->with('error', 'User inactive or not found.');
        }

        if (!$admin->hasPermission($permission)) {
            return redirect()->route('admin.dashboard')->with('error', 'You do not have permission for this section.');
        }

        view()->share('currentAdmin', $admin);
        return $next($request);
    }
}
