<?php
/**
 * Volade Discover — Grille de découverte des plugins Volade
 *
 * @package Volade\SDK
 * @license GPL-2.0-or-later
 */

trait Volade_Discover {

	private static $category_labels = array(
		'forks'        => 'Forks',
		'pepites'      => 'Pépites',
		'wc'           => 'WooCommerce',
		'ai'           => 'AI',
		'devtools'     => 'Devtools',
		'framework'    => 'Framework',
		'sectors'      => 'Secteurs FR',
		'payments'     => 'Paiements',
		'compliance'   => 'Conformité',
		'categories'   => 'Catégories',
		'creator'      => 'Creator',
		'saas'         => 'Intégrations',
		'micro'        => 'Utilitaires',
		'sport'        => 'Sport',
		'agriculture'  => 'Agriculture',
		'finance'      => 'Finance',
		'security'     => 'Sécurité',
		'gaming'       => 'Gaming',
		'health'       => 'Santé',
		'productivity' => 'Productivité',
		'agency'       => 'Agence',
		'media'        => 'Média',
		'tools'        => 'Outils',
		'analytics'    => 'Analytics',
	);

	private static $category_icons = array(
		'forks'        => '🔧',
		'pepites'      => '💎',
		'wc'           => '🛒',
		'ai'           => '🤖',
		'devtools'     => '🛠️',
		'framework'    => '🧱',
		'sectors'      => '🇫🇷',
		'payments'     => '💳',
		'compliance'   => '⚖️',
		'categories'   => '📂',
		'creator'      => '🎨',
		'saas'         => '☁️',
		'micro'        => '✨',
		'sport'        => '⚽',
		'agriculture'  => '🌾',
		'finance'      => '📈',
		'security'     => '🔒',
		'gaming'       => '🎮',
		'health'       => '🏥',
		'productivity' => '📁',
		'agency'       => '🏢',
		'media'        => '🎬',
		'tools'        => '🔩',
		'analytics'    => '📊',
	);

	private static $category_blurbs = array(
		'forks'      => 'Forks maintenus de plugins abandonnés.',
		'pepites'    => 'Outils originaux sans concurrence directe.',
		'wc'         => 'Alternatives WooCommerce premium.',
		'ai'         => 'Intelligence artificielle native WordPress.',
		'devtools'   => 'Pour développeurs et agences.',
		'sectors'    => 'Métiers et secteurs français.',
		'compliance' => 'Conformité légale et réglementaire.',
	);

	public function init_discover() {
		add_shortcode( 'volade_discover', array( $this, 'shortcode_discover' ) );
		add_action( 'wp_ajax_volade_discover_fetch', array( $this, 'ajax_discover_fetch' ) );
	}

	public function get_discover_plugins( $include_planned = true ) {
		$cache_key = 'volade_discover_' . ( $include_planned ? 'all' : 'live' );
		$cached    = get_transient( $cache_key );
		if ( false !== $cached && is_array( $cached ) ) {
			return $cached;
		}

		$plugins = array();
		$api     = Volade_API::get_instance();
		if ( $api ) {
			$remote = $api->get( '/discover/plugins' );
			if ( ! is_wp_error( $remote ) && ! empty( $remote['plugins'] ) ) {
				$plugins = $remote['plugins'];
			}
		}

		if ( empty( $plugins ) ) {
			$plugins = $this->get_local_manifest();
		}

		$plugins = $this->filter_public_catalog( $plugins );

		if ( ! $include_planned ) {
			$plugins = array_values( array_filter( $plugins, array( $this, 'is_plugin_live' ) ) );
		}

		$plugins = array_map( array( $this, 'merge_plugin_description' ), $plugins );

		set_transient( $cache_key, $plugins, 12 * HOUR_IN_SECONDS );
		return $plugins;
	}

	public function is_plugin_live( $plugin ) {
		$status = $plugin['status'] ?? '';
		return in_array( $status, array( 'shipped', 'available', 'beta' ), true );
	}

	public function is_plugin_in_development( $plugin ) {
		$status = $plugin['status'] ?? '';
		return in_array( $status, array( 'development', 'planned' ), true );
	}

	/**
	 * Catalogue public : extension livrée(s) + un seul plugin « en développement ».
	 *
	 * @param array<int, array<string, mixed>> $plugins
	 * @return array<int, array<string, mixed>>
	 */
	private function filter_public_catalog( array $plugins ) {
		$allowed = $this->get_public_catalog_slugs();
		if ( empty( $allowed ) ) {
			return $plugins;
		}

		$by_slug = array();
		foreach ( $plugins as $plugin ) {
			$slug = $plugin['slug'] ?? '';
			if ( $slug && in_array( $slug, $allowed, true ) ) {
				$by_slug[ $slug ] = $plugin;
			}
		}

		$ordered = array();
		foreach ( $allowed as $slug ) {
			if ( isset( $by_slug[ $slug ] ) ) {
				$ordered[] = $by_slug[ $slug ];
			}
		}

		return $ordered;
	}

	/**
	 * @return string[]
	 */
	private function get_public_catalog_slugs() {
		$file = __DIR__ . '/manifest.json';
		if ( ! file_exists( $file ) ) {
			return array();
		}
		$data = json_decode( file_get_contents( $file ), true );
		if ( ! is_array( $data['plugins'] ?? null ) ) {
			return array();
		}
		$slugs = array();
		foreach ( $data['plugins'] as $plugin ) {
			if ( ! empty( $plugin['slug'] ) ) {
				$slugs[] = $plugin['slug'];
			}
		}
		return $slugs;
	}

	private function get_local_manifest() {
		$file = __DIR__ . '/manifest.json';
		if ( ! file_exists( $file ) ) {
			return array();
		}
		$data    = json_decode( file_get_contents( $file ), true );
		$plugins = is_array( $data['plugins'] ?? null ) ? $data['plugins'] : array();

		return array_map( array( $this, 'merge_plugin_description' ), $plugins );
	}

	/**
	 * @return array<string, string>
	 */
	public function get_plugin_descriptions() {
		static $cache = null;
		if ( null !== $cache ) {
			return $cache;
		}
		$file  = __DIR__ . '/data/plugin-descriptions.php';
		$cache = file_exists( $file ) ? include $file : array();
		return is_array( $cache ) ? $cache : array();
	}

	public function get_plugin_description( $slug, $category = 'other' ) {
		if ( 'heartbeat-control-manager-by-volade' === $slug ) {
			return __( 'Controls and manages the WordPress Heartbeat API to reduce admin-ajax load: intervals, per-screen rules, presets, and multisite.', 'core-version-switcher-by-volade' );
		}
		if ( 'php-compatibility-checker-by-volade' === $slug ) {
			return __( 'Scans plugins and themes before a PHP upgrade — local analysis, no Tide API. Modern fork of WP Engine\'s abandoned checker.', 'core-version-switcher-by-volade' );
		}
		$descriptions = $this->get_plugin_descriptions();
		if ( ! empty( $descriptions[ $slug ] ) ) {
			return $descriptions[ $slug ];
		}
		return self::$category_blurbs[ $category ] ?? __( 'Extension Volade pour WordPress.', 'core-version-switcher-by-volade' );
	}

	/**
	 * @param array<string, mixed> $plugin
	 * @return array<string, mixed>
	 */
	public function merge_plugin_description( array $plugin ) {
		$slug = $plugin['slug'] ?? '';
		if ( empty( $plugin['description'] ) && $slug ) {
			$plugin['description'] = $this->get_plugin_description( $slug, $plugin['category'] ?? 'other' );
		}
		return $plugin;
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public function get_manifest_plugin_by_slug( $slug ) {
		foreach ( $this->get_discover_plugins( true ) as $plugin ) {
			if ( ( $plugin['slug'] ?? '' ) === $slug ) {
				return $plugin;
			}
		}
		return null;
	}

	/**
	 * Plugins Volade installés sur ce site, enrichis pour la vue d'ensemble.
	 *
	 * @return array<string, array<string, mixed>>
	 */
	public function get_installed_plugins_hub() {
		$registered = $this->get_registered_plugins();
		$out        = array();

		foreach ( $registered as $slug => $item ) {
			$manifest = $this->get_manifest_plugin_by_slug( $slug );
			$base     = $manifest ?: array(
				'slug'     => $slug,
				'name'     => $item['menu_title'],
				'icon'     => '⚡',
				'category' => 'other',
				'tier'     => 'free',
			);

			$enriched                 = $this->enrich_discover_plugin( $base );
			$enriched['menu_title']   = $item['menu_title'];
			$enriched['page_title']   = $item['page_title'];
			$enriched['settings_url'] = admin_url( 'admin.php?page=' . Volade_SDK::get_plugin_page_slug( $slug ) );

			$out[ $slug ] = $enriched;
		}

		return $out;
	}

	/**
	 * Suggestions catalogue non installées pour la vue d'ensemble.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function get_hub_suggestions( $limit = 4 ) {
		$out = array();
		foreach ( $this->get_discover_catalog() as $plugin ) {
			if ( empty( $plugin['is_live'] ) || ! empty( $plugin['is_installed'] ) ) {
				continue;
			}
			$out[] = $plugin;
			if ( count( $out ) >= $limit ) {
				break;
			}
		}
		return $out;
	}

	/**
	 * @param array<string, array<string, mixed>> $hub_plugins
	 * @return array{installed:int,categories:int}
	 */
	public function get_hub_stats( array $hub_plugins ) {
		$cats = array();
		foreach ( $hub_plugins as $plugin ) {
			$cats[ $plugin['category'] ?? 'other' ] = true;
		}
		return array(
			'installed'  => count( $hub_plugins ),
			'categories' => count( $cats ),
		);
	}

	private function render_plugin_status_badge( $plugin ) {
		if ( $this->is_plugin_live( $plugin ) ) {
			return '<span class="volade-discover-badge volade-discover-badge--live">' . esc_html__( 'Disponible', 'core-version-switcher-by-volade' ) . '</span>';
		}
		if ( $this->is_plugin_in_development( $plugin ) ) {
			return '<span class="volade-discover-badge volade-discover-badge--planned">' . esc_html__( 'En développement', 'core-version-switcher-by-volade' ) . '</span>';
		}
		return '<span class="volade-discover-badge volade-discover-badge--planned">' . esc_html__( 'Bientôt', 'core-version-switcher-by-volade' ) . '</span>';
	}

	public function get_discover_stats() {
		$plugins = $this->get_discover_plugins( true );
		$live    = array_filter( $plugins, array( $this, 'is_plugin_live' ) );
		$cats    = array();
		foreach ( $plugins as $p ) {
			$cats[ $p['category'] ?? 'other' ] = true;
		}

		return array(
			'total'      => count( $plugins ),
			'live'       => count( $live ),
			'planned'    => count( $plugins ) - count( $live ),
			'categories' => count( $cats ),
			'installed'  => count( $this->get_registered_plugins() ),
		);
	}

	/**
	 * @return array<int, array<string, mixed>>
	 */
	public function get_discover_catalog() {
		$plugins    = $this->get_discover_plugins( true );
		$registered = $this->get_registered_plugins();
		$catalog    = array();

		foreach ( $plugins as $plugin ) {
			$catalog[] = $this->enrich_discover_plugin( $plugin, $registered );
		}

		return $catalog;
	}

	/**
	 * @param array<string, mixed> $plugin
	 * @param array<string, mixed> $registered
	 * @return array<string, mixed>
	 */
	public function enrich_discover_plugin( $plugin, $registered = null ) {
		if ( null === $registered ) {
			$registered = $this->get_registered_plugins();
		}

		$slug      = $plugin['slug'] ?? '';
		$category  = $plugin['category'] ?? 'other';
		$live      = $this->is_plugin_live( $plugin );
		$installed = isset( $registered[ $slug ] );
		$tier      = $plugin['tier'] ?? 'free';

		$tier_labels = array(
			'free'     => __( 'Gratuit', 'core-version-switcher-by-volade' ),
			'freemium' => __( 'Freemium', 'core-version-switcher-by-volade' ),
			'premium'  => __( 'Premium', 'core-version-switcher-by-volade' ),
		);

		$blurb = $plugin['description'] ?? '';
		if ( ! $blurb && $slug ) {
			$blurb = $this->get_plugin_description( $slug, $category );
		}

		return array_merge(
			$plugin,
			array(
				'slug'           => $slug,
				'category'       => $category,
				'category_label' => self::$category_labels[ $category ] ?? ucfirst( $category ),
				'category_icon'  => self::$category_icons[ $category ] ?? '📦',
				'is_live'        => $live,
				'is_installed'   => $installed,
				'is_featured'    => $live && ( ! empty( $plugin['priority'] ) || ! empty( $plugin['status'] ) && 'shipped' === $plugin['status'] ),
				'tier_label'     => $tier_labels[ $tier ] ?? ucfirst( $tier ),
				'blurb'          => $blurb,
				'settings_url'   => $installed ? admin_url( 'admin.php?page=' . self::get_plugin_page_slug( $slug ) ) : '',
				'catalog_url'    => function_exists( 'volade_extension_catalog_url' )
					? volade_extension_catalog_url( $slug )
					: $this->volade_public_url( VOLADE_CMS_WP_EXTENSIONS . '/' . rawurlencode( $slug ) ),
			)
		);
	}

	/**
	 * @return array<string, array{label:string,icon:string,plugins:array}>
	 */
	public function group_discover_by_category( $catalog = null ) {
		if ( null === $catalog ) {
			$catalog = $this->get_discover_catalog();
		}

		$groups = array();
		foreach ( $catalog as $plugin ) {
			$cat = $plugin['category'] ?? 'other';
			if ( ! isset( $groups[ $cat ] ) ) {
				$groups[ $cat ] = array(
					'key'     => $cat,
					'label'   => $plugin['category_label'] ?? ucfirst( $cat ),
					'icon'    => $plugin['category_icon'] ?? '📦',
					'plugins' => array(),
				);
			}
			$groups[ $cat ]['plugins'][] = $plugin;
		}

		return $groups;
	}

	/**
	 * @return array<int, array<string, mixed>>
	 */
	public function get_discover_featured( $catalog = null, $limit = 6 ) {
		if ( null === $catalog ) {
			$catalog = $this->get_discover_catalog();
		}

		$featured = array();
		$seen     = array();

		foreach ( $catalog as $p ) {
			if ( ! empty( $p['is_featured'] ) && empty( $seen[ $p['slug'] ?? '' ] ) ) {
				$featured[]               = $p;
				$seen[ $p['slug'] ?? '' ] = true;
			}
		}

		if ( count( $featured ) < $limit ) {
			foreach ( $catalog as $p ) {
				$slug = $p['slug'] ?? '';
				if ( ! empty( $p['is_live'] ) && empty( $seen[ $slug ] ) ) {
					$featured[]    = $p;
					$seen[ $slug ] = true;
				}
				if ( count( $featured ) >= $limit ) {
					break;
				}
			}
		}

		return array_slice( $featured, 0, $limit );
	}

	public function render_discover_grid( $args = array() ) {
		$plugins = $this->get_discover_plugins( true );
		$live    = array_filter( $plugins, array( $this, 'is_plugin_live' ) );

		if ( empty( $plugins ) ) {
			return '<p>' . esc_html__( 'Aucun plugin trouvé.', 'core-version-switcher-by-volade' ) . '</p>';
		}

		$categories = array();
		foreach ( $plugins as $p ) {
			$cat = $p['category'] ?? 'other';
			if ( ! isset( $categories[ $cat ] ) ) {
				$categories[ $cat ] = array();
			}
			$categories[ $cat ][] = $p;
		}

		$output  = '<div class="volade-discover-grid">';
		$output .= '<p class="volade-discover-count">' . sprintf(
			/* translators: 1: number of live plugins, 2: number in development, 3: total catalog size */
			esc_html__( '%1$d disponible(s) · %2$d en développement · %3$d au catalogue', 'core-version-switcher-by-volade' ),
			count( $live ),
			count( $plugins ) - count( $live ),
			count( $plugins )
		) . '</p>';

		foreach ( $categories as $cat => $items ) {
			$cat_label = self::$category_labels[ $cat ] ?? ucfirst( $cat );
			$output   .= '<div class="volade-discover-category">';
			$output   .= '<h3 class="volade-category-title">' . esc_html( $cat_label ) . '</h3>';
			$output   .= '<div class="volade-discover-row">';

			foreach ( $items as $plugin ) {
				$output .= '<div class="volade-discover-card">';
				$output .= '<div class="volade-card-icon">' . esc_html( $plugin['icon'] ?? '🔌' ) . '</div>';
				$output .= $this->render_plugin_status_badge( $plugin );
				$output .= '<h4 class="volade-card-name">' . esc_html( $plugin['name'] ) . '</h4>';
				if ( ! empty( $plugin['description'] ) ) {
					$output .= '<p class="volade-card-desc">' . esc_html( $plugin['description'] ) . '</p>';
				}
				$output .= '</div>';
			}

			$output .= '</div></div>';
		}

		$output .= '</div>';
		return $output;
	}

	public function shortcode_discover( $atts ) {
		if ( ! $this->can_use_ecosystem_features() ) {
			return '';
		}

		wp_enqueue_style( 'volade-sdk-front', $this->get_url() . 'assets/front.css', array(), '1.1.0' );
		return $this->render_discover_grid( $atts );
	}

	public function ajax_discover_fetch() {
		if ( ! $this->can_use_ecosystem_features() ) {
			wp_send_json_error( __( 'Compte Volade requis.', 'core-version-switcher-by-volade' ), 403 );
		}

		check_ajax_referer( 'volade_nonce', 'nonce' );
		$plugins = $this->get_discover_plugins( true );
		wp_send_json_success( array( 'plugins' => $plugins ) );
	}

	public function rest_get_discover_plugins() {
		$plugins = $this->get_discover_plugins( true );
		$live    = array_filter( $plugins, array( $this, 'is_plugin_live' ) );
		return new WP_REST_Response(
			array(
				'plugins' => $plugins,
				'live'    => count( $live ),
				'total'   => count( $plugins ),
			),
			200
		);
	}
}
