<?php
/**
 * Settings repository facade.
 *
 * @package BatoCookieConsent
 */

if (! defined('ABSPATH')) {
    exit;
}

final class Bato_Cookie_Consent_Settings
{
    public const OPTION_NAME = 'bato_cookie_consent_settings';

    private Bato_Cookie_Consent_Settings_Sanitizer $sanitizer;
    private Bato_Cookie_Consent_Settings_Metadata $metadata;
    private Bato_Cookie_Consent_Settings_Frontend_Config $frontend_config;

    public function __construct()
    {
        $this->sanitizer = new Bato_Cookie_Consent_Settings_Sanitizer();
        $this->metadata = new Bato_Cookie_Consent_Settings_Metadata();
        $this->frontend_config = new Bato_Cookie_Consent_Settings_Frontend_Config($this->metadata);
    }

    public static function install_defaults(): void
    {
        if (false === get_option(self::OPTION_NAME, false)) {
            add_option(self::OPTION_NAME, self::defaults(), '', false);
        }
    }

    public static function supported_languages(): array
    {
        return Bato_Cookie_Consent_Settings_Languages::supported();
    }

    public static function normalize_locale(string $locale): string
    {
        return Bato_Cookie_Consent_Settings_Languages::normalize_locale($locale);
    }

    public static function default_language(): string
    {
        return Bato_Cookie_Consent_Settings_Languages::default_language();
    }

    public static function defaults(): array
    {
        return Bato_Cookie_Consent_Settings_Defaults::defaults();
    }

    public static function default_content(): array
    {
        return Bato_Cookie_Consent_Settings_Defaults::content();
    }

    public function get(): array
    {
        $saved = get_option(self::OPTION_NAME, array());

        return $this->sanitizer->merge_defaults(is_array($saved) ? $saved : array());
    }

    public function save(array $input): array
    {
        $settings = $this->sanitize($input);
        $settings['updated_at'] = gmdate('c');

        update_option(self::OPTION_NAME, $settings, false);

        return $settings;
    }

    public function sanitize(array $input): array
    {
        return $this->sanitizer->sanitize($input);
    }

    public function frontend_config(): array
    {
        return $this->frontend_config->build($this->get());
    }

    public function resolve_logo_url(array $settings): string
    {
        return $this->metadata->resolve_logo_url($settings);
    }

    public function metadata(): array
    {
        return $this->metadata->metadata($this->get());
    }
}
