<?php

namespace App\Filters;

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

/**
 * Requires an authenticated session. Restores one from the persistent-login
 * cookie when the CI4 session is gone but a valid token exists (Phase 2).
 */
class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (! $session->get('user_id')) {
            (new PersistentLoginService())->restoreSessionIfValid();
        }

        if (! $session->get('user_id')) {
            if ($request->isAJAX()) {
                return service('response')
                    ->setStatusCode(401)
                    ->setJSON([
                        'ok'    => false,
                        'error' => 'Please sign in.',
                    ]);
            }

            return redirect()->to('/sign-in')->withCookies();
        }

        $path = implode('/', $request->getUri()->getSegments());
        $onboardingExempt = in_array($path, [
            'logout',
            'profile/onboarding',
        ], true);

        if ((int) $session->get('profile_onboarding_completed') !== 1 && ! $onboardingExempt) {
            if ($request->isAJAX()) {
                return service('response')
                    ->setStatusCode(403)
                    ->setJSON([
                        'ok'       => false,
                        'error'    => 'Please complete profile onboarding.',
                        'redirect' => site_url('profile/onboarding'),
                    ]);
            }

            return redirect()->to('/profile/onboarding')->withCookies();
        }

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        $response->removeHeader('Cache-Control');

        return $response
            ->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
            ->setHeader('Pragma', 'no-cache');
    }
}
