<?php

namespace App\Filters;

use App\Services\ModuleRegistryService;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Blocks access to routes belonging to disabled modules.
 */
class ModuleEnabledFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('isLoggedIn')) {
            return;
        }

        $path = trim($request->getUri()->getPath(), '/');

        // Strip index.php prefix if present.
        if (str_starts_with($path, 'index.php/')) {
            $path = substr($path, strlen('index.php/'));
        }

        $registry = new ModuleRegistryService();

        if ($registry->pathIsAccessible($path)) {
            return;
        }

        $moduleKey = $registry->resolveModuleForPath($path);
        $label     = $moduleKey
            ? (config('ModuleRegistry')->registry[$moduleKey]['label'] ?? ucfirst($moduleKey))
            : 'This module';

        $session->setFlashdata('error', $label . ' is not enabled for your company. Contact an administrator.');

        return redirect()->to('/dashboard');
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No-op.
    }
}
