<?php

namespace WPSN\Core;

use WPSN\Admin\NetworkSettingsRepository;

defined('ABSPATH') || exit;

/**
 * NetworkSettings
 *
 * A small helper around NetworkSettingsRepository to apply network-level
 * policies to per-site settings in multisite installations.
 */
final class NetworkSettings
{
    private NetworkSettingsRepository $repo;

    /** @var array<string,mixed>|null */
    private ?array $cache = null;

    public function __construct(NetworkSettingsRepository $repo)
    {
        $this->repo = $repo;
    }

    /**
     * @return array<string,mixed>
     */
    public function all(): array
    {
        if ($this->cache === null) {
            $this->cache = $this->repo->getAll();
        }
        return $this->cache;
    }

    public function flush(): void
    {
        $this->cache = null;
    }

    public function isEnabled(): bool
    {
        if (!is_multisite()) {
            return false;
        }
        return (bool) ($this->all()['enabled'] ?? false);
    }

    public function isEnforced(string $group): bool
    {
        $group = (string) $group;
        if (!$this->isEnabled()) {
            return false;
        }
        $enforce = $this->all()['enforce'] ?? [];
        return is_array($enforce) && !empty($enforce[$group]);
    }

    /**
     * Apply network enforced groups to the given site settings.
     *
     * @param array<string,mixed> $siteSettings
     * @return array<string,mixed>
     */
    public function applyToSiteSettings(array $siteSettings): array
    {
        if (!$this->isEnabled()) {
            return $siteSettings;
        }

        $all = $this->all();
        $settings = isset($all['settings']) && is_array($all['settings']) ? $all['settings'] : [];

        // Enforced groups are overlaid onto the site settings.
        foreach (['modules', 'white_label', 'integrations'] as $group) {
            if (!$this->isEnforced($group)) {
                continue;
            }
            if (!isset($settings[$group]) || !is_array($settings[$group])) {
                continue;
            }
            $siteSettings[$group] = array_replace_recursive(
                isset($siteSettings[$group]) && is_array($siteSettings[$group]) ? $siteSettings[$group] : [],
                $settings[$group]
            );
        }

        return $siteSettings;
    }
}
