<?php
/**
 * ExploreXR Addon Conflict Detector
 *
 * Detects potential conflicts between active addons and displays
 * admin notices to inform users about known incompatibilities.
 *
 * @package ExploreXR_Premium
 * @since   1.0.0
 */

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

/**
 * Addon Conflict Detector Class
 *
 * Checks active addons against a known conflict map and
 * stores/displays warnings via WordPress admin notices.
 */
class ExploreXR_Addon_Conflict_Detector {

	/**
	 * Reference to the Addon Manager
	 *
	 * @var ExploreXR_Addon_Manager
	 */
	private $addon_manager;

	/**
	 * Known conflict map.
	 *
	 * Each entry is an array with:
	 *   - addons:      array of two addon slugs that conflict
	 *   - severity:    'warning' or 'info'
	 *   - message:     Human-readable description of the conflict
	 *
	 * @var array
	 */
	private $conflict_map = array(
		array(
			'addons'   => array( 'camera', 'mouse3d' ),
			'severity' => 'warning',
			'message'  => 'The <strong>Camera Controls</strong> and <strong>Mouse 3D</strong> addons both modify viewer interaction attributes. When both are active, Camera Controls takes priority. Verify your interaction settings work as expected.',
		),
		array(
			'addons'   => array( 'animation', 'morphing' ),
			'severity' => 'info',
			'message'  => 'The <strong>Animation</strong> and <strong>Morphing</strong> addons both control model playback. If a model uses both skeletal animations and morph targets, ensure their settings do not interfere with each other.',
		),
		array(
			'addons'   => array( 'draggable', 'ar' ),
			'severity' => 'info',
			'message'  => 'The <strong>Draggable</strong> addon repositions the viewer on the page. This may interfere with the <strong>AR</strong> addon\'s placement when entering augmented reality mode.',
		),
	);

	/**
	 * Transient key for storing detected conflicts.
	 *
	 * @var string
	 */
	private $transient_key = 'explorexr_addon_conflicts';

	/**
	 * Constructor.
	 *
	 * @param ExploreXR_Addon_Manager $addon_manager Addon Manager instance.
	 */
	public function __construct( $addon_manager ) {
		$this->addon_manager = $addon_manager;
	}

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_action( 'admin_init', array( $this, 'detect_conflicts' ), 25 );
		add_action( 'admin_notices', array( $this, 'display_conflict_notices' ) );
	}

	/**
	 * Detect conflicts between currently active addons.
	 *
	 * Checks the conflict map against active WordPress plugins
	 * and stores any found conflicts in a transient.
	 */
	public function detect_conflicts() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$registered_addons = $this->addon_manager->get_registered_addons();
		$active_slugs      = array();

		foreach ( $registered_addons as $slug => $data ) {
			if ( ! empty( $data['file'] ) && is_plugin_active( plugin_basename( $data['file'] ) ) ) {
				$active_slugs[] = $slug;
			}
		}

		$conflicts = array();

		foreach ( $this->conflict_map as $conflict ) {
			$conflict_addons = $conflict['addons'];

			// Check if both conflicting addons are active.
			if (
				in_array( $conflict_addons[0], $active_slugs, true ) &&
				in_array( $conflict_addons[1], $active_slugs, true )
			) {
				$conflicts[] = $conflict;
			}
		}

		// Store in transient (1 hour cache to avoid running every page load).
		set_transient( $this->transient_key, $conflicts, HOUR_IN_SECONDS );

		do_action( 'explorexr_premium_debug', 'Conflict Detector: Found ' . count( $conflicts ) . ' conflict(s) among ' . count( $active_slugs ) . ' active addon(s).' );
	}

	/**
	 * Display conflict notices in the admin area.
	 *
	 * Only shows on ExploreXR-related admin pages.
	 */
	public function display_conflict_notices() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Only show on ExploreXR pages and plugins page.
		$screen = get_current_screen();
		if ( $screen ) {
			$show_on = array( 'plugins', 'toplevel_page_explorexr', 'explorexr_page_explorexr-settings', 'explorexr_page_explorexr-addons' );
			$is_explorexr_page = ( strpos( $screen->id, 'explorexr' ) !== false ) || in_array( $screen->id, $show_on, true );

			if ( ! $is_explorexr_page ) {
				return;
			}
		}

		$conflicts = get_transient( $this->transient_key );

		if ( empty( $conflicts ) || ! is_array( $conflicts ) ) {
			return;
		}

		foreach ( $conflicts as $conflict ) {
			$notice_class = ( 'warning' === $conflict['severity'] ) ? 'notice-warning' : 'notice-info';
			$dismiss_key  = 'explorexr_conflict_' . implode( '_', $conflict['addons'] );
			$is_dismissed = get_user_meta( get_current_user_id(), $dismiss_key, true );

			if ( $is_dismissed ) {
				continue;
			}

			printf(
				'<div class="notice %s is-dismissible" data-explorexr-conflict="%s"><p><strong>%s</strong> %s</p></div>',
				esc_attr( $notice_class ),
				esc_attr( $dismiss_key ),
				esc_html__( 'ExploreXR Addon Compatibility:', 'explorexr-premium' ),
				wp_kses_post( $conflict['message'] )
			);
		}
	}

	/**
	 * Get the current detected conflicts.
	 *
	 * @return array Array of conflict entries.
	 */
	public function get_conflicts() {
		$conflicts = get_transient( $this->transient_key );
		return is_array( $conflicts ) ? $conflicts : array();
	}

	/**
	 * Get the full conflict map for external use.
	 *
	 * @return array The conflict map.
	 */
	public function get_conflict_map() {
		return $this->conflict_map;
	}

	/**
	 * Check if a specific addon has any conflicts with other active addons.
	 *
	 * @param string $addon_slug The addon slug to check.
	 * @return array Array of conflict entries involving this addon.
	 */
	public function get_addon_conflicts( $addon_slug ) {
		$conflicts     = $this->get_conflicts();
		$addon_conflicts = array();

		foreach ( $conflicts as $conflict ) {
			if ( in_array( $addon_slug, $conflict['addons'], true ) ) {
				$addon_conflicts[] = $conflict;
			}
		}

		return $addon_conflicts;
	}
}
