<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Requires a logged-in staff user for the current tenant. Applied per
 * route-group (see app/Config/Routes.php) rather than globally, so the
 * login page itself and the tenant-unknown error page stay reachable.
 *
 * Session is tenant-scoped by nature: TenantResolver runs first, and a
 * session started under one tenant's login simply doesn't carry a role
 * that means anything on another tenant's data, since every tenant-scoped
 * query goes through that tenant's own `users` table.
 */
class Auth implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('isLoggedIn')) {
            $session->setFlashdata('error', 'Please log in to continue.');

            return redirect()->to(site_url('login'))->withCookies();
        }

        return null;
    }

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