<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Utils;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Plugin_Detector {

	private static $detection_cache = array();

	/**
	 * Detect active plugins and their capabilities
	 */
	public static function get_active_plugins_info() {
		if ( ! empty( self::$detection_cache ) ) {
			return self::$detection_cache;
		}

		$plugins = array(
			'wpml'        => self::detect_wpml(),
			'yoast'       => self::detect_yoast(),
			'rankmath'    => self::detect_rankmath(),
			'seopress'    => self::detect_seopress(),
			'woocommerce' => self::detect_woocommerce(),
			'acf'         => self::detect_acf(),
			'polylang'    => self::detect_polylang(),
		);

		self::$detection_cache = $plugins;
		return $plugins;
	}

	/**
	 * Check if WPML is active and functional
	 */
	public static function detect_wpml() {
		if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
			return array( 'active' => false );
		}

		global $sitepress;
		if ( ! $sitepress ) {
			return array( 'active' => false );
		}

		$languages    = $sitepress->get_active_languages();
		$default_lang = $sitepress->get_default_language();

		return array(
			'active'              => true,
			'version'             => ICL_SITEPRESS_VERSION ?? 'unknown',
			'languages'           => $languages,
			'default_language'    => $default_lang,
			'total_languages'     => count( $languages ),
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_categories' => true,
			'supports_products'   => class_exists( 'WooCommerce' ),
		);
	}

	/**
	 * Check if Yoast SEO is active and get capabilities
	 */
	public static function detect_yoast() {
		if ( ! defined( 'WPSEO_VERSION' ) ) {
			return array( 'active' => false );
		}

		return array(
			'active'              => true,
			'version'             => WPSEO_VERSION ?? 'unknown',
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_products'   => class_exists( 'WooCommerce' ),
			'supports_categories' => true,
			'meta_keys'           => array(
				'title'               => '_yoast_wpseo_title',
				'description'         => '_yoast_wpseo_metadesc',
				'focus_keyword'       => '_yoast_wpseo_focuskw',
				'canonical'           => '_yoast_wpseo_canonical',
				'og_title'            => '_yoast_wpseo_opengraph-title',
				'og_description'      => '_yoast_wpseo_opengraph-description',
				'twitter_title'       => '_yoast_wpseo_twitter-title',
				'twitter_description' => '_yoast_wpseo_twitter-description',
			),
		);
	}

	/**
	 * Check if Rank Math is active and get capabilities
	 */
	public static function detect_rankmath() {
		if ( ! defined( 'RANK_MATH_VERSION' ) ) {
			return array( 'active' => false );
		}

		return array(
			'active'              => true,
			'version'             => RANK_MATH_VERSION ?? 'unknown',
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_products'   => class_exists( 'WooCommerce' ),
			'supports_categories' => true,
			'meta_keys'           => array(
				'title'               => 'rank_math_title',
				'description'         => 'rank_math_description',
				'focus_keyword'       => 'rank_math_focus_keyword',
				'canonical'           => 'rank_math_canonical_url',
				'og_title'            => 'rank_math_facebook_title',
				'og_description'      => 'rank_math_facebook_description',
				'twitter_title'       => 'rank_math_twitter_title',
				'twitter_description' => 'rank_math_twitter_description',
			),
		);
	}

	/**
	 * Check if SEOPress is active and get capabilities
	 */
	public static function detect_seopress() {
		if ( ! defined( 'SEOPRESS_VERSION' ) ) {
			return array( 'active' => false );
		}

		$has_pro = defined( 'SEOPRESS_PRO_VERSION' );

		return array(
			'active'              => true,
			'version'             => SEOPRESS_VERSION ?? 'unknown',
			'has_pro'             => $has_pro,
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_products'   => class_exists( 'WooCommerce' ),
			'supports_categories' => true,
			'meta_keys'           => array(
				'title'               => '_seopress_titles_title',
				'description'         => '_seopress_titles_desc',
				'focus_keyword'       => '_seopress_analysis_target_kw',
				'canonical'           => '_seopress_robots_canonical',
				'og_title'            => '_seopress_social_fb_title',
				'og_description'      => '_seopress_social_fb_desc',
				'og_image'            => '_seopress_social_fb_img',
				'twitter_title'       => '_seopress_social_twitter_title',
				'twitter_description' => '_seopress_social_twitter_desc',
				'twitter_image'       => '_seopress_social_twitter_img',
			),
		);
	}

	/**
	 * Check if WooCommerce is active and functional
	 */
	public static function detect_woocommerce() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return array( 'active' => false );
		}

		global $woocommerce;
		$version = $woocommerce ? $woocommerce->version : 'unknown';

		return array(
			'active'              => true,
			'version'             => $version,
			'supports_products'   => true,
			'supports_categories' => true,
			'supports_attributes' => true,
			'product_count'       => wp_count_posts( 'product' )->publish ?? 0,
			'category_count'      => wp_count_terms( 'product_cat' ) ?? 0,
		);
	}

	/**
	 * Check if ACF is active
	 */
	public static function detect_acf() {
		if ( ! function_exists( 'get_field' ) ) {
			return array( 'active' => false );
		}

		return array(
			'active'              => true,
			'version'             => defined( 'ACF_VERSION' ) ? ACF_VERSION : 'unknown',
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_products'   => class_exists( 'WooCommerce' ),
			'supports_categories' => true,
		);
	}

	/**
	 * Check if Polylang is active (alternative to WPML)
	 */
	public static function detect_polylang() {
		if ( ! function_exists( 'pll_languages_list' ) ) {
			return array( 'active' => false );
		}

		$languages = pll_languages_list();

		return array(
			'active'              => true,
			'version'             => defined( 'POLYLANG_VERSION' ) ? POLYLANG_VERSION : 'unknown',
			'languages'           => $languages,
			'total_languages'     => count( $languages ),
			'supports_posts'      => true,
			'supports_pages'      => true,
			'supports_categories' => true,
		);
	}

	/**
	 * Check if any multilingual plugin is active
	 */
	public static function has_multilingual_support() {
		$wpml     = self::detect_wpml();
		$polylang = self::detect_polylang();

		return $wpml['active'] || $polylang['active'];
	}

	/**
	 * Check if any SEO plugin is active
	 */
	public static function has_seo_support() {
		$yoast    = self::detect_yoast();
		$rankmath = self::detect_rankmath();
		$seopress = self::detect_seopress();

		return $yoast['active'] || $rankmath['active'] || $seopress['active'];
	}

	/**
	 * Get the primary SEO plugin info
	 */
	public static function get_primary_seo_plugin() {
		$yoast    = self::detect_yoast();
		$rankmath = self::detect_rankmath();
		$seopress = self::detect_seopress();

		if ( $yoast['active'] ) {
			return array(
				'plugin' => 'yoast',
				'info'   => $yoast,
			);
		}

		if ( $rankmath['active'] ) {
			return array(
				'plugin' => 'rankmath',
				'info'   => $rankmath,
			);
		}

		if ( $seopress['active'] ) {
			return array(
				'plugin' => 'seopress',
				'info'   => $seopress,
			);
		}

		return array(
			'plugin' => 'none',
			'info'   => array( 'active' => false ),
		);
	}

	/**
	 * Get available post types for import
	 */
	public static function get_available_post_types() {
		$post_types = array(
			'post' => __( 'Blog Post', 'wisewand-ai-content-writer-seo-content-generator' ),
			'page' => __( 'Page', 'wisewand-ai-content-writer-seo-content-generator' ),
		);

		// Add WooCommerce types if available
		$woocommerce = self::detect_woocommerce();
		if ( $woocommerce['active'] ) {
			$post_types['product'] = __( 'WooCommerce Product', 'wisewand-ai-content-writer-seo-content-generator' );
		}

		return $post_types;
	}

	/**
	 * Check if post type supports SEO fields
	 */
	public static function post_type_supports_seo( $post_type ) {
		$seo_plugin = self::get_primary_seo_plugin();

		if ( ! $seo_plugin['info']['active'] ) {
			return false;
		}

		$info = $seo_plugin['info'];

		switch ( $post_type ) {
			case 'post':
				return $info['supports_posts'] ?? true;
			case 'page':
				return $info['supports_pages'] ?? true;
			case 'product':
				return $info['supports_products'] ?? false;
			case 'category':
				return $info['supports_categories'] ?? true;
			default:
				return false;
		}
	}

	/**
	 * Get plugin status summary for admin display
	 */
	public static function get_plugin_status_summary() {
		$plugins = self::get_active_plugins_info();

		$summary = array(
			'multilingual'  => array(
				'available'       => $plugins['wpml']['active'] || $plugins['polylang']['active'],
				'plugin'          => $plugins['wpml']['active'] ? 'WPML' : ( $plugins['polylang']['active'] ? 'Polylang' : 'None' ),
				'languages_count' => $plugins['wpml']['total_languages'] ?? $plugins['polylang']['total_languages'] ?? 0,
			),
			'seo'           => array(
				'available' => $plugins['yoast']['active'] || $plugins['rankmath']['active'] || $plugins['seopress']['active'],
				'plugin'    => $plugins['yoast']['active'] ? 'Yoast SEO' :
							( $plugins['rankmath']['active'] ? 'Rank Math' :
							( $plugins['seopress']['active'] ? 'SEOPress' : 'None' ) ),
				'version'   => $plugins['yoast']['version'] ?? $plugins['rankmath']['version'] ?? $plugins['seopress']['version'] ?? 'N/A',
				'has_pro'   => $plugins['seopress']['has_pro'] ?? false,
			),
			'ecommerce'     => array(
				'available'     => $plugins['woocommerce']['active'],
				'plugin'        => $plugins['woocommerce']['active'] ? 'WooCommerce' : 'None',
				'product_count' => $plugins['woocommerce']['product_count'] ?? 0,
			),
			'custom_fields' => array(
				'available' => $plugins['acf']['active'],
				'plugin'    => $plugins['acf']['active'] ? 'ACF' : 'None',
				'version'   => $plugins['acf']['version'] ?? 'N/A',
			),
		);

		return $summary;
	}
}
