<?php

namespace NewsletterBridge\Config;

/**
 * Configurazione campi "In evidenza newsletter" / "Oggetto newsletter" per post type.
 */
class FeaturedConfig {

    public const OPTION_POST_TYPES = 'newsletter_featured_post_types';

    public const META_IN_EVIDENZA = 'in_evidenza_newsletter';
    public const META_SUBJECT = 'newsletter_subject';

    /**
     * Post type abilitati (default: post).
     *
     * @return string[]
     */
    public static function getEnabledPostTypes(): array {
        $is_multisite = function_exists('is_multisite') && is_multisite();
        $raw = self::get_option_safe(self::OPTION_POST_TYPES, '["post"]', $is_multisite);

        if (is_string($raw)) {
            $decoded = json_decode($raw, true);
        } elseif (is_array($raw)) {
            $decoded = $raw;
        } else {
            $decoded = ['post'];
        }

        if (!is_array($decoded)) {
            return ['post'];
        }

        $types = array_values(array_filter(array_map('sanitize_key', $decoded)));
        return $types !== [] ? $types : ['post'];
    }

    /**
     * @param string[] $post_types
     */
    public static function saveEnabledPostTypes(array $post_types): void {
        $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;
        }

        $public = array_keys(get_post_types(['public' => true], 'names'));
        $valid = array_values(array_intersect($post_types, $public));

        if ($valid === []) {
            $valid = ['post'];
        }

        self::update_option_safe(self::OPTION_POST_TYPES, wp_json_encode($valid), $is_network);
    }

    private static function get_option_safe(string $option_name, $default, bool $is_multisite) {
        if ($is_multisite) {
            $sentinel = [];
            $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(string $option_name, $value, bool $is_network = false): void {
        if ($is_network && function_exists('update_site_option')) {
            update_site_option($option_name, $value);
            return;
        }
        update_option($option_name, $value);
    }
}
