<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\Module\Redirect;

use Inpsyde\MultilingualPress\Module\Redirect\NoRedirectStorage\NoRedirectStorage;
use Inpsyde\MultilingualPress\Module\Redirect\Settings\Repository\Repository;

use function Inpsyde\MultilingualPress\siteLanguageTag;

/**
 * Request validator to be used for (potential) redirect requests.
 */
class RedirectRequestChecker
{
    public const FILTER_REDIRECT = 'multilingualpress.do_redirect';

    /**
     * @var NoRedirectStorage
     */
    private $noRedirectStorage;

    /**
     * @var Repository
     */
    private $settingsRepository;

    public function __construct(Repository $settingsRepository, NoRedirectStorage $redirectStorage)
    {
        $this->settingsRepository = $settingsRepository;
        $this->noRedirectStorage = $redirectStorage;
    }

    /**
     * Checks if the current request should be redirected.
     *
     * @return bool true if the current request should be redirected, otherwise false.
     */
    public function isRedirectRequest(): bool
    {
        if ('wp-login.php' === ($GLOBALS['pagenow'] ?? '')) {
            return false;
        }

        $redirectDisabledForUser = $this->settingsRepository->redirectUserSetting(get_current_user_id(), Repository::META_KEY_USER);
        $redirectEnabledForSite = $this->settingsRepository->redirectSiteSetting(get_current_blog_id(), Repository::OPTION_SITE_ENABLE_REDIRECT) ?: false;

        if (!$redirectEnabledForSite || $redirectDisabledForUser || $this->noRedirectStorage->hasLanguage(siteLanguageTag())) {
            return false;
        }

        /**
         * Filters if the current request should be redirected.
         *
         * @param bool $redirect
         */
        return (bool)apply_filters(static::FILTER_REDIRECT, true);
    }
}
