<?php

namespace App\Http\Middleware;

use App\Models\Route;
use App\Models\RoleUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckRoutePermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Get current path
        $path = $request->path();
        
        // Check if the route is defined in our routes table
        $route = Route::matchPath($path);
        
        // If route not defined in our custom routes table, allow access (fallback to default Laravel auth)
        if (!$route) {
            return $next($request);
        }
        
        // If route is public, allow access
        if ($route->is_public) {
            return $next($request);
        }
        
        // If user is not authenticated, redirect to login
        if (!Auth::check()) {
            return redirect()->route('login');
        }
        
        // Get user role
        $user = Auth::user();
        $roleUser = RoleUser::where('user_id', $user->id)->first();
        
        if (!$roleUser) {
            return redirect()->route('not-authorized');
        }
        
        // Check if user's role has access to this route
        if ($route->hasRole($roleUser->role_id)) {
            return $next($request);
        }
        
        // If no access, redirect to not authorized page
        return redirect()->route('not-authorized');
    }
}
