<?php

namespace Brandy;

use Brandy\Traits\SingletonTrait;

class PatternsLibrary {
	use SingletonTrait;

	protected function __construct() {

		if ( ! is_admin() ) {
			return;
		}

		// Always register AJAX handler, even if plugin is active
		add_action( 'wp_ajax_brandy_get_patterns_after_activation', array( $this, 'get_patterns_after_activation' ) );

		add_action( 'enqueue_block_assets', array( $this, 'enqueue_scripts' ) );
	}

	public function enqueue_scripts() {
		// Only load the install prompt if Brandy Blocks is not active
		if ( is_brandy_blocks_installed() ) {
			return;
		}

		// Check if plugin is installed but not active
		$plugin_file     = 'brandy-blocks/brandy-blocks.php';
		$is_installed    = false;
		$plugin_basename = '';

		// Get all plugins
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$all_plugins = get_plugins();

		// Check if Brandy Blocks is installed
		foreach ( $all_plugins as $plugin_path => $plugin_data ) {
			if ( strpos( $plugin_path, 'brandy-blocks' ) !== false ) {
				$is_installed    = true;
				$plugin_basename = $plugin_path;
				break;
			}
		}

		wp_enqueue_script( 'brandy-patterns-library', BRANDY_TEMPLATE_URL . '/assets/lib/patterns-library.js', array( 'jquery' ), BRANDY_VERSION, true );
		wp_localize_script(
			'brandy-patterns-library',
			'brandyPatternsLibrary',
			array(
				'siteUrl'                    => home_url(),
				'ajaxUrl'                    => admin_url( 'admin-ajax.php' ),
				'nonce'                      => wp_create_nonce( 'updates' ),
				'patternsNonce'              => wp_create_nonce( 'brandy_get_patterns' ),
				'isBrandyBlocksInstalled'    => $is_installed,
				'brandyBlocksPluginBasename' => $plugin_basename,
			)
		);
	}

	/**
	 * AJAX handler to get patterns after plugin activation
	 */
	public function get_patterns_after_activation() {
		// Verify nonce (false = don't die on failure, just return false)
		$nonce_check = check_ajax_referer( 'brandy_get_patterns', 'nonce', false );
		if ( false === $nonce_check ) {
			wp_send_json_error( array( 'message' => 'Nonce verification failed' ) );
			return;
		}

		// Check user capabilities
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( array( 'message' => 'Insufficient permissions' ) );
			return;
		}

		try {
			// Force WordPress to recognize the newly activated plugin
			// This is necessary because the plugin was just activated via AJAX
			if ( ! defined( 'BRANDY_BLOCKS_VERSION' ) ) {
				// Try to find the plugin file
				$possible_paths = array(
					WP_PLUGIN_DIR . '/brandy-blocks/brandy-blocks.php',
					WP_PLUGIN_DIR . '/Brandy-Blocks/brandy-blocks.php',
					WP_PLUGIN_DIR . '/Brandy-Blocks-1/brandy-blocks.php',
				);

				foreach ( $possible_paths as $plugin_file ) {
					if ( file_exists( $plugin_file ) ) {
						include_once $plugin_file;
						// Initialize the plugin if there's an init class
						if ( class_exists( 'BrandyBlocks\Initialize' ) ) {
							\BrandyBlocks\Initialize::get_instance();
						}
						break;
					}
				}
			}

			// Get all registered patterns
			$patterns   = \WP_Block_Patterns_Registry::get_instance()->get_all_registered();
			$categories = \WP_Block_Pattern_Categories_Registry::get_instance()->get_all_registered();

			// Filter only Brandy patterns
			$brandy_patterns = array_filter(
				$patterns,
				function ( $pattern ) {
					return isset( $pattern['categories'] ) && is_array( $pattern['categories'] )
						&& count(
							array_filter(
								$pattern['categories'],
								function ( $cat ) {
									return stripos( $cat, 'brandy' ) !== false;
								}
							)
						) > 0;
				}
			);

			$brandy_categories = array();
			foreach ( $categories as $category ) {
				if ( stripos( $category['name'], 'brandy' ) !== false ) {
					$brandy_categories[] = $category;
				}
			}

			wp_send_json_success(
				array(
					'patterns'   => array_values( $brandy_patterns ),
					'categories' => $brandy_categories,
				)
			);
		} catch ( \Exception $e ) {
			wp_send_json_error(
				array(
					'message' => 'Error loading patterns: ' . $e->getMessage(),
				)
			);
		}
	}
}

PatternsLibrary::get_instance();
