<?php

namespace Modules\Auth\Filters;

use App\Models\RolePermissionModel;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Auth\Services\AuthService;

class PermissionFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('isLoggedIn')) {
            return redirect()->to(config('Auth')->loginUrl);
        }

        $requiredSlug = $arguments[0] ?? null;
        if (! $requiredSlug) {
            return;
        }

        $roleId = $session->get('role_id') ? (int) $session->get('role_id') : null;
        if (! $roleId || ! (new RolePermissionModel())->roleHasPermission($roleId, $requiredSlug)) {
            $session->setFlashdata('error', 'You do not have permission to do that.');

            $redirect = (new AuthService())->permissionDeniedRedirectUrl(
                $requiredSlug,
                $roleId,
                $request->getUri()->getPath()
            );

            return redirect()->to($redirect);
        }
    }

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