<?php
/**
 * Plugin Action Links Resolver - Collects Settings/Configure links from plugin filters.
 *
 * @package FleekDash\Controllers\Plugins
 * @since 2.2.0
 */

namespace FleekDash\Controllers\Plugins;

/**
 * Resolves plugin action links (Settings, Configure, etc.) via WordPress filters.
 */
class PluginActionLinksResolver
{
    /** @var array<string, array> */
    private static $cache = [];

    /**
     * Get plugin action links (Settings, etc.) for a plugin.
     *
     * @param string $plugin_file Plugin file path (e.g. "plugin-name/plugin-name.php")
     * @param array $plugin_data Plugin data from get_plugins()
     * @return array<string, array{url: string, text: string, html?: string}>
     */
    public function getActionLinks(string $plugin_file, array $plugin_data): array
    {
        if (isset(self::$cache[$plugin_file])) {
            return self::$cache[$plugin_file];
        }

        try {
            $action_links = \apply_filters('plugin_action_links', [], $plugin_file, $plugin_data, 'all');
            $action_links = \apply_filters('plugin_action_links_' . $plugin_file, $action_links, $plugin_file);
            $parsed = $this->parseActionLinks($action_links);
            self::$cache[$plugin_file] = $parsed;
            return $parsed;
        } catch (\Throwable $e) {
            self::$cache[$plugin_file] = [];
            return [];
        }
    }

    /**
     * Parse action links (HTML strings or arrays) into structured format.
     *
     * @param mixed $action_links
     * @return array<string, array{url: string, text: string, html?: string}>
     */
    private function parseActionLinks($action_links): array
    {
        $parsed = [];
        if (!is_array($action_links)) {
            return $parsed;
        }
        foreach ($action_links as $key => $link_html) {
            $entry = $this->parseSingleLink($key, $link_html);
            if ($entry !== null) {
                $parsed[$entry['key']] = $entry['data'];
            }
        }
        return $parsed;
    }

    /**
     * @return array{key: string|int, data: array}|null
     */
    private function parseSingleLink($key, $link_html): ?array
    {
        if (is_array($link_html)) {
            return ['key' => $key, 'data' => $link_html];
        }
        if (!is_string($link_html) || !preg_match('/<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>([^<]+)<\/a>/i', $link_html, $m)) {
            return null;
        }
        $text = trim(strip_tags($m[2]));
        $link_key = is_numeric($key) ? strtolower(str_replace(' ', '_', $text)) : $key;
        return [
            'key' => $link_key,
            'data' => ['url' => $m[1], 'text' => $text, 'html' => $link_html],
        ];
    }
}
