<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\Module\Redirect\Redirector;

use Inpsyde\MultilingualPress\Framework\Database\Exception\NonexistentTable;
use Inpsyde\MultilingualPress\Module\Redirect\NoRedirectStorage\NoRedirectStorage;
use Inpsyde\MultilingualPress\Module\Redirect\Settings\Repository\Repository;

use function Inpsyde\MultilingualPress\callExit;
use function Inpsyde\MultilingualPress\isWpDebugMode;
use function Inpsyde\MultilingualPress\siteLanguageTag;
use function Inpsyde\MultilingualPress\siteLocale;

/**
 * Class NotFoundSiteRedirect
 * @package Inpsyde\MultilingualPress\Module\Redirect
 */
class NotFoundSiteRedirect implements Redirector
{
    /**
     * @var Repository
     */
    private $redirectSettingsRepository;

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

    public function __construct(
        Repository $redirectSettingsRepository,
        NoRedirectStorage $noRedirectStorage
    ) {

        $this->redirectSettingsRepository = $redirectSettingsRepository;
        $this->noRedirectStorage = $noRedirectStorage;
    }

    /**
     * @inheritDoc
     */
    public function redirect(): bool
    {
        $siteIdToRedirectTo = (int)$this->redirectSettingsRepository->settingValue(Repository::MODULE_SETTING_FALLBACK_REDIRECT_SITE_ID);

        if (!$siteIdToRedirectTo || $siteIdToRedirectTo < 1) {
            return false;
        }

        try {
            $siteUrlToRedirectTo = $this->redirectUrlForSite($siteIdToRedirectTo);
        } catch (NonexistentTable $exc) {
            if (isWpDebugMode()) {
                throw new $exc();
            }

            return false;
        }

        if (!$siteUrlToRedirectTo) {
            return false;
        }

        $siteLanguageTag = siteLanguageTag($siteIdToRedirectTo);
        $this->noRedirectStorage->addLanguage($siteLanguageTag);

        $this->redirectToUrl($siteUrlToRedirectTo);

        return false;
    }

    /**
     * Retrieve the Site Url Where Redirect the User
     *
     * @param int $siteId
     * @return string
     * @throws NonexistentTable
     */
    protected function redirectUrlForSite(int $siteId): string
    {
        $siteLocale = siteLocale($siteId);
        $siteUrlToRedirectTo = get_site_url($siteId);

        return add_query_arg(['noredirect' => $siteLocale], $siteUrlToRedirectTo);
    }

    /**
     * Do the Redirect and Stop the Execution
     *
     * @param string $url
     */
    protected function redirectToUrl(string $url)
    {
        //phpcs:disable WordPressVIPMinimum.Security.ExitAfterRedirect.NoExit
        //phpcs:disable WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
        wp_redirect($url) and callExit();
    }
}
