<?php

namespace WPSN\Admin;

defined('ABSPATH') || exit;

/**
 * NetworkSettingsRepository
 *
 * Stores network-level policy settings for multisite installs.
 *
 * Option name: wpsn_network_settings (site option)
 */
final class NetworkSettingsRepository
{
    public const OPTION_NAME = 'wpsn_network_settings';

    /**
     * @return array<string,mixed>
     */
    public function getAll(): array
    {
        $value = [];
        if (is_multisite()) {
            $value = get_site_option(self::OPTION_NAME);
        }

        if (!is_array($value)) {
            $value = [];
        }

        return array_replace_recursive($this->defaults(), $value);
    }

    /**
     * @param array<string,mixed> $settings
     */
    public function update(array $settings): void
    {
        if (!is_multisite()) {
            return;
        }
        $settings = $this->sanitize($settings);
        update_site_option(self::OPTION_NAME, $settings);
    }

    /**
     * @param array<string,mixed> $input
     * @return array<string,mixed>
     */
    public function sanitize(array $input): array
    {
        $out = $this->defaults();

        $out['enabled'] = !empty($input['enabled']);

        // Enforce groups.
        if (isset($input['enforce']) && is_array($input['enforce'])) {
            foreach (['modules', 'white_label', 'integrations'] as $group) {
                $out['enforce'][$group] = !empty($input['enforce'][$group]);
            }
        }

        // Settings payload per group.
        if (isset($input['settings']) && is_array($input['settings'])) {
            $s = $input['settings'];

            if (isset($s['modules']) && is_array($s['modules'])) {
                $out['settings']['modules'] = [];
                foreach ($s['modules'] as $moduleId => $enabled) {
                    $moduleId = sanitize_key((string) $moduleId);
                    if ($moduleId === '') {
                        continue;
                    }
                    $out['settings']['modules'][$moduleId] = (bool) $enabled;
                }
            }

            if (isset($s['white_label']) && is_array($s['white_label'])) {
                $wl = $s['white_label'];
                $out['settings']['white_label']['enabled'] = !empty($wl['enabled']);
                $out['settings']['white_label']['hide_branding'] = !empty($wl['hide_branding']);

                $out['settings']['white_label']['brand_name'] = isset($wl['brand_name'])
                    ? sanitize_text_field((string) $wl['brand_name'])
                    : $out['settings']['white_label']['brand_name'];

                $out['settings']['white_label']['menu_title'] = isset($wl['menu_title'])
                    ? sanitize_text_field((string) $wl['menu_title'])
                    : $out['settings']['white_label']['menu_title'];

                $out['settings']['white_label']['settings_heading'] = isset($wl['settings_heading'])
                    ? sanitize_text_field((string) $wl['settings_heading'])
                    : $out['settings']['white_label']['settings_heading'];
            }

            if (isset($s['integrations']) && is_array($s['integrations'])) {
                $in = $s['integrations'];

                if (isset($in['elementor']) && is_array($in['elementor'])) {
                    $out['settings']['integrations']['elementor']['enabled'] = !empty($in['elementor']['enabled']);
                    $out['settings']['integrations']['elementor']['editor_controls'] = !empty($in['elementor']['editor_controls']);
                }

                if (isset($in['custom_fields']) && is_array($in['custom_fields'])) {
                    $out['settings']['integrations']['custom_fields']['enabled'] = !empty($in['custom_fields']['enabled']);
                    $out['settings']['integrations']['custom_fields']['include_in_analysis'] = !empty($in['custom_fields']['include_in_analysis']);

                    $keys = isset($in['custom_fields']['analysis_keys']) ? sanitize_textarea_field((string) $in['custom_fields']['analysis_keys']) : '';
                    $out['settings']['integrations']['custom_fields']['analysis_keys'] = trim($keys);

                    $max = isset($in['custom_fields']['max_value_chars']) ? (int) $in['custom_fields']['max_value_chars'] : (int) $out['settings']['integrations']['custom_fields']['max_value_chars'];
                    if ($max < 50) {
                        $max = 50;
                    }
                    if ($max > 5000) {
                        $max = 5000;
                    }
                    $out['settings']['integrations']['custom_fields']['max_value_chars'] = $max;
                }
            }
        }

        return $out;
    }

    /**
     * @return array<string,mixed>
     */
    public function defaults(): array
    {
        return [
            'enabled' => false,
            'enforce' => [
                'modules' => false,
                'white_label' => false,
                'integrations' => false,
            ],
            'settings' => [
                'modules' => [],
                'white_label' => [
                    'enabled' => false,
                    'brand_name' => 'WP SEO Next',
                    'menu_title' => '',
                    'settings_heading' => '',
                    'hide_branding' => false,
                ],
                'integrations' => [
                    'elementor' => [
                        'enabled' => true,
                        'editor_controls' => true,
                    ],
                    'custom_fields' => [
                        'enabled' => true,
                        'include_in_analysis' => false,
                        'analysis_keys' => '',
                        'max_value_chars' => 500,
                    ],
                ],
            ],
        ];
    }
}
