<?php

namespace NeurogenesisTheme\Helpers;

defined( 'ABSPATH' ) || exit;

/**
 * Dashboard resource links declared in theme/config/dashboard-resources.php.
 */
final class DashboardResources {

	/**
	 * @return array<int, array{id:string,icon:string,title:string,description:string,url:string,disabled:bool}>
	 */
	public static function all(): array {
		$resources = array();

		foreach ( self::load_config() as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}

			if ( array_key_exists( 'enabled', $item ) && ! $item['enabled'] ) {
				continue;
			}

			$resources[] = self::normalize( $item );
		}

		/**
		 * Filter dashboard resource links after config is loaded.
		 *
		 * @param array<int, array{id:string,icon:string,title:string,description:string,url:string,disabled:bool}> $resources
		 */
		return (array) apply_filters( 'neurogenesis_theme_dashboard_resources', $resources );
	}

	/**
	 * @return list<array<string, mixed>>
	 */
	private static function load_config(): array {
		$path = NEUROGENESIS_THEME_THEME_PATH . '/config/dashboard-resources.php';

		if ( ! is_readable( $path ) ) {
			return array();
		}

		$config = require $path;

		return is_array( $config ) ? $config : array();
	}

	/**
	 * @param array<string, mixed> $item
	 * @return array{id:string,icon:string,title:string,description:string,url:string,disabled:bool}
	 */
	private static function normalize( array $item ): array {
		return array(
			'id'          => sanitize_key( (string) ( $item['id'] ?? '' ) ),
			'icon'        => sanitize_key( (string) ( $item['icon'] ?? '' ) ),
			'title'       => (string) ( $item['title'] ?? '' ),
			'description' => (string) ( $item['description'] ?? '' ),
			'url'         => self::resolve_url( (string) ( $item['url'] ?? '' ) ),
			'disabled'    => ! empty( $item['disabled'] ),
		);
	}

	private static function resolve_url( string $url ): string {
		$replacements = array(
			'{{theme_uri}}'        => self::theme_uri(),
			'{{support_url}}'      => self::support_url(),
			'{{wp_org_theme_url}}' => self::wp_org_theme_url(),
		);

		return str_replace( array_keys( $replacements ), array_values( $replacements ), $url );
	}

	private static function theme_uri(): string {
		$theme_uri = (string) get_theme_mod( 'external_theme_uri', get_stylesheet_directory_uri() );

		if ( function_exists( 'wp_get_theme' ) ) {
			$theme = wp_get_theme();
			if ( $theme->exists() && $theme->get( 'ThemeURI' ) ) {
				$theme_uri = (string) $theme->get( 'ThemeURI' );
			}
		}

		return $theme_uri;
	}

	private static function support_url(): string {
		return sprintf(
			'https://wordpress.org/support/theme/%s/',
			rawurlencode( sanitize_key( get_stylesheet() ) )
		);
	}

	private static function wp_org_theme_url(): string {
		return sprintf(
			'https://wordpress.org/themes/%s/',
			rawurlencode( sanitize_key( get_stylesheet() ) )
		);
	}
}
