<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class UM_Elementor_Admin_Settings {

	const PAGE_SLUG                    = 'um-elementor-settings';
	const SETUP_NOTICE_OPTION          = 'um_elementor_show_setup_notice';
	const SETUP_NOTICE_DISMISSED_META  = 'um_elementor_setup_notice_dismissed';
	const SETUP_NOTICE_AJAX            = 'um_elementor_dismiss_setup_notice';

	public function __construct() {
		if ( $this->should_defer_to_pro() ) {
			return;
		}

		add_action( 'admin_menu', [ $this, 'add_settings_page' ] );
		add_action( 'um_extend_admin_menu', [ $this, 'add_um_submenu' ] );
		add_action( 'admin_menu', [ $this, 'add_elementor_submenu' ], 999 );
		add_action( 'admin_menu', [ $this, 'add_fallback_menu' ], 999 );
		add_action( 'admin_init', [ $this, 'register_settings' ] );
		add_action( 'admin_head', [ $this, 'admin_styles' ] );
		add_action( 'admin_notices', [ $this, 'render_setup_notice' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_setup_notice_assets' ] );
		add_action( 'wp_ajax_' . self::SETUP_NOTICE_AJAX, [ $this, 'handle_setup_notice_dismiss' ] );
		add_filter( 'plugin_action_links_' . plugin_basename( UM_USER_ELEMENTOR_PATH . 'um-addon-elementor.php' ), [ $this, 'add_plugin_action_links' ] );
	}

	private function should_defer_to_pro(): bool {
		return defined( 'UMEP_VERSION' );
	}

	public static function get_setup_page_url(): string {
		return admin_url( 'admin.php?page=' . self::PAGE_SLUG );
	}

	public function add_settings_page(): void {
		add_options_page(
			__( 'Elementor Setup', 'ultimate-member-widgets-for-elementor' ),
			__( 'Elementor Setup', 'ultimate-member-widgets-for-elementor' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_settings_page' ]
		);
	}

	public function add_um_submenu(): void {
		add_submenu_page(
			'ultimatemember',
			__( 'Build Member Pages with Elementor', 'ultimate-member-widgets-for-elementor' ),
			__( 'Elementor Setup', 'ultimate-member-widgets-for-elementor' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_settings_page' ]
		);
	}

	public function add_elementor_submenu(): void {
		$parent = $this->get_elementor_menu_slug();
		if ( ! $parent ) {
			return;
		}

		add_submenu_page(
			$parent,
			__( 'Ultimate Member Pages', 'ultimate-member-widgets-for-elementor' ),
			__( 'Member Pages', 'ultimate-member-widgets-for-elementor' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_settings_page' ]
		);
	}

	public function add_fallback_menu(): void {
		if ( function_exists( 'UM' ) ) {
			return;
		}

		add_menu_page(
			__( 'Build Member Pages with Elementor', 'ultimate-member-widgets-for-elementor' ),
			__( 'Elementor Setup', 'ultimate-member-widgets-for-elementor' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render_settings_page' ],
			'dashicons-admin-users',
			58
		);
	}

	private function get_elementor_menu_slug(): ?string {
		global $menu;

		foreach ( [ 'elementor-home', 'elementor' ] as $slug ) {
			if ( isset( $menu ) && is_array( $menu ) ) {
				foreach ( $menu as $item ) {
					if ( isset( $item[2] ) && $slug === $item[2] ) {
						return $slug;
					}
				}
			}
		}

		return null;
	}

	public function register_settings(): void {
		register_setting(
			'um_elementor_settings_group',
			'um_use_new_query_engine',
			[
				'type'              => 'boolean',
				'default'           => true,
				'sanitize_callback' => static function ( $value ) {
					return ! empty( $value ) ? 1 : 0;
				},
			]
		);

		add_settings_section(
			'um_elementor_advanced_section',
			__( 'Advanced', 'ultimate-member-widgets-for-elementor' ),
			[ $this, 'render_advanced_section_intro' ],
			self::PAGE_SLUG
		);

		add_settings_field(
			'um_use_new_query_engine',
			__( 'Use New Query Engine', 'ultimate-member-widgets-for-elementor' ),
			[ $this, 'render_query_engine_toggle' ],
			self::PAGE_SLUG,
			'um_elementor_advanced_section'
		);
	}

	public function render_advanced_section_intro(): void {
		echo '<p class="description">';
		esc_html_e( 'Optional settings. Configure member pages in the cards above.', 'ultimate-member-widgets-for-elementor' );
		echo '</p>';
	}

	public function render_query_engine_toggle(): void {
		$stored  = get_option( 'um_use_new_query_engine', null );
		$enabled = null === $stored ? true : (bool) rest_sanitize_boolean( $stored );
		?>
		<input type="hidden" name="um_use_new_query_engine" value="0" />
		<label>
			<input type="checkbox" name="um_use_new_query_engine" value="1" <?php checked( $enabled ); ?> />
			<?php esc_html_e( 'Enable the high-performance query engine.', 'ultimate-member-widgets-for-elementor' ); ?>
		</label>
		<p class="description">
			<?php esc_html_e( 'Disable only if you need the legacy query path for backward compatibility.', 'ultimate-member-widgets-for-elementor' ); ?>
		</p>
		<?php
	}

	private function is_setup_screen( $screen ): bool {
		if ( ! $screen ) {
			return false;
		}

		return str_contains( $screen->id, self::PAGE_SLUG );
	}

	public function admin_styles(): void {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $this->is_setup_screen( $screen ) ) {
			return;
		}
		?>
		<style>
			.umwfe-setup-wrap { max-width: 1120px; }
			.umwfe-setup-wrap > h1 { margin-bottom: 16px; }

			.umwfe-pro-teaser {
				margin: 0 0 14px;
				padding: 10px 14px;
				background: #f6f7f7;
				border-left: 3px solid #2271b1;
				font-size: 13px;
			}

			/* Hero */
			.umwfe-setup-hero {
				margin: 0 0 20px;
				padding: 18px 20px;
				background: #fff;
				border: 1px solid #c3c4c7;
				border-radius: 8px;
				box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
			}
			.umwfe-setup-hero-top {
				display: flex;
				align-items: center;
				gap: 18px;
			}
			.umwfe-setup-progress-ring {
				position: relative;
				flex-shrink: 0;
				width: 64px;
				height: 64px;
			}
			.umwfe-setup-progress-ring svg {
				width: 64px;
				height: 64px;
				transform: rotate(-90deg);
			}
			.umwfe-ring-bg {
				fill: none;
				stroke: #dcdcde;
				stroke-width: 3;
			}
			.umwfe-ring-fill {
				fill: none;
				stroke: #007017;
				stroke-width: 3;
				stroke-linecap: round;
				transition: stroke-dasharray 0.4s ease;
			}
			.umwfe-ring-label {
				position: absolute;
				inset: 0;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 11px;
				line-height: 1.1;
				color: #1d2327;
			}
			.umwfe-ring-label strong { font-size: 18px; font-weight: 600; }
			.umwfe-ring-label small { color: #646970; font-size: 10px; }
			.umwfe-setup-tagline {
				margin: 0 0 6px;
				font-size: 15px;
				font-weight: 500;
				color: #1d2327;
			}
			.umwfe-setup-quicklinks { font-size: 12px; color: #646970; }
			.umwfe-setup-quicklinks a { text-decoration: none; }
			.umwfe-setup-pills {
				display: flex;
				flex-wrap: wrap;
				gap: 8px 12px;
				margin: 14px 0 0;
				padding: 0;
				list-style: none;
			}
			.umwfe-setup-pills li {
				display: inline-flex;
				align-items: center;
				gap: 4px;
				margin: 0;
				padding: 4px 10px;
				font-size: 12px;
				color: #50575e;
				background: #f6f7f7;
				border-radius: 999px;
			}
			.umwfe-setup-pills .dashicons {
				width: 16px;
				height: 16px;
				font-size: 16px;
				color: #787c82;
			}
			.umwfe-setup-warnings {
				margin: 12px 0 0;
				padding: 8px 12px;
				list-style: none;
				font-size: 12px;
				color: #8a6d00;
				background: #fff8e5;
				border-radius: 4px;
			}
			.umwfe-setup-warnings li { margin: 0; }
			.umwfe-setup-warnings li + li { margin-top: 4px; }

			/* Page cards */
			.umwfe-page-cards {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
				gap: 14px;
				margin: 0 0 8px;
			}
			.umwfe-page-cards-empty {
				grid-column: 1 / -1;
				margin: 0;
				padding: 16px;
				background: #fff;
				border: 1px solid #c3c4c7;
				border-radius: 8px;
			}
			.umwfe-page-card {
				display: flex;
				flex-direction: column;
				margin: 0;
				padding: 14px 16px;
				background: #fff;
				border: 1px solid #c3c4c7;
				border-radius: 8px;
				box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
			}
			.umwfe-page-card-action {
				border-left: 3px solid #dba617;
			}
			.umwfe-page-card-ready {
				border-left: 3px solid #007017;
			}
			.umwfe-page-card-pro {
				border-left: 3px solid #8c8f94;
				background: #f6f7f7;
				opacity: 0.92;
			}
			.umwfe-page-card-pro .umwfe-page-card-icon {
				color: #8c8f94;
				background: #e8e8e9;
			}
			.umwfe-page-card-pro .umwfe-page-card-title h2,
			.umwfe-page-card-pro .umwfe-page-card-url,
			.umwfe-page-card-pro .umwfe-page-card-hint {
				color: #646970;
			}
			.umwfe-page-card-pro .umwfe-page-card-widget {
				color: #50575e;
			}
			.umwfe-badge-pro {
				color: #3c434a;
				background: #dcdcde;
			}
			.umwfe-page-card-head {
				display: flex;
				align-items: flex-start;
				gap: 10px;
			}
			.umwfe-page-card-icon {
				flex-shrink: 0;
				width: 36px;
				height: 36px;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 18px;
				color: #50575e;
				background: #f0f0f1;
				border-radius: 8px;
			}
			.umwfe-page-card-icon::before {
				width: 18px;
				height: 18px;
				font-size: 18px;
			}
			.umwfe-page-card-title {
				flex: 1;
				min-width: 0;
			}
			.umwfe-page-card-title h2 {
				margin: 0;
				font-size: 14px;
				font-weight: 600;
				line-height: 1.3;
			}
			.umwfe-page-card-url {
				display: inline-block;
				margin-top: 2px;
				font-size: 12px;
				text-decoration: none;
				color: #646970;
			}
			.umwfe-badge {
				flex-shrink: 0;
				padding: 2px 8px;
				font-size: 11px;
				font-weight: 600;
				line-height: 1.5;
				border-radius: 999px;
				white-space: nowrap;
			}
			.umwfe-badge-um_widget { color: #00450c; background: #e6f2e8; }
			.umwfe-badge-shortcode_only { color: #8a1f1f; background: #fcebea; }
			.umwfe-badge-elementor_no_um { color: #8a6d00; background: #fff8e5; }
			.umwfe-badge-classic { color: #50575e; background: #f0f0f1; }
			.umwfe-badge-not_set,
			.umwfe-badge-missing { color: #50575e; background: #f0f0f1; }
			.umwfe-page-card-widget {
				display: flex;
				align-items: center;
				gap: 4px;
				margin: 10px 0 0;
				font-size: 12px;
				color: #646970;
			}
			.umwfe-page-card-widget .dashicons {
				width: 14px;
				height: 14px;
				font-size: 14px;
			}
			.umwfe-page-card-hint {
				margin: 6px 0 0;
				font-size: 12px;
				line-height: 1.4;
				color: #787c82;
			}
			.umwfe-page-card-actions {
				display: flex;
				flex-wrap: wrap;
				gap: 6px;
				margin-top: auto;
				padding-top: 12px;
			}
			.umwfe-page-card-actions .button { margin: 0; }

			.umwfe-setup-advanced { margin-top: 28px; padding-top: 8px; border-top: 1px solid #dcdcde; }

			@media (max-width: 600px) {
				.umwfe-setup-hero-top { flex-direction: column; align-items: flex-start; }
				.umwfe-page-cards { grid-template-columns: 1fr; }
			}
		</style>
		<?php
	}

	public function render_settings_page(): void {
		?>
		<div class="wrap umwfe-setup-wrap">
			<h1><?php esc_html_e( 'Elementor setup', 'ultimate-member-widgets-for-elementor' ); ?></h1>
			<?php $this->render_pro_upgrade_section(); ?>
			<?php
			if ( class_exists( '\UM_Elementor\Helpers\UM_Core_Pages' ) ) {
				\UM_Elementor\Helpers\UM_Core_Pages::render_dashboard_table();
			}
			?>
			<div class="umwfe-setup-advanced">
				<form method="post" action="options.php">
					<?php
					settings_fields( 'um_elementor_settings_group' );
					do_settings_sections( self::PAGE_SLUG );
					submit_button( __( 'Save settings', 'ultimate-member-widgets-for-elementor' ) );
					?>
				</form>
			</div>
		</div>
		<?php
	}

	private function render_pro_upgrade_section(): void {
		if ( ! class_exists( 'UM_Elementor_Pro_Links' ) ) {
			return;
		}
		$upgrade_url = UM_Elementor_Pro_Links::upgrade_url( 'setup-page' );
		?>
		<p class="umwfe-pro-teaser">
			<?php
			printf(
				wp_kses(
					/* translators: %s: upgrade URL */
					__( 'Need profile builder, directory styler, and advanced layouts? <a href="%s">Get Pro</a>.', 'ultimate-member-widgets-for-elementor' ),
					[ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ] ]
				),
				esc_url( $upgrade_url )
			);
			?>
		</p>
		<?php
	}

	/**
	 * @param array<string, string> $links
	 * @return array<string, string>
	 */
	public function add_plugin_action_links( array $links ): array {
		$setup_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( self::get_setup_page_url() ),
			esc_html__( 'Setup guide', 'ultimate-member-widgets-for-elementor' )
		);
		array_unshift( $links, $setup_link );
		return $links;
	}

	public function render_setup_notice(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! get_option( self::SETUP_NOTICE_OPTION ) ) {
			return;
		}
		if ( get_user_meta( get_current_user_id(), self::SETUP_NOTICE_DISMISSED_META, true ) ) {
			return;
		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $this->is_setup_screen( $screen ) ) {
			return;
		}

		$nonce    = wp_create_nonce( self::SETUP_NOTICE_AJAX );
		$setup_url = esc_url( self::get_setup_page_url() );
		?>
		<div class="notice notice-info is-dismissible umwfe-setup-notice" id="umwfe-setup-notice" data-nonce="<?php echo esc_attr( $nonce ); ?>">
			<p>
				<strong><?php esc_html_e( 'Ultimate Member + Elementor', 'ultimate-member-widgets-for-elementor' ); ?></strong>
				<?php esc_html_e( 'Use Elementor to design login, register, profile, account, and directory pages — without losing UM forms and permissions.', 'ultimate-member-widgets-for-elementor' ); ?>
				<a href="<?php echo $setup_url; ?>" class="button button-primary" style="margin-left:8px;">
					<?php esc_html_e( 'Open setup guide', 'ultimate-member-widgets-for-elementor' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	public function enqueue_setup_notice_assets( $hook ): void {
		unset( $hook );

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! get_option( self::SETUP_NOTICE_OPTION ) ) {
			return;
		}
		if ( get_user_meta( get_current_user_id(), self::SETUP_NOTICE_DISMISSED_META, true ) ) {
			return;
		}
		?>
		<script id="umwfe-setup-notice-script">
		(function(){
			document.addEventListener('DOMContentLoaded', function(){
				var notice = document.getElementById('umwfe-setup-notice');
				if ( ! notice ) return;
				var dismissBtn = notice.querySelector('.notice-dismiss');
				if ( ! dismissBtn ) return;
				dismissBtn.addEventListener('click', function(){
					var fd = new FormData();
					fd.append('action', <?php echo wp_json_encode( self::SETUP_NOTICE_AJAX ); ?>);
					fd.append('_wpnonce', notice.dataset.nonce || '');
					fetch(<?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, {
						method: 'POST', body: fd, credentials: 'same-origin'
					});
				});
			});
		}());
		</script>
		<?php
	}

	public function handle_setup_notice_dismiss(): void {
		if ( ! check_ajax_referer( self::SETUP_NOTICE_AJAX, '_wpnonce', false ) ) {
			wp_die( esc_html__( 'Security check failed.', 'ultimate-member-widgets-for-elementor' ) );
		}

		update_user_meta( get_current_user_id(), self::SETUP_NOTICE_DISMISSED_META, '1' );
		delete_option( self::SETUP_NOTICE_OPTION );

		wp_die();
	}
}

add_action(
	'plugins_loaded',
	static function () {
		new UM_Elementor_Admin_Settings();
	}
);
