<?php

namespace Core\Middleware;


use Core\Auth;
use Core\Response;
use App\Models\Department;

class DepartmentMiddleware implements MiddlewareInterface
{
    /**
     * @var string The department name to check against.
     */
    private $departmentName;

    /**
     * DepartmentMiddleware constructor.
     *
     * @param string $departmentName The name of the department associated with the route.
     */
    public function __construct(string $departmentName)
    {
        $this->departmentName = $departmentName;
    }

    /**
     * Handles the middleware logic.
     *
     * @param \Core\Router $router The router instance.
     * @return bool True if access is granted, false otherwise.
     */
    public function handle(string $uri, string $method, array $params)
    {
        $user = Auth::user();

        // If the user is not authenticated for any reason, deny access.
        if (!$user) {
            Response::redirect(APP_URL . '/login');
            return false;
        }

        // Super Admins, Directors, and Managers can bypass the department-specific check.
        // This grants them access to all departments within their scope.
        if (in_array($user['role'], ['super_admin', 'director', 'manager'])) {
            return true;
        }

        // Only staff members are restricted to a single department.
        // We check if their assigned department_id matches the one in the route.

        $department = Department::where('name', ucfirst($this->departmentName));



        if ($user['role'] === 'staff' && $user['department_id'] === $department['id']) {
            return true;
        }


        // If no conditions are met, the user is unauthorized.
       Response::redirect(APP_URL . '/dashboard');
        return false;
    }
}
