<?php
/**
 * Sports Leagues :: Shortcode
 *
 * @since   0.5.11
 * @package Sports_Leagues
 */

/**
 * Main shortcode controller.
 *
 * Handles TinyMCE button, REST API for form loading, and legacy AJAX endpoints.
 *
 * @since 0.5.11
 */
class Sports_Leagues_Shortcode {

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->hooks();
	}

	/**
	 * Initiate hooks.
	 */
	public function hooks() {

		// Initialize MCE button
		add_action( 'admin_init', [ $this, 'mce_button' ] );

		add_action( 'after_wp_tiny_mce', [ $this, 'tinymce_l10n_vars' ] );
		add_action( 'enqueue_block_assets', [ $this, 'add_scripts_to_gutenberg' ] );

		// REST API route for shortcode form.
		add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );

		// Ajax request (legacy - kept for backwards compatibility).
		add_action( 'wp_ajax_sl_shortcodes_modal_structure', [ $this, 'get_modal_structure' ] );
		add_action( 'wp_ajax_sl_shortcodes_modal_form', [ $this, 'get_modal_form' ] );
	}

	/**
	 * Register REST API routes.
	 *
	 * @since 0.14.1
	 */
	public function register_rest_routes() {
		register_rest_route(
			'sports-leagues',
			'/shortcode-form/(?P<shortcode>[a-z0-9_-]+)',
			[
				'methods'             => 'GET',
				'callback'            => [ $this, 'rest_get_shortcode_form' ],
				'permission_callback' => function () {
					return current_user_can( 'edit_posts' ) || current_user_can( 'edit_pages' );
				},
				'args'                => [
					'shortcode' => [
						'required'          => true,
						'type'              => 'string',
						'sanitize_callback' => 'sanitize_key',
					],
				],
			]
		);
	}

	/**
	 * REST callback: Get shortcode form HTML.
	 *
	 * @param WP_REST_Request $request REST request.
	 *
	 * @return WP_REST_Response
	 * @since 0.14.1
	 */
	public function rest_get_shortcode_form( WP_REST_Request $request ) {
		$shortcode = $request->get_param( 'shortcode' );

		if ( empty( $shortcode ) ) {
			return new WP_REST_Response(
				[ 'message' => 'Shortcode parameter required' ],
				400
			);
		}

		ob_start();

		/**
		 * Render form with shortcode options (core shortcodes).
		 *
		 * @since 0.14.1
		 */
		do_action( 'sports-leagues/shortcode/get_shortcode_form_' . $shortcode );

		/**
		 * Render form with shortcode options (premium shortcodes).
		 *
		 * @since 0.14.1
		 */
		do_action( 'sports-leagues/shortcode-pro/get_shortcode_form_' . $shortcode );

		/**
		 * Hook: sports-leagues/shortcodes/modal_form_shortcode
		 *
		 * Legacy hook that triggers premium shortcode forms.
		 *
		 * @since 0.5.13
		 * @deprecated 0.14.1 Use shortcode-specific hooks instead.
		 */
		do_action( 'sports-leagues/shortcodes/modal_form_shortcode', $shortcode );

		$html_output = ob_get_clean();

		return new WP_REST_Response(
			[
				'success' => true,
				'html'    => $html_output,
			],
			200
		);
	}

	/**
	 * Filter Functions with Hooks
	 *
	 * @since 0.5.11
	 */
	public function mce_button() {

		// Check if user have permission
		if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
			return;
		}

		// Check if WYSIWYG is enabled
		if ( 'true' === get_user_option( 'rich_editing' ) ) {
			add_filter( 'mce_external_plugins', [ $this, 'add_tinymce_plugin' ] );
			add_filter( 'mce_buttons', [ $this, 'register_tinymce_button' ] );
		}
	}

	/**
	 * @param $plugin_array
	 *
	 * @return mixed
	 * @since 0.5.11
	 */
	public function add_tinymce_plugin( $plugin_array ) {
		$plugin_array['sports_leagues'] = Sports_Leagues::url( 'admin/js/tinymce-plugin.js?ver=' . Sports_Leagues::VERSION );
		return $plugin_array;
	}

	/**
	 * @param $buttons
	 *
	 * @return mixed
	 * @since 0.5.11
	 */
	public function register_tinymce_button( $buttons ) {
		array_push( $buttons, 'sports_leagues_button' );
		return $buttons;
	}

	/**
	 * Load TinyMCE localized vars
	 *
	 * @since 0.5.11
	 * @since 0.14.1 Added shortcode options and additional l10n strings for Alpine component.
	 */
	public function tinymce_l10n_vars() {

		// Get core shortcode options (sorted alphabetically).
		$core_options = apply_filters( 'sports-leagues/shortcode/get_shortcode_options', [] );

		if ( ! empty( $core_options ) && is_array( $core_options ) ) {
			asort( $core_options );
		}

		// Get premium shortcode options (sorted alphabetically).
		$premium_options = apply_filters( 'sports-leagues/shortcode-pro/get_shortcode_options', [] );

		if ( ! empty( $premium_options ) && is_array( $premium_options ) ) {
			asort( $premium_options );
		}

		$vars = [
			'sports_leagues'            => esc_html__( 'Sports Leagues', 'sports-leagues' ),
			'nonce'                     => wp_create_nonce( 'sl_shortcodes_nonce' ),
			'shortcode_options'         => $core_options,
			'shortcode_options_premium' => $premium_options,
			'shortcode'                 => esc_html__( 'Shortcode', 'sports-leagues' ),
			'select'                    => esc_html__( 'select', 'sports-leagues' ),
			'insert'                    => esc_html__( 'Insert Shortcode', 'sports-leagues' ),
			'copy'                      => esc_html__( 'Copy', 'sports-leagues' ),
			'cancel'                    => esc_html__( 'Close', 'sports-leagues' ),
			'copied_to_clipboard'       => esc_html__( 'Copied to Clipboard', 'sports-leagues' ),
		];

		?>
		<script type="text/javascript">
			var _sl_shortcodes_l10n = <?php echo wp_json_encode( $vars ); ?>;
		</script>
		<?php
	}

	/**
	 * Get results for ajax request.
	 *
	 * @since 0.5.11
	 */
	public function get_modal_structure() {

		// Check if our nonce is set.
		if ( ! isset( $_POST['nonce'] ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['nonce'], 'sl_shortcodes_nonce' ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		// Check the user's permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		ob_start();
		?>
		<div class="anwp-sl-shortcode-modal__header">
			<label for="anwp-sl-shortcode-modal__selector"><?php echo esc_html__( 'Shortcode', 'sports-leagues' ); ?></label>
			<select id="anwp-sl-shortcode-modal__selector">
				<option value="">- <?php echo esc_html__( 'select', 'sports-leagues' ); ?> -</option>
				<option value="games"><?php echo esc_html__( 'Games', 'sports-leagues' ); ?></option>
				<option value="players-stats"><?php echo esc_html__( 'Players Stats', 'sports-leagues' ); ?></option>
				<option value="standing"><?php echo esc_html__( 'Standing Table', 'sports-leagues' ); ?></option>
				<option value="roster"><?php echo esc_html__( 'Roster', 'sports-leagues' ); ?></option>
				<option value="teams"><?php echo esc_html__( 'Teams', 'sports-leagues' ); ?></option>
				<option value="tournament-header"><?php echo esc_html__( 'Tournament Header', 'sports-leagues' ); ?></option>
				<option value="tournament-list"><?php echo esc_html__( 'Tournament List', 'sports-leagues' ); ?></option>
				<?php
				/**
				 * Hook: sports-leagues/shortcodes/selector_bottom
				 *
				 * @since 0.5.11
				 */
				do_action( 'sports-leagues/shortcodes/selector_bottom' );
				?>
			</select>
			<span class="spinner"></span>
		</div>
		<div class="anwp-sl-shortcode-modal__content"></div>
		<div class="anwp-sl-shortcode-modal__footer">
			<button id="anwp-sl-shortcode-modal__cancel" class="button"><?php echo esc_html__( 'Close', 'sports-leagues' ); ?></button>
			<button id="anwp-sl-shortcode-modal__insert" class="button button-primary"><?php echo esc_html__( 'Insert Shortcode', 'sports-leagues' ); ?></button>
		</div>
		<?php
		$html_output = ob_get_clean();

		wp_send_json_success( [ 'html' => $html_output ] );
	}

	/**
	 * Get results for ajax request.
	 *
	 * Legacy AJAX endpoint for backwards compatibility.
	 * Forms are now rendered by individual shortcode classes via the action hook.
	 *
	 * @since 0.5.11
	 * @since 0.14.1 Simplified to use action hooks from shortcode classes.
	 */
	public function get_modal_form() {

		// Check if our nonce is set.
		if ( ! isset( $_POST['nonce'] ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( $_POST['nonce'], 'sl_shortcodes_nonce' ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		// Check the user's permissions.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Error : Unauthorized action' );
		}

		$shortcode = isset( $_POST['shortcode'] ) ? sanitize_key( $_POST['shortcode'] ) : '';

		if ( ! $shortcode ) {
			wp_send_json_error( 'Error : Incorrect Data' );
		}

		ob_start();

		/**
		 * Render form with shortcode options (core shortcodes).
		 *
		 * Individual shortcode classes hook into this action via their constructor
		 * to render their declarative field definitions.
		 *
		 * @since 0.14.1
		 */
		do_action( 'sports-leagues/shortcode/get_shortcode_form_' . $shortcode );

		/**
		 * Hook: sports-leagues/shortcodes/modal_form_shortcode
		 *
		 * Legacy hook that triggers premium shortcode forms.
		 *
		 * @since 0.5.13
		 */
		do_action( 'sports-leagues/shortcodes/modal_form_shortcode', $shortcode );

		$html_output = ob_get_clean();

		wp_send_json_success( [ 'html' => $html_output ] );
	}


	/**
	 * Added TinyMCE scripts to the Gutenberg Classic editor Block
	 *
	 * @since 0.5.11
	 */
	public function add_scripts_to_gutenberg() {
		global $current_screen;

		$is_gutenberg_old = function_exists( 'is_gutenberg_page' ) && is_gutenberg_page();
		$is_gutenberg_new = $current_screen instanceof WP_Screen && method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor();

		if ( is_admin() && ( $is_gutenberg_new || $is_gutenberg_old ) ) {
			$this->tinymce_l10n_vars();
		}
	}
}
