<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\Module\Redirect\Settings\Repository;

class Repository implements RedirectSettingsRepositoryInterface
{
    public const META_KEY_USER = 'multilingualpress_redirect';
    public const OPTION_SITE = 'multilingualpress_module_redirect';
    public const OPTION_SITE_ENABLE_REDIRECT = 'option_site_enable_redirect';
    public const OPTION_SITE_ENABLE_REDIRECT_FALLBACK = 'option_site_enable_redirect_fallback';

    public const MODULE_SETTINGS = 'multilingualpress_module_redirect_settings';
    public const MODULE_SETTING_FALLBACK_REDIRECT_SITE_ID = 'fallback_site_id';
    public const MODULE_SETTING_FALLBACK_REDIRECT_EXTERNAL_SITE_ID = 'fallback_external_site_id';
    public const MODULE_SETTING_EXECUTION_TYPE = 'execution_type';
    public const MODULE_SETTING_REDIRECT_TYPE = 'redirect_type';

    /**
     * @inheritdoc
     * phpcs:disable Inpsyde.CodeQuality.ReturnTypeDeclaration
     */
    public function redirectSiteSetting(int $siteId, string $settingName)
    {
        // phpcs:enable

        $allRedirectSiteSettings = get_blog_option($siteId, self::OPTION_SITE);

        if (!$allRedirectSiteSettings) {
            return '';
        }

        if ($settingName === self::OPTION_SITE_ENABLE_REDIRECT || $settingName === self::OPTION_SITE_ENABLE_REDIRECT_FALLBACK) {
            return in_array($settingName, $allRedirectSiteSettings, true);
        }

        return $allRedirectSiteSettings[$settingName] ?? '';
    }

    /**
     * @inheritdoc
     * phpcs:disable Inpsyde.CodeQuality.ReturnTypeDeclaration
     */
    public function redirectUserSetting(int $userId, string $settingName)
    {
        // phpcs:enable

        return get_user_meta($userId, $settingName, true);
    }

    /**
     * @inheritdoc
     */
    public function allSettingValues(): array
    {
        return (array)get_network_option(0, self::MODULE_SETTINGS, []) ?: [];
    }

    /**
     * @inheritdoc
     * phpcs:disable Inpsyde.CodeQuality.ReturnTypeDeclaration
     */
    public function settingValue(string $settingName)
    {
        // phpcs:enable

        $allSettings = $this->allSettingValues();

        return $allSettings[$settingName] ?? '';
    }

    /**
     * @inheritdoc
     */
    public function updateSettings(array $settingsMap): void
    {
        update_network_option(0, self::MODULE_SETTINGS, $settingsMap);
    }
}
