<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

/**
 * Handles configuration related to menu behaviors (e.g., new tab URL list).
 */
class MenuConfigService
{
    /**
     * Get configured URLs that should always open in a new tab.
     */
    public function getNewTabUrls(): array
    {
        $option = \get_option(MenuItemFormatter::NEW_TAB_URLS_OPTION, null);

        if ($option === null) {
            return $this->getDefaultNewTabUrls();
        }

        return array_values(array_filter(array_map('trim', (array) $option)));
    }

    /**
     * Persist custom new tab URL list.
     */
    public function updateNewTabUrls(array $urls): array
    {
        $sanitized = array_values(array_filter(array_map(static function ($url) {
            return \sanitize_text_field(trim((string) $url));
        }, $urls)));

        \update_option(MenuItemFormatter::NEW_TAB_URLS_OPTION, $sanitized, false);

        return $sanitized;
    }

    /**
     * Reset new tab URL configuration to defaults.
     */
    public function resetNewTabUrls(): array
    {
        \delete_option(MenuItemFormatter::NEW_TAB_URLS_OPTION);
        return $this->getDefaultNewTabUrls();
    }

    /**
     * Defaults come from MenuItemFormatter for backwards compatibility.
     */
    public function getDefaultNewTabUrls(): array
    {
        $formatter = new MenuItemFormatter(new RouteConverter());
        return $formatter->getDefaultNewTabUrls();
    }
}
