<?php
/**
 * Admin onboarding bootstrap for AR for WordPress.
 *
 * @package AR_For_WordPress
 */

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

if ( ! class_exists( 'AR_Onboarding_Assistant' ) ) {
	class AR_Onboarding_Assistant {
		const USER_META_TOUR_DISMISSED = 'ar_onboarding_tour_dismissed';

		/**
		 * Initialise hooks.
		 */
		public static function init() {
			add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_assets' ), 20 );
			add_action( 'wp_ajax_ar_onboarding_toggle_tour', array( __CLASS__, 'handle_tour_state' ) );
		}

		/**
		 * Determines whether the current admin screen should load onboarding assets.
		 *
		 * @return bool
		 */
		protected static function should_enqueue() {
			if ( ! function_exists( 'get_current_screen' ) ) {
				return false;
			}

			$screen = get_current_screen();
			if ( ! $screen ) {
				return false;
			}

			// Directly target AR model post type for list, edit, and add-new screens.
			if ( isset( $screen->post_type ) && 'armodels' === $screen->post_type ) {
				return true;
			}

			// Settings and analytics subpages under the AR Models menu.
			if ( isset( $screen->id ) && 0 === strpos( $screen->id, 'armodels_page_' ) ) {
				return true;
			}

			// Dedicated analytics dashboard page.
			if ( 'armodels_page_ar-analytics' === ( $screen->id ?? '' ) ) {
				return true;
			}

			return false;
		}

		/**
		 * Enqueue onboarding assets.
		 *
		 * @param string $hook Current admin hook.
		 */
		public static function enqueue_admin_assets( $hook ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
			if ( ! self::should_enqueue() ) {
				return;
			}

			global $ar_plugin_root_url, $ar_version;

			$style_handle  = 'ar-onboarding-admin';
			$script_handle = 'ar-onboarding-admin';

			wp_enqueue_style(
				$style_handle,
				$ar_plugin_root_url . 'assets/onboarding/onboarding.css',
				array(),
				$ar_version
			);

			wp_enqueue_style(
				'ar-onboarding-shepherd-css',
				$ar_plugin_root_url . 'assets/onboarding/vendor/shepherd.min.css',
				array(),
				'11.1.1'
			);

			wp_enqueue_script(
				'ar-onboarding-shepherd-js',
				$ar_plugin_root_url . 'assets/onboarding/vendor/shepherd.min.js',
				array(),
				'11.1.1',
				true
			);

			$dependencies = array( 'jquery', 'wp-i18n', 'ar-onboarding-shepherd-js' );
			wp_enqueue_script(
				$script_handle,
				$ar_plugin_root_url . 'assets/onboarding/onboarding.js',
				$dependencies,
				$ar_version,
				true
			);

			wp_set_script_translations( $script_handle, 'ar-for-wordpress' );

			$data = self::get_localized_data();

			wp_localize_script(
				$script_handle,
				'AROnboardingData',
				$data
			);
		}

		/**
		 * Retrieve onboarding structured data shared with the client.
		 *
		 * @return array
		 */
		protected static function get_localized_data() {
			$user_id        = get_current_user_id();
			$dismissed_tour = (bool) get_user_meta( $user_id, self::USER_META_TOUR_DISMISSED, true );
			$capabilities   = current_user_can( 'manage_options' );
			$screen         = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
			$screen_id      = $screen ? $screen->id : '';

			$content    = require __DIR__ . '/onboarding-data.php';
			$screen_key = self::determine_screen_key( $screen );
			$content    = self::prepare_content_for_screen( $content, $screen_key );

			return array(
				'content'     => $content,
				'user'        => array(
					'id'            => $user_id,
					'canManage'     => (bool) $capabilities,
					'tourDismissed' => $dismissed_tour,
				),
				'screen'      => array(
					'id' => $screen_id,
				),
				'strings'     => array(
					'openHelp'       => __( 'Open help panel', 'ar-for-wordpress' ),
					'resumeTour'     => __( 'Resume welcome tour', 'ar-for-wordpress' ),
					'startTour'      => __( 'Start guided tour', 'ar-for-wordpress' ),
					'searchDocs'     => __( 'Search documentation…', 'ar-for-wordpress' ),
					'next'           => __( 'Next', 'ar-for-wordpress' ),
					'previous'       => __( 'Previous', 'ar-for-wordpress' ),
					'finish'         => __( 'Finish', 'ar-for-wordpress' ),
					'panelTitle'     => __( 'AR for WordPress Assistant', 'ar-for-wordpress' ),
					'openDocs'       => __( 'View documentation', 'ar-for-wordpress' ),
					'instructions'   => __( 'Instructions', 'ar-for-wordpress' ),
					'quickStart'     => __( 'Quick start', 'ar-for-wordpress' ),
					'resources'      => __( 'Resources', 'ar-for-wordpress' ),
					'contactSupport' => __( 'Contact support', 'ar-for-wordpress' ),
					'close'          => __( 'Close panel', 'ar-for-wordpress' ),
					'noResults'      => __( 'No matches found.', 'ar-for-wordpress' ),
					'viewInTour'     => __( 'Show in tour', 'ar-for-wordpress' ),
				),
				'options'     => array(
					'dismissMetaKey' => self::USER_META_TOUR_DISMISSED,
				),
				'ajax'        => array(
					'url'    => admin_url( 'admin-ajax.php' ),
					'action' => 'ar_onboarding_toggle_tour',
					'nonce'  => wp_create_nonce( 'ar_onboarding_toggle' ),
				),
				'rest'        => array(
					'root'  => esc_url_raw( rest_url() ),
					'nonce' => wp_create_nonce( 'wp_rest' ),
				),
			);
		}

		/**
		 * Persist tour dismissal state for the current user.
		 */
		public static function handle_tour_state() {
			check_ajax_referer( 'ar_onboarding_toggle', 'nonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'Insufficient permissions.', 'ar-for-wordpress' ),
					),
					403
				);
			}

			$dismissed = isset( $_POST['dismissed'] ) ? sanitize_text_field( wp_unslash( $_POST['dismissed'] ) ) : '';
			$user_id   = get_current_user_id();

			if ( '1' === $dismissed ) {
				update_user_meta( $user_id, self::USER_META_TOUR_DISMISSED, '1' );
			} else {
				delete_user_meta( $user_id, self::USER_META_TOUR_DISMISSED );
			}

			wp_send_json_success(
				array(
					'dismissed' => '1' === $dismissed,
				)
			);
		}

		/**
		 * Determine which screen definition should be used for the current admin page.
		 *
		 * @param WP_Screen|null $screen Current screen.
		 *
		 * @return string
		 */
		protected static function determine_screen_key( $screen ) {
			if ( $screen && 'post' === $screen->base && 'armodels' === ( $screen->post_type ?? '' ) ) {
				return 'modelEditor';
			}

			if ( $screen && isset( $screen->id ) ) {
				if ( 0 === strpos( $screen->id, 'armodels_page_' ) ) {
					return 'settings';
				}

				if ( 'edit-armodels' === $screen->id ) {
					return 'list';
				}
			}

			if ( isset( $_GET['post_type'] ) && 'armodels' === sanitize_key( wp_unslash( $_GET['post_type'] ) ) ) {
				$pagenow = $GLOBALS['pagenow'] ?? '';

				if ( in_array( $pagenow, array( 'post-new.php', 'post.php' ), true ) ) {
					return 'modelEditor';
				}

				if ( 'edit.php' === $pagenow && isset( $_GET['page'] ) ) {
					return 'settings';
				}
			}

			return 'settings';
		}

		/**
		 * Merge the base onboarding content with screen-specific overrides.
		 *
		 * @param array  $content    Base content array.
		 * @param string $screen_key Screen identifier.
		 *
		 * @return array
		 */
		protected static function prepare_content_for_screen( array $content, $screen_key ) {
			if ( isset( $content['screens'] ) && is_array( $content['screens'] ) ) {
				$screen_data = $content['screens'][ $screen_key ] ?? $content['screens']['default'] ?? array();

				if ( isset( $screen_data['tourSteps'] ) ) {
					$content['tourSteps'] = $screen_data['tourSteps'];
				} else {
					$content['tourSteps'] = array();
				}

				if ( isset( $screen_data['faqSections'] ) ) {
					$content['faqSections'] = $screen_data['faqSections'];
				}

				if ( isset( $screen_data['quickLinks'] ) ) {
					$content['quickLinks'] = $screen_data['quickLinks'];
				}

				if ( isset( $screen_data['guides'] ) ) {
					$content['guides'] = $screen_data['guides'];
				} else {
					$content['guides'] = array();
				}
			}

			if ( ! isset( $content['tourSteps'] ) ) {
				$content['tourSteps'] = array();
			}

			if ( ! isset( $content['guides'] ) ) {
				$content['guides'] = array();
			}

			return $content;
		}
	}

	AR_Onboarding_Assistant::init();
}

