<?php

namespace NewsletterBridge\Config;

use NewsletterBridge\Services\ImgCDN\CDNFactory;

class CdnConfig
{
    public static function getConfig($site_id = null)
    {
        $is_multisite = function_exists('is_multisite') && is_multisite();

        $provider = self::get_option_safe('IMG_CDN_PROVIDER', CDNFactory::LOCAL, $is_multisite, $site_id);

        return (object) [
            'provider' => $provider ?: CDNFactory::LOCAL,
            'default_format' => self::get_option_safe('IMG_CDN_DEFAULT_FORMAT', 'webp', $is_multisite, $site_id),
            'default_width' => (int) self::get_option_safe('IMG_CDN_DEFAULT_WIDTH', 1200, $is_multisite, $site_id),
            'default_height' => (int) self::get_option_safe('IMG_CDN_DEFAULT_HEIGHT', 675, $is_multisite, $site_id),
            'default_quality' => (int) self::get_option_safe('IMG_CDN_DEFAULT_QUALITY', 85, $is_multisite, $site_id),
            'resize_mode' => self::get_option_safe('IMG_CDN_RESIZE_MODE', 'fill', $is_multisite, $site_id),
            'imgProxy' => (object) [
                'url' => self::get_option_safe('IMG_CDN_IMGPROXY_URL', '', $is_multisite, $site_id),
                'key' => self::get_option_safe('IMG_CDN_IMGPROXY_KEY', '', $is_multisite, $site_id),
                'salt' => self::get_option_safe('IMG_CDN_IMGPROXY_SALT', '', $is_multisite, $site_id),
            ],
            'thumbor' => (object) [
                'url' => self::get_option_safe('IMG_CDN_THUMBOR_URL', '', $is_multisite, $site_id),
                'key' => self::get_option_safe('IMG_CDN_THUMBOR_KEY', '', $is_multisite, $site_id),
            ],
        ];
    }

    public static function saveConfig(array $data): void
    {
        $allowedProviders = [
            CDNFactory::LOCAL,
            CDNFactory::IMG_PROXY_PLAIN,
            CDNFactory::IMG_PROXY_ENC,
            CDNFactory::THUMBOR,
        ];

        $provider = in_array($data['IMG_CDN_PROVIDER'] ?? '', $allowedProviders, true)
            ? $data['IMG_CDN_PROVIDER']
            : CDNFactory::LOCAL;

        $fields = [
            'IMG_CDN_PROVIDER' => $provider,
            'IMG_CDN_DEFAULT_FORMAT' => sanitize_text_field($data['IMG_CDN_DEFAULT_FORMAT'] ?? 'webp'),
            'IMG_CDN_RESIZE_MODE' => sanitize_text_field($data['IMG_CDN_RESIZE_MODE'] ?? 'fill'),
            'IMG_CDN_IMGPROXY_URL' => esc_url_raw($data['IMG_CDN_IMGPROXY_URL'] ?? ''),
            'IMG_CDN_IMGPROXY_KEY' => sanitize_text_field($data['IMG_CDN_IMGPROXY_KEY'] ?? ''),
            'IMG_CDN_IMGPROXY_SALT' => sanitize_text_field($data['IMG_CDN_IMGPROXY_SALT'] ?? ''),
            'IMG_CDN_THUMBOR_URL' => esc_url_raw($data['IMG_CDN_THUMBOR_URL'] ?? ''),
            'IMG_CDN_THUMBOR_KEY' => sanitize_text_field($data['IMG_CDN_THUMBOR_KEY'] ?? ''),
        ];

        $intFields = [
            'IMG_CDN_DEFAULT_WIDTH' => isset($data['IMG_CDN_DEFAULT_WIDTH']) ? absint($data['IMG_CDN_DEFAULT_WIDTH']) : 1200,
            'IMG_CDN_DEFAULT_HEIGHT' => isset($data['IMG_CDN_DEFAULT_HEIGHT']) ? absint($data['IMG_CDN_DEFAULT_HEIGHT']) : 675,
            'IMG_CDN_DEFAULT_QUALITY' => isset($data['IMG_CDN_DEFAULT_QUALITY']) ? absint($data['IMG_CDN_DEFAULT_QUALITY']) : 85,
        ];

        $is_multisite = function_exists('is_multisite') && is_multisite();
        $is_network_admin = function_exists('is_network_admin') && is_network_admin();
        $is_network = $is_multisite && $is_network_admin;

        if ($is_multisite && !$is_network_admin) {
            $is_network = false;
        }

        foreach ($fields as $option => $value) {
            self::update_option_safe($option, $value, $is_network);
        }

        foreach ($intFields as $option => $value) {
            self::update_option_safe($option, $value, $is_network);
        }
    }

    private static function get_option_safe($option_name, $default = false, $is_multisite = false, $site_id = null)
    {
        if ($is_multisite) {
            $sentinel = [];

            if ($site_id !== null && function_exists('get_blog_option')) {
                $site_value = get_blog_option($site_id, $option_name, $sentinel);
                if ($site_value !== $sentinel) {
                    return $site_value;
                }

                if (function_exists('get_site_option')) {
                    $network_value = get_site_option($option_name, $sentinel);
                    if ($network_value !== $sentinel) {
                        return $network_value;
                    }
                }

                return $default;
            }

            $site_value = get_option($option_name, $sentinel);
            if ($site_value !== $sentinel) {
                return $site_value;
            }

            if (function_exists('get_site_option')) {
                $network_value = get_site_option($option_name, $sentinel);
                if ($network_value !== $sentinel) {
                    return $network_value;
                }
            }

            return $default;
        }

        return get_option($option_name, $default);
    }

    private static function update_option_safe($option_name, $value, $is_network = false)
    {
        if ($is_network && function_exists('update_site_option')) {
            return update_site_option($option_name, $value);
        }

        return update_option($option_name, $value);
    }
}

