<?php
/**
 * Middleware Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Middlewares
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Http\Middleware;


use BplanBase\Globals\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;


/**
 * Middleware Class
 *
 * @version     1.0.0 / 2025-04-15
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class CheckAccessLevelOrRoles
{

    /**
     * Handle an incoming request.
     *
     * @param       Request $Request
     *
     * @param       Closure $Next
     *
     * @param       string $requiredLevel
     *              Use "null" to omit this parameter
     *
     * @param       string ...$roles
     *
     * @return      Response
     *
     * @version     1.0.0 / 2025-04-15
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function handle(Request $Request, Closure $Next, $requiredLevel, ...$roles): Response
    {
        $User = $Request->user() ?? new User();

        $accessGranted = false;

        if (strtolower($requiredLevel) === 'null') {
            $requiredLevel = null;
        }
        if ($requiredLevel !== null) {
            if ($User->hasMinAccessLevel($requiredLevel)) {
                $accessGranted = true;
            }
        }
        if($accessGranted === false && !empty($roles)) {
            if ($User->hasAnyRole($roles)) {
                $accessGranted = true;
            }
        }
        if($accessGranted === true) {
            return $Next($Request);
        }
        return redirect('login');

    } // handle()


} // class CheckAccessLevelOrRoles {}
