<?php
/**
 * Main plugin bootstrap.
 *
 * @package SKYNSMFA_Smart_Favorites
 */

declare( strict_types=1 );

namespace SKYNSMFA\Wishlist;

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


final class Plugin {
	/**
	 * Singleton instance.
	 *
	 * @var Plugin|null
	 */
	private static $instance = null;

	/**
	 * Whether WooCommerce is active.
	 *
	 * @var bool
	 */
	private $wc_active = false;

	/**
	 * Whether the free bootstrap has already run.
	 *
	 * @var bool
	 */
	private static $booted = false;

	/**
	 * Boot plugin on plugins_loaded.
	 *
	 * @return void
	 */
	public static function boot(): void {
		if ( self::$booted ) {
			return;
		}

		self::$booted = true;
		self::instance()->init();
	}

	/**
	 * Declare WooCommerce feature compatibility for Marketplace / QIT.
	 *
	 * Must run only on `before_woocommerce_init`. Declares HPOS (custom_order_tables)
	 * and Cart/Checkout blocks — required for new WooCommerce.com extension submissions.
	 *
	 * @see https://developer.woocommerce.com/docs/woo-marketplace/submitting-your-product/
	 * @return void
	 */
	public static function declare_wc_compatibility(): void {
		if ( ! class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
			return;
		}

		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', SKYNSMFA_FILE, true );
		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', SKYNSMFA_FILE, true );
	}

	/**
	 * Get singleton instance.
	 *
	 * @return Plugin
	 */
	public static function instance(): Plugin {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Plugin constructor.
	 */
	private function __construct() {
	}

	/**
	 * Prevent cloning.
	 */
	private function __clone() {
	}

	/**
	 * Prevent unserializing.
	 *
	 * @return void
	 */
	public function __wakeup(): void {
	}

	/**
	 * Initialize plugin.
	 *
	 * @return void
	 */
	private function init(): void {
		$this->wc_active = class_exists( 'WooCommerce' );

		if ( ! $this->wc_active ) {
			add_action( 'admin_notices', array( $this, 'render_wc_missing_notice' ) );
			return;
		}

		spl_autoload_register( array( __CLASS__, 'autoload' ) );

		add_filter( 'plugin_action_links_' . plugin_basename( SKYNSMFA_FILE ), array( $this, 'filter_plugin_action_links' ) );
		add_action( 'woocommerce_init', array( $this, 'bootstrap_woocommerce_integrations' ), 5 );

		Admin::instance();
		Session::instance();
		Ajax::instance();
		Frontend::instance();
		Blocks::instance();
		Sync::instance();
	}

	/**
	 * Add Settings link on Plugins screen (after Activate).
	 *
	 * @param array<string, string> $links Existing action links.
	 * @return array<string, string>
	 */
	public function filter_plugin_action_links( array $links ): array {
		$settings_url = add_query_arg(
			array(
				'page' => SKYNSMFA_ADMIN_PAGE_SLUG,
				'tab'  => 'settings',
			),
			admin_url( 'admin.php' )
		);

		$settings_link = sprintf(
			'<a href="%1$s">%2$s</a>',
			esc_url( $settings_url ),
			esc_html__( 'Settings', 'skynet-smart-favorites' )
		);

		array_unshift( $links, $settings_link );

		return $links;
	}

	/**
	 * DB upgrades and WooCommerce email registration.
	 *
	 * @return void
	 */
	public function bootstrap_woocommerce_integrations(): void {
		$db = DB::instance();
		$db->maybe_upgrade();

		/**
		 * Load Pro integrations (emails, analytics consumers, etc.).
		 *
		 * @since 1.0.2
		 */
		do_action( 'skynsmfa_bootstrap_integrations' );
	}

	/**
	 * Autoloader for SKYNSMFA\Wishlist classes (allowlisted paths only).
	 *
	 * @param string $class_name Fully qualified class name.
	 * @return void
	 */
	public static function autoload( string $class_name ): void {
		$prefix = __NAMESPACE__ . '\\';

		if ( 0 !== strpos( $class_name, $prefix ) ) {
			return;
		}

		$relative = substr( $class_name, strlen( $prefix ) );
		if ( '' === $relative ) {
			return;
		}

		$relative = strtolower( str_replace( '\\', '-', $relative ) );

		switch ( $relative ) {
			case 'admin':
				require_once __DIR__ . '/class-admin.php';
				break;
			case 'ajax':
				require_once __DIR__ . '/class-ajax.php';
				break;
			case 'blocks':
				require_once __DIR__ . '/class-blocks.php';
				break;
			case 'css_sanitizer':
				require_once __DIR__ . '/class-css-sanitizer.php';
				break;
			case 'db':
				require_once __DIR__ . '/class-db.php';
				break;
			case 'feature_gate':
				require_once __DIR__ . '/class-feature-gate.php';
				break;
			case 'frontend':
				require_once __DIR__ . '/class-frontend.php';
				break;
			case 'rate_limit':
				require_once __DIR__ . '/class-rate-limit.php';
				break;
			case 'session':
				require_once __DIR__ . '/class-session.php';
				break;
			case 'sync':
				require_once __DIR__ . '/class-sync.php';
				break;
			default:
				return;
		}
	}

	/**
	 * Activation hook.
	 *
	 * @return void
	 */
	public static function activate(): void {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		spl_autoload_register( array( __CLASS__, 'autoload' ) );

		DB::instance()->install();
		update_option( 'skynsmfa_db_version', DB::SCHEMA_VERSION, false );

		if ( false === get_option( 'skynsmfa_settings', false ) ) {
			add_option(
				'skynsmfa_settings',
				array(
					'skynsmfa_enable'               => 'yes',
					'skynsmfa_multiple_enable'      => 'yes',
					'skynsmfa_add_target_mode'      => 'last_used',
					'skynsmfa_loop_icon'            => 'yes',
					'skynsmfa_single_icon'          => 'yes',
					'skynsmfa_loop_position'        => 'after_add_to_cart',
					'skynsmfa_single_position'      => 'after_add_to_cart',
					'skynsmfa_display_mode'         => 'button',
					'skynsmfa_custom_shortcode'     => 'yes',
					'skynsmfa_menu_icon'            => 'yes',
					'skynsmfa_notification_type'    => 'toast',
					'skynsmfa_page_layout'          => 'table',
					'skynsmfa_rate_limit_per_min'   => 120,
				),
				'',
				false
			);
		}

		self::create_pages();
	}

	/**
	 * Create default wishlist page if it doesn't exist.
	 *
	 * @return void
	 */
	public static function create_pages(): void {
		$settings = get_option( 'skynsmfa_settings', array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		// Check if page already exists and is valid
		if ( ! empty( $settings['wishlist_page_id'] ) && 'publish' === get_post_status( $settings['wishlist_page_id'] ) ) {
			return;
		}

		// Try to find an existing wishlist page by title.
		$pages = get_posts(
			array(
				'post_type'      => 'page',
				'post_status'    => 'publish',
				's'              => __( 'Wishlist', 'skynet-smart-favorites' ),
				'posts_per_page' => 5,
			)
		);

		$page = null;
		foreach ( $pages as $found_page ) {
			if ( $found_page instanceof WP_Post && $found_page->post_title === __( 'Wishlist', 'skynet-smart-favorites' ) ) {
				$page = $found_page;
				break;
			}
		}

		if ( $page instanceof WP_Post && 'publish' === $page->post_status ) {
			$page_id_to_save = $page->ID;

			if ( ! has_shortcode( $page->post_content, 'skynsmfa_wishlist' ) ) {
				wp_update_post(
					array(
						'ID'           => $page_id_to_save,
						'post_content' => trim( $page->post_content ) . "\n\n[skynsmfa_wishlist]",
					)
				);
			}
		} else {
			// Create a new one
			$page_id_to_save = wp_insert_post(
				array(
					'post_title'     => 'Wishlist',
					'post_content'   => '[skynsmfa_wishlist]',
					'post_status'    => 'publish',
					'post_type'      => 'page',
					'comment_status' => 'closed',
				)
			);
		}

		if ( ! is_wp_error( $page_id_to_save ) ) {
			$settings['wishlist_page_id'] = $page_id_to_save;
			update_option( 'skynsmfa_settings', $settings );
		}
	}

	/**
	 * Whether storefront wishlist features are enabled in settings.
	 *
	 * @return bool
	 */
	public static function is_wishlist_enabled(): bool {
		$settings = get_option( 'skynsmfa_settings', array() );
		if ( ! is_array( $settings ) ) {
			return true;
		}

		return 'yes' === ( $settings['skynsmfa_enable'] ?? 'yes' );
	}

	/**
	 * Admin notice for missing WooCommerce.
	 *
	 * @return void
	 */
	public function render_wc_missing_notice(): void {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}

		echo '<div class="notice notice-error"><p>';
		echo esc_html__( 'SkyNet Smart Favorites requires WooCommerce to be installed and active.', 'skynet-smart-favorites' );
		echo '</p></div>';
	}
}
