<?php
/**
 * Admin menu and settings screens.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Admin
 */
class Rsmspark_Content_Widgets_Admin {

	const PAGE_SLUG = 'rsmspark-content-widgets';

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'register_with_suite' ), 5 );
		add_action( 'admin_init', array( __CLASS__, 'maybe_save_settings' ) );
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 10 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_assets' ) );
		add_filter( 'admin_body_class', array( __CLASS__, 'admin_body_class' ) );
		add_filter( 'plugin_action_links_' . RSMSPARK_CONTENT_WIDGETS_BASENAME, array( __CLASS__, 'plugin_action_links' ) );
	}

	/**
	 * Register with the suite menu after translations are available.
	 *
	 * @return void
	 */
	public static function register_with_suite() {
		if ( ! class_exists( 'Rsmspark_Suite', false ) ) {
			return;
		}

		Rsmspark_Suite::register_plugin( 'content-widgets', __( 'Content Widgets', 'rsm-content-widgets' ), 55 );
	}

	/**
	 * Queue submenu order after Content Widgets and Buttons screens exist.
	 *
	 * @return void
	 */
	private static function register_submenu_order() {
		if ( ! function_exists( 'rsmspark_suite_register_submenu_order' ) ) {
			return;
		}

		rsmspark_suite_register_submenu_order(
			'content-widgets',
			array(
				'rsmspark-suite-content-widgets',
				self::PAGE_SLUG,
				Rsmspark_Buttons_Admin::PAGE_SLUG,
				Rsmspark_Testimonials_Admin::MENU_SLUG,
			)
		);
	}

	/**
	 * @param array<string, string> $links Plugin action links.
	 * @return array<string, string>
	 */
	public static function plugin_action_links( $links ) {
		array_unshift(
			$links,
			sprintf(
				'<a href="%s">%s</a>',
				esc_url( self::settings_url() ),
				esc_html__( 'Settings', 'rsm-content-widgets' )
			)
		);
		return $links;
	}

	/**
	 * @param string               $tab   Active tab.
	 * @param array<string, mixed> $extra Extra query args.
	 * @return string
	 */
	public static function settings_url( $tab = 'general', $extra = array() ) {
		$args = array_merge(
			array(
				'page' => self::PAGE_SLUG,
				'tab'  => sanitize_key( $tab ),
			),
			$extra
		);
		return add_query_arg( $args, admin_url( 'admin.php' ) );
	}

	/**
	 * Settings under the shared RSM suite menu when available.
	 *
	 * @return void
	 */
	public static function register_menu() {
		$capability = 'manage_options';
		$callback   = array( __CLASS__, 'render_settings' );

		if ( class_exists( 'Rsmspark_Suite', false ) ) {
			Rsmspark_Suite::register_parent();
			Rsmspark_Suite::add_section_heading( 'content-widgets' );

			add_submenu_page(
				Rsmspark_Suite::parent_slug(),
				__( 'Content Widgets', 'rsm-content-widgets' ),
				__( 'Content Widgets', 'rsm-content-widgets' ),
				$capability,
				self::PAGE_SLUG,
				$callback
			);

			if ( class_exists( 'Rsmspark_Buttons_Admin', false ) ) {
				Rsmspark_Buttons_Admin::register_menu();
			}

			self::register_submenu_order();
			return;
		}

		add_menu_page(
			__( 'Content Widgets', 'rsm-content-widgets' ),
			__( 'Content Widgets', 'rsm-content-widgets' ),
			$capability,
			self::PAGE_SLUG,
			$callback,
			'dashicons-screenoptions',
			26
		);
	}

	/**
	 * @return void
	 */
	public static function render_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'rsm-content-widgets' ) );
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin notice flag; no state change.
		$updated = isset( $_GET['updated'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['updated'] ) ) : '';
		if ( '1' === $updated ) {
			rsmspark_suite_render_admin_notice( __( 'Settings saved.', 'rsm-content-widgets' ) );
		}

		$settings = Rsmspark_Content_Widgets_Settings::get();
		include RSMSPARK_CONTENT_WIDGETS_PATH . 'admin/views/settings.php';
	}

	/**
	 * @param string $hook Admin hook suffix.
	 * @return void
	 */
	public static function enqueue_admin_assets( $hook ) {
		if ( ! self::is_content_widgets_admin_screen( $hook ) ) {
			return;
		}

		self::enqueue_admin_brand_assets();
	}

	/**
	 * @param string $classes Admin body classes.
	 * @return string
	 */
	public static function admin_body_class( $classes ) {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

		if ( $screen && false !== strpos( (string) $screen->id, 'rsm-content-widgets' ) ) {
			$classes .= ' rsmspark-suite-admin-screen';
		}

		return $classes;
	}

	/**
	 * @param string $hook Admin hook suffix.
	 * @return bool
	 */
	private static function is_content_widgets_admin_screen( $hook ) {
		if ( false !== strpos( (string) $hook, self::PAGE_SLUG ) ) {
			return true;
		}

		if ( function_exists( 'get_current_screen' ) ) {
			$screen = get_current_screen();
			return $screen && ! empty( $screen->id ) && false !== strpos( (string) $screen->id, self::PAGE_SLUG );
		}

		return false;
	}

	/**
	 * Shared Content Widgets admin branding styles.
	 *
	 * @return void
	 */
	public static function enqueue_admin_brand_assets() {
		if ( function_exists( 'rsmspark_suite_enqueue_admin_styles' ) ) {
			rsmspark_suite_enqueue_admin_styles( RSMSPARK_CONTENT_WIDGETS_PATH . 'rsm-shared', RSMSPARK_CONTENT_WIDGETS_URL . 'rsm-shared', RSMSPARK_CONTENT_WIDGETS_VERSION );
		} elseif ( class_exists( 'Rsmspark_Suite', false ) ) {
			Rsmspark_Suite::enqueue_local_admin_styles( RSMSPARK_CONTENT_WIDGETS_PATH . 'rsm-shared', RSMSPARK_CONTENT_WIDGETS_URL . 'rsm-shared', RSMSPARK_CONTENT_WIDGETS_VERSION );
		}

		$admin_ui_js = RSMSPARK_CONTENT_WIDGETS_PATH . 'rsm-shared/assets/js/admin-suite-ui.js';
		if ( is_readable( $admin_ui_js ) ) {
			wp_enqueue_script(
				'rsmspark-suite-admin-ui',
				RSMSPARK_CONTENT_WIDGETS_URL . 'rsm-shared/assets/js/admin-suite-ui.js',
				array(),
				RSMSPARK_CONTENT_WIDGETS_VERSION,
				true
			);
		} elseif ( defined( 'RSMSPARK_SUITE_URL' ) && defined( 'RSMSPARK_SUITE_VERSION' ) ) {
			$suite_ui_js = ( defined( 'RSMSPARK_SUITE_DIR' ) ? RSMSPARK_SUITE_DIR : '' ) . 'assets/js/admin-suite-ui.js';
			if ( '' !== $suite_ui_js && is_readable( $suite_ui_js ) ) {
				wp_enqueue_script(
					'rsmspark-suite-admin-ui',
					RSMSPARK_SUITE_URL . 'assets/js/admin-suite-ui.js',
					array(),
					RSMSPARK_SUITE_VERSION,
					true
				);
			}
		}
		wp_enqueue_style(
			'rsmspark-content-widgets-admin',
			RSMSPARK_CONTENT_WIDGETS_URL . 'assets/css/admin-widgets.css',
			array( 'rsmspark-suite-admin', 'rsmspark-suite-buttons' ),
			RSMSPARK_CONTENT_WIDGETS_VERSION
		);
		wp_enqueue_style(
			'rsmspark-content-widgets-admin-hub',
			RSMSPARK_CONTENT_WIDGETS_URL . 'assets/css/admin-hub.css',
			array( 'rsmspark-suite-admin', 'rsmspark-suite-buttons', 'rsmspark-content-widgets-admin' ),
			RSMSPARK_CONTENT_WIDGETS_VERSION
		);
	}

	/**
	 * @return void
	 */
	public static function maybe_save_settings() {
		if ( ! isset( $_POST['rsmspark_content_widgets_settings_nonce'] ) ) {
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['rsmspark_content_widgets_settings_nonce'] ) ), 'rsmspark_content_widgets_save_settings' ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to save these settings.', 'rsm-content-widgets' ) );
		}

		$tab     = isset( $_POST['rsm_settings_tab'] ) ? sanitize_key( wp_unslash( (string) $_POST['rsm_settings_tab'] ) ) : 'general';
		$current = Rsmspark_Content_Widgets_Settings::get();

		if ( 'general' === $tab ) {
			$current['enabled']             = isset( $_POST['rsmspark_content_widgets_enabled'] );
			$current['output_shortcodes']   = isset( $_POST['rsmspark_content_widgets_output_shortcodes'] );
			$current['output_blocks']       = isset( $_POST['rsmspark_content_widgets_output_blocks'] );
			$current['output_siteorigin']   = isset( $_POST['rsmspark_content_widgets_output_siteorigin'] );
			$current['primary_color']       = isset( $_POST['rsmspark_content_widgets_primary_color'] ) ? sanitize_hex_color( wp_unslash( (string) $_POST['rsmspark_content_widgets_primary_color'] ) ) : $current['primary_color'];
			$current['border_radius']       = isset( $_POST['rsmspark_content_widgets_border_radius'] ) ? absint( $_POST['rsmspark_content_widgets_border_radius'] ) : $current['border_radius'];
			$load                           = isset( $_POST['rsmspark_content_widgets_load_assets'] ) ? sanitize_key( wp_unslash( (string) $_POST['rsmspark_content_widgets_load_assets'] ) ) : 'conditional';
			$current['load_assets']         = in_array( $load, array( 'always', 'conditional', 'never' ), true ) ? $load : 'conditional';
		}

		if ( 'widgets' === $tab ) {
			$defs    = Rsmspark_Content_Widgets_Registry::definitions();
			$enabled = array();
			foreach ( array_keys( $defs ) as $widget_id ) {
				$field = 'rsmspark_content_widgets_widget_' . $widget_id;
				$enabled[ $widget_id ] = isset( $_POST[ $field ] );
			}
			$current['widgets_enabled'] = $enabled;
		}

		if ( 'editor' === $tab ) {
			$current['editor_media_row']       = isset( $_POST['rsmspark_content_widgets_editor_media_row'] );
			$current['editor_use_rsm_media']   = isset( $_POST['rsmspark_content_widgets_editor_use_rsm_media'] );
			$current['editor_calendar_button'] = isset( $_POST['rsmspark_content_widgets_editor_calendar_button'] );

			if ( class_exists( 'Rsmspark_Rich_Text_Standards', false ) ) {
				if ( isset( $_POST['rsmspark_editor_reset_standards'] ) ) {
					Rsmspark_Rich_Text_Standards::reset_to_defaults();
					$redirect = class_exists( 'Rsmspark_Migration', false )
						? Rsmspark_Migration::settings_url( self::PAGE_SLUG, $tab, array( 'reset' => '1' ) )
						: self::settings_url( $tab, array( 'reset' => '1' ) );

					Rsmspark_Content_Widgets_Settings::save( $current );
					wp_safe_redirect( $redirect );
					exit;
				}

				Rsmspark_Rich_Text_Standards::save_from_request( $_POST );
			}
		}

		if ( 'advanced' === $tab ) {
			$current['debug_mode']              = isset( $_POST['rsmspark_content_widgets_debug_mode'] );
			$current['per_widget_assets']       = isset( $_POST['rsmspark_content_widgets_per_widget_assets'] );
			$current['disable_all_styling']     = isset( $_POST['rsmspark_content_widgets_disable_all_styling'] );
			$current['experimental_blocks']     = isset( $_POST['rsmspark_content_widgets_experimental_blocks'] );
			$current['legacy_shortcode_support'] = isset( $_POST['rsmspark_content_widgets_legacy_shortcodes'] );
		}

		Rsmspark_Content_Widgets_Settings::save( $current );

		$redirect = class_exists( 'Rsmspark_Migration', false )
			? Rsmspark_Migration::settings_url( self::PAGE_SLUG, $tab, array( 'updated' => '1' ) )
			: self::settings_url( $tab, array( 'updated' => '1' ) );

		wp_safe_redirect( $redirect );
		exit;
	}
}
