<?php
/**
 * Agency white-label branding for WP PowerSuite admin and plugins list.
 *
 * Central source for all plugin branding values. Other code should use the
 * public getters here rather than hardcoding vendor names or URLs.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class WhiteLabel {

	public const WHITE_LABEL_PAGE_SLUG = 'powersuite-white-label';

	public const LICENSE_PAGE_SLUG = 'powersuite-license';

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

	public static function init(): void {
		add_filter( 'all_plugins', [ self::class, 'filterAllPlugins' ], 20 );
		add_filter( 'plugin_row_meta', [ self::class, 'filterPluginRowMeta' ], 20, 2 );

		if ( defined( 'WP_POWERSUITE_PLUGIN_BASENAME' ) ) {
			add_filter( 'plugin_action_links_' . WP_POWERSUITE_PLUGIN_BASENAME, [ self::class, 'filterPluginActionLinks' ], 20 );
			add_filter( 'network_admin_plugin_action_links_' . WP_POWERSUITE_PLUGIN_BASENAME, [ self::class, 'filterPluginActionLinks' ], 20 );
		}

		add_filter( 'wp_powersuite_brand_icon_url', [ self::class, 'filterBrandIconUrl' ], 20 );
		add_filter( 'wp_powersuite_admin_menu_icon', [ self::class, 'filterAdminMenuIcon' ], 20 );
		add_filter( 'wp_powersuite_modules_hero_icon_url', [ self::class, 'filterHeroIconUrl' ], 20 );
		add_filter( 'wp_powersuite_product_url', [ self::class, 'filterProductUrl' ], 20 );
		add_filter( 'wp_powersuite_renew_url', [ self::class, 'filterRenewUrl' ], 20 );
		add_filter( 'wp_powersuite_support_url', [ self::class, 'filterSupportUrl' ], 20 );
		add_filter( 'wp_powersuite_docs_url', [ self::class, 'filterDocsUrl' ], 20 );
		add_action( 'wp_powersuite_white_label_saved', [ '\WP_PowerSuite\Email\EmailRenderer', 'bustBrandingCache' ] );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function defaultSettings(): array {
		return [
			'enabled'                   => false,
			'plugin_name'                 => '',
			'plugin_short_name'           => '',
			'plugin_description'          => '',
			'plugin_author'               => '',
			'plugin_author_uri'           => '',
			'company_name'                => '',
			'menu_title'                  => '',
			'dashboard_title'             => '',
			'website_url'                 => '',
			'support_url'                 => '',
			'documentation_url'           => '',
			'logo_attachment_id'          => 0,
			'menu_icon_attachment_id'     => 0,
			'email_sender_name'           => '',
			'email_footer_text'           => '',
			'hide_powered_by'             => true,
			'hide_license_menu'           => true,
			'hide_white_label_settings'   => false,
			'hide_external_links'         => true,
		];
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function getSettings(): array {
		if ( self::$settings_cache !== null ) {
			return self::$settings_cache;
		}

		$stored = OptionStore::getInstance()->get( 'white_label', [] );
		if ( ! is_array( $stored ) ) {
			$stored = [];
		}

		self::$settings_cache = self::sanitizeSettings( array_merge( self::defaultSettings(), $stored ) );

		return self::$settings_cache;
	}

	public static function clearCache(): void {
		self::$settings_cache = null;
	}

	/**
	 * @param array<string, mixed> $settings
	 * @return array<string, mixed>
	 */
	public static function sanitizeSettings( array $settings ): array {
		$defaults = self::defaultSettings();
		$out      = $defaults;

		$out['enabled'] = ! empty( $settings['enabled'] );

		foreach (
			[
				'plugin_name',
				'plugin_short_name',
				'plugin_author',
				'company_name',
				'menu_title',
				'dashboard_title',
				'email_sender_name',
			] as $key
		) {
			$out[ $key ] = sanitize_text_field( (string) ( $settings[ $key ] ?? '' ) );
		}

		$out['plugin_description'] = sanitize_textarea_field( (string) ( $settings['plugin_description'] ?? '' ) );
		$out['email_footer_text']  = sanitize_textarea_field( (string) ( $settings['email_footer_text'] ?? '' ) );

		foreach ( [ 'plugin_author_uri', 'website_url', 'support_url', 'documentation_url' ] as $url_key ) {
			$out[ $url_key ] = esc_url_raw( (string) ( $settings[ $url_key ] ?? '' ) );
		}

		$out['logo_attachment_id']           = max( 0, (int) ( $settings['logo_attachment_id'] ?? 0 ) );
		$out['menu_icon_attachment_id']      = max( 0, (int) ( $settings['menu_icon_attachment_id'] ?? 0 ) );
		$out['hide_powered_by']              = ! empty( $settings['hide_powered_by'] );
		$out['hide_license_menu']            = ! empty( $settings['hide_license_menu'] );
		$out['hide_white_label_settings']    = ! empty( $settings['hide_white_label_settings'] );
		$out['hide_external_links']          = ! empty( $settings['hide_external_links'] );

		$out['logo_attachment_id']      = self::sanitizeAttachmentId( $out['logo_attachment_id'] );
		$out['menu_icon_attachment_id'] = self::sanitizeAttachmentId( $out['menu_icon_attachment_id'] );

		return $out;
	}

	private static function sanitizeAttachmentId( int $attachment_id ): int {
		if ( $attachment_id <= 0 ) {
			return 0;
		}

		if ( get_post_type( $attachment_id ) !== 'attachment' ) {
			return 0;
		}

		return $attachment_id;
	}

	public static function hasAgencyLicense(): bool {
		if ( function_exists( 'wp_powersuite_has_agency_license' ) ) {
			return wp_powersuite_has_agency_license();
		}

		return false;
	}

	public static function isConfigured(): bool {
		return ! empty( self::getSettings()['enabled'] );
	}

	public static function isActive(): bool {
		return self::isConfigured() && self::hasAgencyLicense();
	}

	public static function defaultPluginName(): string {
		return __( 'WP PowerSuite', 'wp-powersuite' );
	}

	public static function defaultPluginShortName(): string {
		return __( 'PowerSuite', 'wp-powersuite' );
	}

	public static function defaultCompanyName(): string {
		return __( 'WP PowerSuite', 'wp-powersuite' );
	}

	public static function defaultPluginDescription(): string {
		return __( 'A modular WordPress plugin system with 150+ modules. Zero runtime cost for disabled modules.', 'wp-powersuite' );
	}

	// -------------------------------------------------------------------------
	// Public branding API (snake_case aliases for module authors).
	// -------------------------------------------------------------------------

	public static function get_plugin_name(): string {
		return self::pluginName();
	}

	public static function get_plugin_short_name(): string {
		return self::pluginShortName();
	}

	public static function get_company_name(): string {
		return self::companyName();
	}

	public static function get_author_name(): string {
		return self::pluginAuthor();
	}

	public static function get_logo_url(): string {
		return self::logoUrl();
	}

	public static function get_icon_url(): string {
		return self::menuIconUrl();
	}

	public static function get_support_url(): string {
		return self::supportUrl();
	}

	public static function get_documentation_url(): string {
		return self::documentationUrl();
	}

	public static function get_menu_label(): string {
		return self::menuTitle();
	}

	/**
	 * @return array{sender_name:string,footer_text:string,logo_url:string,company_name:string}
	 */
	public static function get_email_branding(): array {
		return self::emailBranding();
	}

	public static function is_vendor_branding_hidden(): bool {
		return self::shouldHideExternalLinks();
	}

	public static function pluginName(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginName();
		}

		$name = trim( (string) ( self::getSettings()['plugin_name'] ?? '' ) );

		return $name !== '' ? $name : self::defaultPluginName();
	}

	public static function pluginShortName(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginShortName();
		}

		$short = trim( (string) ( self::getSettings()['plugin_short_name'] ?? '' ) );
		if ( $short !== '' ) {
			return $short;
		}

		$name = trim( (string) ( self::getSettings()['plugin_name'] ?? '' ) );

		return $name !== '' ? $name : self::defaultPluginShortName();
	}

	public static function pluginDescription(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginDescription();
		}

		$description = trim( (string) ( self::getSettings()['plugin_description'] ?? '' ) );

		return $description !== '' ? $description : self::defaultPluginDescription();
	}

	public static function menuTitle(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginName();
		}

		$title = trim( (string) ( self::getSettings()['menu_title'] ?? '' ) );

		return $title !== '' ? $title : self::pluginName();
	}

	public static function dashboardTitle(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginName();
		}

		$title = trim( (string) ( self::getSettings()['dashboard_title'] ?? '' ) );

		return $title !== '' ? $title : self::pluginName();
	}

	public static function companyName(): string {
		if ( ! self::isActive() ) {
			return self::defaultCompanyName();
		}

		$company = trim( (string) ( self::getSettings()['company_name'] ?? '' ) );
		if ( $company !== '' ) {
			return $company;
		}

		$author = self::pluginAuthor();

		return $author !== '' ? $author : self::defaultCompanyName();
	}

	public static function pluginAuthor(): string {
		if ( ! self::isActive() ) {
			return '';
		}

		return trim( (string) ( self::getSettings()['plugin_author'] ?? '' ) );
	}

	public static function pluginAuthorUri(): string {
		if ( ! self::isActive() ) {
			return '';
		}

		$uri = trim( (string) ( self::getSettings()['plugin_author_uri'] ?? '' ) );
		if ( $uri !== '' ) {
			return esc_url_raw( $uri );
		}

		return self::websiteUrl();
	}

	public static function websiteUrl(): string {
		if ( self::isActive() ) {
			$url = trim( (string) ( self::getSettings()['website_url'] ?? '' ) );
			if ( $url !== '' ) {
				return esc_url_raw( $url );
			}
			if ( self::shouldHideExternalLinks() ) {
				return '';
			}
		}

		$default = defined( 'WP_POWERSUITE_PRODUCT_URL' ) ? WP_POWERSUITE_PRODUCT_URL : 'https://wppowersuite.com/';

		return esc_url_raw( (string) apply_filters( 'wp_powersuite_product_url', $default ) );
	}

	public static function supportUrl(): string {
		if ( self::isActive() ) {
			$url = trim( (string) ( self::getSettings()['support_url'] ?? '' ) );
			if ( $url !== '' ) {
				return esc_url_raw( $url );
			}
			if ( self::shouldHideExternalLinks() ) {
				return '';
			}
		}

		$default = defined( 'WP_POWERSUITE_SUPPORT_URL' ) ? WP_POWERSUITE_SUPPORT_URL : 'https://wppowersuite.com/support';

		return esc_url_raw( (string) apply_filters( 'wp_powersuite_support_url', $default ) );
	}

	public static function documentationUrl(): string {
		if ( self::isActive() ) {
			$url = trim( (string) ( self::getSettings()['documentation_url'] ?? '' ) );
			if ( $url !== '' ) {
				return esc_url_raw( $url );
			}
			if ( self::shouldHideExternalLinks() ) {
				return '';
			}
		}

		$default = defined( 'WP_POWERSUITE_DOCS_URL' ) ? WP_POWERSUITE_DOCS_URL : 'https://wppowersuite.com/docs';

		return esc_url_raw( (string) apply_filters( 'wp_powersuite_docs_url', $default ) );
	}

	public static function logoUrl(): string {
		if ( ! self::isActive() ) {
			return '';
		}

		return self::attachmentUrl( (int) ( self::getSettings()['logo_attachment_id'] ?? 0 ) );
	}

	public static function menuIconUrl(): string {
		if ( ! self::isActive() ) {
			return '';
		}

		$url = self::attachmentUrl( (int) ( self::getSettings()['menu_icon_attachment_id'] ?? 0 ) );
		if ( $url !== '' ) {
			return $url;
		}

		return self::logoUrl();
	}

	public static function emailSenderName(): string {
		if ( ! self::isActive() ) {
			return self::defaultPluginName();
		}

		$name = trim( (string) ( self::getSettings()['email_sender_name'] ?? '' ) );

		return $name !== '' ? $name : self::companyName();
	}

	public static function emailFooterText(): string {
		if ( ! self::isActive() ) {
			return '';
		}

		return trim( (string) ( self::getSettings()['email_footer_text'] ?? '' ) );
	}

	/**
	 * @return array{sender_name:string,footer_text:string,logo_url:string,company_name:string}
	 */
	public static function emailBranding(): array {
		return [
			'sender_name'  => self::emailSenderName(),
			'footer_text'  => self::emailFooterText(),
			'logo_url'     => self::logoUrl(),
			'company_name' => self::companyName(),
		];
	}

	public static function shouldHideLicenseMenu(): bool {
		return self::isActive() && ! empty( self::getSettings()['hide_license_menu'] );
	}

	public static function shouldHideWhiteLabelSettings(): bool {
		return self::isActive() && ! empty( self::getSettings()['hide_white_label_settings'] );
	}

	public static function shouldHideExternalLinks(): bool {
		return self::isActive() && ! empty( self::getSettings()['hide_external_links'] );
	}

	public static function shouldHidePoweredBy(): bool {
		return self::isActive() && ! empty( self::getSettings()['hide_powered_by'] );
	}

	public static function canAccessHiddenPages(): bool {
		return NetworkScope::canManagePlugin();
	}

	public static function directAccessUrl( string $page_slug ): string {
		return NetworkScope::adminUrl(
			'admin.php',
			[ 'page' => sanitize_key( $page_slug ) ]
		);
	}

	public static function whiteLabelDirectUrl(): string {
		return self::directAccessUrl( self::WHITE_LABEL_PAGE_SLUG );
	}

	public static function licenseDirectUrl(): string {
		return self::directAccessUrl( self::LICENSE_PAGE_SLUG );
	}

	public static function isWhiteLabelPage( string $page_slug ): bool {
		return sanitize_key( $page_slug ) === self::WHITE_LABEL_PAGE_SLUG;
	}

	public static function isLicensePage( string $page_slug ): bool {
		return sanitize_key( $page_slug ) === self::LICENSE_PAGE_SLUG;
	}

	/**
	 * Branded sprintf helper for translatable strings containing the plugin name.
	 */
	public static function branded( string $template ): string {
		return sprintf( $template, self::pluginName() );
	}

	/**
	 * @param array<string, array<string, mixed>> $plugins
	 * @return array<string, array<string, mixed>>
	 */
	public static function filterAllPlugins( array $plugins ): array {
		if ( ! self::isActive() || ! defined( 'WP_POWERSUITE_PLUGIN_BASENAME' ) ) {
			return $plugins;
		}

		$basename = WP_POWERSUITE_PLUGIN_BASENAME;
		if ( ! isset( $plugins[ $basename ] ) || ! is_array( $plugins[ $basename ] ) ) {
			return $plugins;
		}

		$name = trim( (string) ( self::getSettings()['plugin_name'] ?? '' ) );
		if ( $name !== '' ) {
			$plugins[ $basename ]['Name'] = $name;
		}

		$description = trim( (string) ( self::getSettings()['plugin_description'] ?? '' ) );
		if ( $description !== '' ) {
			$plugins[ $basename ]['Description'] = $description;
		}

		$author = self::pluginAuthor();
		if ( $author !== '' ) {
			$author_uri = self::pluginAuthorUri();
			$plugins[ $basename ]['Author']     = $author;
			$plugins[ $basename ]['AuthorName'] = $author;
			$plugins[ $basename ]['AuthorURI']  = $author_uri;
		}

		if ( self::shouldHideExternalLinks() ) {
			unset( $plugins[ $basename ]['PluginURI'] );
		}

		return $plugins;
	}

	/**
	 * @param array<int, string> $links
	 * @return array<int, string>
	 */
	public static function filterPluginRowMeta( array $links, string $plugin_file ): array {
		if ( ! self::isActive() || ! self::shouldHideExternalLinks() ) {
			return $links;
		}

		if ( ! defined( 'WP_POWERSUITE_PLUGIN_BASENAME' ) || $plugin_file !== WP_POWERSUITE_PLUGIN_BASENAME ) {
			return $links;
		}

		return array_values(
			array_filter(
				$links,
				static function ( string $link ): bool {
					return ! preg_match( '/wppowersuite\.com|WP PowerSuite/i', $link );
				}
			)
		);
	}

	/**
	 * @param array<int|string, string> $links
	 * @return array<int|string, string>
	 */
	public static function filterPluginActionLinks( array $links ): array {
		$settings_url = NetworkScope::adminUrl( 'admin.php', [ 'page' => 'powersuite-settings' ] );
		$links['settings'] = '<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Settings', 'wp-powersuite' ) . '</a>';

		if ( self::shouldHideExternalLinks() ) {
			unset( $links['docs'], $links['support'] );
			return $links;
		}

		$docs_url = self::documentationUrl();
		if ( $docs_url !== '' ) {
			$links['docs'] = '<a href="' . esc_url( $docs_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Docs', 'wp-powersuite' ) . '</a>';
		} else {
			unset( $links['docs'] );
		}

		$support_url = self::supportUrl();
		if ( $support_url !== '' ) {
			$links['support'] = '<a href="' . esc_url( $support_url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Support', 'wp-powersuite' ) . '</a>';
		} else {
			unset( $links['support'] );
		}

		return $links;
	}

	public static function filterBrandIconUrl( string $default ): string {
		if ( ! self::isActive() ) {
			return $default;
		}

		$url = self::logoUrl();

		return $url !== '' ? $url : $default;
	}

	/**
	 * @param string|null $icon
	 * @return string|null
	 */
	public static function filterAdminMenuIcon( $icon ) {
		if ( $icon !== null && $icon !== '' ) {
			return $icon;
		}

		if ( ! self::isActive() ) {
			return $icon;
		}

		$url = self::menuIconUrl();

		return $url !== '' ? $url : $icon;
	}

	public static function filterHeroIconUrl( string $default ): string {
		return self::filterBrandIconUrl( $default );
	}

	public static function filterProductUrl( string $url ): string {
		if ( self::isActive() ) {
			$custom = trim( (string) ( self::getSettings()['website_url'] ?? '' ) );
			if ( $custom !== '' ) {
				return esc_url_raw( $custom );
			}
		}

		if ( self::shouldHideExternalLinks() ) {
			return '';
		}

		return $url;
	}

	public static function filterRenewUrl( string $url ): string {
		if ( self::shouldHideExternalLinks() ) {
			return '';
		}

		return $url;
	}

	public static function filterSupportUrl( string $url ): string {
		if ( self::isActive() ) {
			$custom = trim( (string) ( self::getSettings()['support_url'] ?? '' ) );
			if ( $custom !== '' ) {
				return esc_url_raw( $custom );
			}
		}

		if ( self::shouldHideExternalLinks() ) {
			return '';
		}

		return $url;
	}

	public static function filterDocsUrl( string $url ): string {
		if ( self::isActive() ) {
			$custom = trim( (string) ( self::getSettings()['documentation_url'] ?? '' ) );
			if ( $custom !== '' ) {
				return esc_url_raw( $custom );
			}
		}

		if ( self::shouldHideExternalLinks() ) {
			return '';
		}

		return $url;
	}

	private static function attachmentUrl( int $attachment_id ): string {
		if ( $attachment_id <= 0 ) {
			return '';
		}

		$url = wp_get_attachment_url( $attachment_id );

		return is_string( $url ) ? $url : '';
	}
}
