<?php
/**
 * Admin page bootstrap.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Admin;

use PRECO\Includes\Common\AssetLoader;
use PRECO\Includes\Preco;

defined( 'ABSPATH' ) || exit;

/**
 * Registers the admin page and enqueues the React app.
 */
class Admin {
	/**
	 * Menu hook suffix.
	 *
	 * @var string|null
	 */
	private $page_hook = null;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_filter( 'plugin_action_links_' . PRECO_BASE, array( $this, 'add_plugin_action_links' ) );
		add_action( 'admin_init', array( $this, 'maybe_activation_redirect' ) );
		add_filter( 'plugin_row_meta', array( $this, 'plugin_settings_meta' ), 10, 2 );
	}

	/**
	 * Redirect to the Overview page once, right after activation.
	 *
	 * Skipped for bulk/network activation and AJAX requests, where a
	 * redirect can't be followed or would hijack an unrelated screen.
	 *
	 * @return void
	 */
	public function maybe_activation_redirect() {
		if ( ! get_transient( 'preco_activation_redirect' ) ) {
			return;
		}

		delete_transient( 'preco_activation_redirect' );

		if ( wp_doing_ajax() || is_network_admin() || isset( $_GET['activate-multi'] ) || ! current_user_can( 'manage_woocommerce' ) ) {   // @codingStandardsIgnoreLine
			return;
		}

		wp_safe_redirect( admin_url( 'admin.php?page=preco-dashboard#overview' ) );
		exit;
	}

	/**
	 * Add a "Recommendation" link to the plugin row on the Plugins page,
	 * pointing to the plugin's main admin page.
	 *
	 * @param array $links Existing plugin action links.
	 * @return array
	 */
	public function add_plugin_action_links( $links ) {
		$overview_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=preco-dashboard#overview' ) ),
			esc_html__( 'Recommendations', 'wow-ai-product-recommendations' )
		);

		array_unshift( $links, $overview_link );

		return $links;
	}

	/**
	 * Adds extra links to the plugin row meta on the plugins page.
	 *
	 * @param array  $links Existing plugin meta links.
	 * @param string $file  Plugin file path.
	 * @return array Modified plugin meta links.
	 */
	public function plugin_settings_meta( $links, $file ) {
		if ( strpos( $file, 'wow-ai-product-recommendations.php' ) !== false ) {
			$new_links = array(
				'preco_docs'    => '<a href="https://wpxpo.com/docs/wowrecommend/?utm_source=db-wowrecommend-plugin&utm_medium=doc&utm_campaign=wowrecommend-dashboard" target="_blank">' . esc_html__( 'Docs', 'wow-ai-product-recommendations' ) . '</a>',
				'preco_support' => '<a href="https://www.wpxpo.com/contact/" target="_blank">' . esc_html__( 'Support', 'wow-ai-product-recommendations' ) . '</a>',
			);
			$links     = array_merge( $links, $new_links );
		}
		return $links;
	}

	/**
	 * Suppress other plugins' admin notices on our screen.
	 *
	 * @return void
	 */
	public function suppress_admin_notices() {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( empty( $screen ) || empty( $this->page_hook ) || $screen->id !== $this->page_hook ) {
			return;
		}

		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );
		remove_all_actions( 'network_admin_notices' );
		remove_all_actions( 'user_admin_notices' );
	}

	/**
	 * Hide any remaining notice containers via CSS on our admin page.
	 *
	 * @return void
	 */
	public function hide_notice_css() {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( empty( $screen ) || empty( $this->page_hook ) || $screen->id !== $this->page_hook ) {
			return;
		}
	}

	/**
	 * Recommendation Builder (any route) and onboarding both render as a
	 * full-screen React overlay that covers the WP admin bar/menu — but only
	 * once the JS bundle has mounted, which is well after WordPress has
	 * already printed the (still-visible) admin bar markup into <body>. The
	 * builder route is client-only (URL hash, never sent to the server), so
	 * PHP can't scope this by hook alone; instead this registers a sourceless
	 * "boot" script — printed in <head>, before the admin bar HTML exists —
	 * and attaches the actual logic to it via wp_add_inline_script() (rather
	 * than echoing a raw <script> tag, which trips the WP coding standards'
	 * enqueued-resources check). The inline script adds the same
	 * 'preco-popup-layout-open' class the React app uses (see
	 * src/builder/index.js and popup-layout/style.scss), eliminating the
	 * flash of the admin bar/menu on first paint. React takes over class
	 * management once it mounts.
	 *
	 * Only ever called from enqueue_assets(), which has already confirmed
	 * we're on our own admin page before reaching this point.
	 *
	 * @return void
	 */
	public function print_fullscreen_boot_script() {
		$handle = 'preco-fullscreen-boot';
		// `false` src + `false` in_footer registers a placeholder with
		// nothing to load, printed in <head> — a carrier for the inline
		// script below, not an actual asset request.
		wp_register_script( $handle, false, array(), PRECO_VER, false );
		wp_enqueue_script( $handle );

		$onboarding_pending = \PRECO\Includes\Admin\Onboarding::should_show();
		$inline_script      = sprintf(
			'(function(){var hash=window.location.hash||"";if(%s||hash.indexOf("#recommendation-builder/")===0){document.documentElement.classList.add("preco-popup-layout-open");}})();',
			wp_json_encode( $onboarding_pending )
		);
		wp_add_inline_script( $handle, $inline_script );
	}

	/**
	 * Register admin menu page.
	 *
	 * @return void
	 */
	public function register_menu() {
		$this->page_hook = add_menu_page(
			__( 'WowRecommend', 'wow-ai-product-recommendations' ),
			__( 'WowRecommend', 'wow-ai-product-recommendations' ),
			'manage_woocommerce',
			'preco-dashboard',
			array( $this, 'render_page' ),
			PRECO_URL . '/assets/img/preco-icon-square-v2.svg',
			55.7
		);

		// Overrides the auto-generated first submenu item (which would
		// otherwise repeat the "Recommendation" menu title) with a
		// distinct label, without changing the top-level menu text.
		add_submenu_page(
			'preco-dashboard',
			__( 'WowRecommend', 'wow-ai-product-recommendations' ),
			__( 'Overview', 'wow-ai-product-recommendations' ),
			'manage_woocommerce',
			'preco-dashboard',
			array( $this, 'render_page' )
		);

		// These two link into the React app's own hash-routed pages (see
		// NavProvider in src/builder/store/nav/provider.js). The "#…" fragment
		// never reaches the server — WordPress always renders render_page()
		// for the base "preco-dashboard" slug — so the app
		// picks up the requested view from window.location.hash on load.
		// preco-admin-menu.js re-applies the "current" class client-side since
		// core can't tell these apart from Overview by slug alone.
		add_submenu_page(
			'preco-dashboard',
			__( 'Recommendations', 'wow-ai-product-recommendations' ),
			__( 'Recommendations', 'wow-ai-product-recommendations' ),
			'manage_woocommerce',
			'preco-dashboard#recommendation-builder/product-page',
			array( $this, 'render_page' )
		);

		add_submenu_page(
			'preco-dashboard',
			__( 'Analytics', 'wow-ai-product-recommendations' ),
			__( 'Analytics', 'wow-ai-product-recommendations' ),
			'manage_woocommerce',
			'preco-dashboard#analytics',
			array( $this, 'render_page' )
		);

		// License activation only makes sense once the Pro plugin (which owns
		// the wp_ajax_edd_preco_* handlers, see PRECO_PRO\Includes\License) is
		// installed and active — mirrors wow-ai-product-recommendations' Options::menu_page_callback().
		if ( defined( 'PRECO_PRO_VER' ) ) {
			add_submenu_page(
				'preco-dashboard',
				__( 'License', 'wow-ai-product-recommendations' ),
				__( 'License', 'wow-ai-product-recommendations' ),
				'manage_woocommerce',
				'preco-dashboard#license',
				array( $this, 'render_page' )
			);
		}

		$pro_link      = '';
		$pro_link_text = '';
		if ( ! Preco::is_lc_active() ) {
			$pro_link      = Preco::generate_utm_link(
				array(
					'utmKey' => 'sub_menu',
				)
			);
			$pro_link_text = __( 'Upgrade to Pro!', 'wow-ai-product-recommendations' );

			$is_offer_running = true;
			if ( $is_offer_running ) {
				$current_time = gmdate( 'U' );
				$start        = '2026-01-01 00:00 Asia/Dhaka';
				$end          = '2026-02-15 23:59 Asia/Dhaka';
				$notice_start = gmdate( 'U', strtotime( $start ) );
				$notice_end   = gmdate( 'U', strtotime( $end ) );
				if ( $current_time >= $notice_start && $current_time <= $notice_end ) {
					$pro_link_text = esc_html__( 'New Year Offer!', 'wow-ai-product-recommendations' );
				}
			}
		}

		if ( ! empty( $pro_link ) ) {
			ob_start();
			?>
				<a href="<?php echo esc_url( $pro_link ); ?>" target="_blank" class="preco-go-pro">
					<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M2.86 6.553a.5.5 0 01.823-.482l3.02 2.745c.196.178.506.13.64-.098L9.64 4.779a.417.417 0 01.72 0l2.297 3.939a.417.417 0 00.64.098l3.02-2.745a.5.5 0 01.823.482l-1.99 8.63a.833.833 0 01-.813.646H5.663a.833.833 0 01-.812-.646L2.86 6.553z" stroke="currentColor" stroke-width="1.5"></path>
					</svg>
					<span><?php echo esc_html( $pro_link_text ); ?></span>
				</a>
			<?php
			$submenu_content = ob_get_clean();

			add_submenu_page(
				'preco-dashboard',
				'',
				$submenu_content,
				'manage_options',
				'preco-pro',
				array( self::class, 'handle_external_redirects' )
			);

		}
	}

	/**
	 * Go to Pro URL Redirect
	 *
	 * @since v.1.0.0
	 * @return null
	 */
	public function handle_external_redirects() {
        if ( empty( $_GET['page'] ) ) {     // @codingStandardsIgnoreLine
			return;
		}
        if ( 'go_preco_pro' === sanitize_text_field( $_GET['page'] ) ) {   // @codingStandardsIgnoreLine
			wp_safe_redirect( 'https://www.wpxpo.com/product/wowrecommend/#pricing' );
			die();
		}
	}

	/**
	 * Render root element for the React app.
	 *
	 * @return void
	 */
	public function render_page() {
		echo '<div class="wrap"><div id="preco-builder-root"></div></div>';
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_assets( $hook ) {
		AssetLoader::enqueue_script( 'preco-admin-menu-script', 'preco-admin-menu', true );
		AssetLoader::enqueue_style( 'preco-admin-menu-style', 'preco-admin-menu' );
		if ( empty( $this->page_hook ) || $hook !== $this->page_hook ) {
			return;
		}

		add_action( 'in_admin_header', array( $this, 'suppress_admin_notices' ), 0 );
		add_action( 'admin_head', array( $this, 'hide_notice_css' ), 99 );
		// Registers/enqueues a script, so it must run here (on
		// admin_enqueue_scripts, before <head> output starts) rather than
		// on admin_head — enqueueing that late risks WP deferring it to
		// admin_print_footer_scripts, well after the admin bar has printed.
		$this->print_fullscreen_boot_script();

		// Ensure WordPress React dependencies are loaded.
		wp_enqueue_script( 'wp-element' );
		wp_enqueue_script( 'wp-components' );
		wp_enqueue_script( 'wp-api-fetch' );
		wp_enqueue_script( 'wp-i18n' );

		$handle       = 'preco-builder';
		$entry        = 'preco-builder';
		$preco_common = 'preco-common';

		// Enqueue built script (assets/js/preco-builder.js + .asset.php).
		AssetLoader::enqueue_script( $handle, $entry, true );
		AssetLoader::enqueue_style( $handle, $entry, array( 'wp-components' ) );
		AssetLoader::enqueue_style( $preco_common, $preco_common );

		// preco-common.css relies on row-position classes that only JS can
		// resolve — the builder preview needs the same script the storefront
		// loads (class-frontend.php) or layout 3 draws double borders.
		AssetLoader::enqueue_script( 'preco-grid-rows', 'preco-grid-rows', true );

		$user_info = wp_get_current_user();

		AssetLoader::localize_script(
			$handle,
			'PRECO_ADMIN',
			array_merge(
				array(
					'restRoot'      => esc_url_raw( rest_url() ),
					'url'           => PRECO_URL,
					'show_lic_page' => defined( 'PRECO_PRO_VER' ),
					'is_active'     => Preco::is_lc_active(),
					'license'       => Preco::get_lc_key(),
					'nonce'         => wp_create_nonce( 'wp_rest' ),
					'flags'         => $this->get_flags(),
					'ajax'          => admin_url( 'admin-ajax.php' ),
					'has_products'  => Preco::has_products(),
					'productsUrl'   => admin_url( 'edit.php?post_type=product' ),
					'previewUrls'   => $this->get_preview_urls(),
					'onboarding'    => array(
						'status' => \PRECO\Includes\Admin\Onboarding::get_status(),
					),
					'userInfo'      => array(
						'name'  => $user_info->first_name ? $user_info->first_name . ( $user_info->last_name ? ' ' . $user_info->last_name : '' ) : $user_info->user_login,
						'email' => $user_info->user_email,
					),
				),
				Preco::get_wow_products_details()
			)
		);

		// WP components styles.
		wp_enqueue_style( 'wp-components' );
	}

	/**
	 * Get flags for the admin page.
	 *
	 * @return array
	 */
	public function get_flags() {
		$flags = array(
			'CONDITION_PRO_OPTIONS' => array( 'relative_price', 'stock_status' ),
		);
		return $flags;
	}

	/**
	 * Well-known storefront URLs for the live builder preview iframe.
	 *
	 * Shop/Cart/Checkout are fixed WooCommerce pages, so these are localized
	 * once here rather than round-tripped via REST. Product Page and Product
	 * Archive need a specific product/category, so those are resolved by the
	 * PreviewRest /preview/sample-product and /preview/sample-category routes.
	 *
	 * @return array
	 */
	private function get_preview_urls() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return array();
		}

		return array(
			'shop'     => function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'shop' ) : '',
			'cart'     => function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : '',
			'checkout' => function_exists( 'wc_get_checkout_url' ) ? wc_get_checkout_url() : '',
		);
	}
}
