<?php

namespace CustomNavMenuItemsNewTab;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'custom-nav-menu-items-new-tab';
	private const MODULE_VERSION = '1.0.2';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'New Tab for custom menu items', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Selected custom menu links open in a new tab with safe rel attributes.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'frontend' ];
	}

	protected function registerHooks(): void {
		add_filter( 'nav_menu_link_attributes', [ $this, 'addAttributesToMenuItem' ], 10, 3 );

		if ( is_admin() ) {
			add_action( 'wp_nav_menu_item_custom_fields', [ $this, 'addOpenInNewTabField' ], 10, 4 );
			add_action( 'wp_update_nav_menu_item', [ $this, 'saveOpenInNewTabStatus' ], 10, 3 );
		}
	}

	public function addOpenInNewTabField( int $item_id, object $menu_item, int $depth, object $args ): void {
		if ( 'custom' !== $menu_item->object ) {
			return;
		}

		$target_blank = get_post_meta( $item_id, '_menu_item_target_blank', true );
		$is_checked   = ( $target_blank === '1' );
		?>
		<p class="field-target_blank description-wide">
			<label for="edit-menu-item-target-blank-<?php echo esc_attr( $item_id ); ?>">
				<input
					type="checkbox"
					id="edit-menu-item-target-blank-<?php echo esc_attr( $item_id ); ?>"
					name="menu-item-target-blank[<?php echo esc_attr( $item_id ); ?>]"
					value="1"
					<?php checked( $is_checked, true ); ?>
				/>
				<?php esc_html_e( 'Open link in new tab and add rel="noopener noreferrer nofollow" attribute.', 'wp-powersuite' ); ?>
			</label>
		</p>
		<?php
	}

	public function saveOpenInNewTabStatus( int $menu_id, int $menu_item_db_id, array $args ): void {
		if ( ! current_user_can( 'edit_theme_options' ) ) {
			return;
		}

		if ( ! isset( $_POST['update-nav-menu-nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['update-nav-menu-nonce'] ) ), 'update-nav_menu' ) ) {
			return;
		}

		$posted = $_POST['menu-item-target-blank'] ?? [];
		$on     = is_array( $posted ) && isset( $posted[ $menu_item_db_id ] ) && (string) wp_unslash( $posted[ $menu_item_db_id ] ) === '1';
		update_post_meta( $menu_item_db_id, '_menu_item_target_blank', $on ? '1' : '0' );
	}

	public function addAttributesToMenuItem( array $atts, object $menu_item, object $args ): array {
		if ( isset( $menu_item->object ) && $menu_item->object !== 'custom' ) {
			return $atts;
		}

		if ( get_post_meta( $menu_item->ID, '_menu_item_target_blank', true ) !== '1' ) {
			return $atts;
		}

		$atts['target'] = '_blank';

		// Merge required tokens into any existing rel (preserve sponsored/ugc/etc.).
		$rel_tokens = ( isset( $atts['rel'] ) && is_string( $atts['rel'] ) )
			? array_values( array_filter( (array) preg_split( '/\s+/', trim( $atts['rel'] ) ) ) )
			: [];
		foreach ( [ 'noopener', 'noreferrer', 'nofollow' ] as $token ) {
			if ( ! in_array( $token, $rel_tokens, true ) ) {
				$rel_tokens[] = $token;
			}
		}
		$atts['rel'] = implode( ' ', $rel_tokens );

		return $atts;
	}
}
