<?php
/**
 * Admin menu management.
 *
 * @package automation-web-platform
 */

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

if ( ! defined( 'WAWP_MAIN_MENU_SLUG' ) ) {
	define( 'WAWP_MAIN_MENU_SLUG', 'wawp' );
}


/**
 * Class WAWP_Menu
 */
class WAWP_Menu {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;

	/**
	 * Initialize menu hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'wawp_register_main_menu' ) );
		add_action( 'admin_post_wawp_process_form', array( $this, 'wawp_process_form' ) );
		add_action( 'admin_bar_menu', array( $this, 'wawp_add_admin_bar_node' ), 90 );
		add_action( 'admin_post_wawp_admin_bar_flush_cache', array( $this, 'handle_admin_bar_flush_cache' ) );
		add_action( 'admin_notices', array( $this, 'wawp_render_admin_notices' ) );
		add_action( 'current_screen', array( $this, 'wawp_disable_notices_on_wawp_pages' ) );
	}

	/**
	 * Disable administrative notices on Wawp pages.
	 *
	 * @param WP_Screen $screen Current screen object.
	 */
	public function wawp_disable_notices_on_wawp_pages( $screen ) {
		if ( $screen && false !== strpos( $screen->id, 'wawp' ) ) {
			remove_all_actions( 'admin_notices' );
			remove_all_actions( 'all_admin_notices' );
			remove_all_actions( 'user_admin_notices' );
		}
	}

	/**
	 * Load section dependencies.
	 */
	public function wawp_load_section_dependencies() {
		// Legacy dependencies removed. React dashboard handles routing and logic.
	}

	/**
	 * Register main menu.
	 */
	public function wawp_register_main_menu() {
		$menu_label = esc_html__( 'Wawp', 'automation-web-platform' );

		// Use the official brand robot icon path, base64 encoded for a crisp look.
		$svg_icon  = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M7 0C7.55228 0 8 0.447715 8 1V3H16V1C16 0.447715 16.4477 0 17 0H19C19.5523 0 20 0.447715 20 1V3C22.2091 3 24 4.79086 24 7V17C24 19.2091 22.2091 21 20 21H17C17 21 14 24 12 24C10 24 7 21 7 21H4C1.79086 21 1.61067e-08 19.2091 0 17V7C0 4.79086 1.79086 3 4 3V1C4 0.447715 4.44772 0 5 0H7ZM4 5C2.89543 5 2 5.89543 2 7V17C2 18.1046 2.89543 19 4 19H20C21.1046 19 22 18.1046 22 17V7C22 5.89543 21.1046 5 20 5H4ZM9 9C9.55228 9 10 9.44772 10 10V14C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14V10C6 9.44772 6.44772 9 7 9H9ZM17 9C17.5523 9 18 9.44772 18 10V14C18 14.5523 17.5523 15 17 15H15C14.4477 15 14 14.5523 14 14V10C14 9.44772 14.4477 9 15 9H17Z" fill="#44FF87"/></svg>';
		$icon_data = 'data:image/svg+xml;base64,' . call_user_func( 'base64_encode', $svg_icon );

		add_menu_page( $menu_label, $menu_label, WAWP_CAPABILITY, WAWP_MAIN_MENU_SLUG, array( $this, 'wawp_render_main_page' ), $icon_data, 50 );

		add_action(
			'admin_head',
			function () {
				?>
			<style>
				#adminmenu #toplevel_page_wawp .wp-menu-image {
					display: flex !important;
					align-items: center !important;
					justify-content: center !important;
					filter: none !important;
					-webkit-filter: none !important;
					opacity: 1 !important;
				}
				#adminmenu #toplevel_page_wawp .wp-menu-image img {
					width: 18px !important;
					height: 18px !important;
					padding: 0 !important;
					filter: none !important;
					-webkit-filter: none !important;
					opacity: 1 !important;
				}
				#adminmenu #toplevel_page_wawp:hover .wp-menu-image img,
				#adminmenu #toplevel_page_wawp.wp-has-current-submenu .wp-menu-image img,
				#adminmenu #toplevel_page_wawp.current .wp-menu-image img {
					filter: none !important;
					-webkit-filter: none !important;
					opacity: 1 !important;
				}
				#adminmenu #toplevel_page_wawp .wp-menu-image:before {
					display: none !important;
				}
				body.toplevel_page_wawp #wpfooter {
					display: none !important;
				}
				body.toplevel_page_wawp .notice,
				body.toplevel_page_wawp .update-nag,
				body.toplevel_page_wawp .updated,
				body.toplevel_page_wawp .error,
				body.toplevel_page_wawp .error-notice,
				body.toplevel_page_wawp .is-dismissible,
				body.toplevel_page_wawp .wawp-admin-notice,
				body.toplevel_page_wawp #wpbody-content > .notice,
				body.toplevel_page_wawp #wpbody-content > .error,
				body.toplevel_page_wawp #wpbody-content > .update-nag,
				body.toplevel_page_wawp #wpbody-content > div:has(.notice),
				body.toplevel_page_wawp #wpbody-content > div:has(.error),
				body.toplevel_page_wawp #wpbody-content > div:has(.update-nag) {
					display: none !important;
				}
				body.toplevel_page_wawp #wpbody-content {
					padding-bottom: 0 !important;
				}
				html:has(body.toplevel_page_wawp) {
					margin-top: 0 !important;
					padding-top: 0 !important;
					height: 100vh !important;
					overflow: hidden !important;
				}
				body.toplevel_page_wawp {
					margin-top: 0 !important;
					padding-top: var(--wp-admin--admin-bar--height, 32px) !important;
					height: 100vh !important;
					overflow: hidden !important;
					box-sizing: border-box !important;
				}
				@media screen and (max-width: 782px) {
					body.toplevel_page_wawp {
						padding-top: 46px !important;
					}
				}
				body.toplevel_page_wawp #wpwrap {
					height: 100% !important;
					overflow: hidden !important;
				}
				body.toplevel_page_wawp #wpcontent {
					height: 100% !important;
					padding: 0 !important;
					overflow: hidden !important;
					margin-top: 0 !important;
				}
				body.toplevel_page_wawp #wpbody {
					height: 100% !important;
					overflow: hidden !important;
				}
				body.toplevel_page_wawp #wpbody-content {
					height: 100% !important;
					padding: 0 !important;
					overflow: hidden !important;
				}
				#wawp-dashboard-root {
					height: 100% !important;
					width: 100% !important;
					margin: 0 !important;
					padding: 0 !important;
					overflow: hidden !important;
				}
			</style>
				<?php
			}
		);
	}


	/**
	 * Render main page.
	 */
	public function wawp_render_main_page() {
		$this->wawp_load_section_dependencies();
		echo '<div id="wawp-dashboard-root"></div>';
		echo '<div id="wawp-get-started-container"></div>';
	}

	/**
	 * Process form submission.
	 */
	public function wawp_process_form() {
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
			return;
		}

		$this->check_permissions( 'wawp_form_action', 'wawp_form_nonce' );
		WAWP_Connector()->check_admin_auth();

		set_transient(
			'wawp_admin_notice_' . get_current_user_id(),
			array(
				'message' => esc_html__( 'Form processed successfully.', 'automation-web-platform' ),
				'type'    => 'success',
			),
			30
		);

		wp_safe_redirect( admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG ) );
		exit;
	}


	/**
	 * Add Wawp shortcut to the admin bar.
	 *
	 * @param WP_Admin_Bar $wp_admin_bar Admin bar instance.
	 */
	public function wawp_add_admin_bar_node( $wp_admin_bar ) {
		// Check if current user is logged in via temporary access session.
		$is_temp_session = false;
		$user_id         = get_current_user_id();
		if ( $user_id ) {
			$token = wp_get_session_token();
			if ( $token ) {
				$manager = WP_Session_Tokens::get_instance( $user_id );
				$session = $manager->get( $token );
				if ( is_array( $session ) && isset( $session['wawp_temp_link_id'] ) ) {
					$is_temp_session = true;
				}
			}
			// Fallback check if the username matches the dynamic temp user prefix.
			if ( ! $is_temp_session ) {
				$user = get_userdata( $user_id );
				if ( $user && 0 === strpos( $user->user_login, 'wawp_temp_' ) ) {
					$is_temp_session = true;
				}
			}
		}

		$capability = defined( 'WAWP_CAPABILITY' ) ? WAWP_CAPABILITY : 'manage_options';
		if ( ! $is_temp_session && ! current_user_can( $capability ) ) {
			return;
		}

		$issues_count = 0;
		if ( class_exists( 'WAWP' ) && WAWP()->system_info ) {
			$issues_count = WAWP()->system_info->get_cached_issue_count();
		}

		$svg_icon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" style="display: block;"><path d="M7 0C7.55228 0 8 0.447715 8 1V3H16V1C16 0.447715 16.4477 0 17 0H19C19.5523 0 20 0.447715 20 1V3C22.2091 3 24 4.79086 24 7V17C24 19.2091 22.2091 21 20 21H17C17 21 14 24 12 24C10 24 7 21 7 21H4C1.79086 21 1.61067e-08 19.2091 0 17V7C0 4.79086 1.79086 3 4 3V1C4 0.447715 4.44772 0 5 0H7ZM4 5C2.89543 5 2 5.89543 2 7V17C2 18.1046 2.89543 19 4 19H20C21.1046 19 22 18.1046 22 17V7C22 5.89543 21.1046 5 20 5H4ZM9 9C9.55228 9 10 9.44772 10 10V14C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14V10C6 9.44772 6.44772 9 7 9H9ZM17 9C17.5523 9 18 9.44772 18 10V14C18 14.5523 17.5523 15 17 15H15C14.4477 15 14 14.5523 14 14V10C14 9.44772 14.4477 9 15 9H17Z" fill="#44FF87"/></svg>';
		$logo     = '<span class="wawp-admin-bar-logo" style="display: inline-block; vertical-align: middle; margin-inline-start: 6px; margin-inline-end: 6px; line-height: 0;">' . $svg_icon . '</span>';
		$label    = '<span style="vertical-align: middle; display: inline-block; line-height: 1;">Wawp</span>';

		$badge = '';
		if ( $is_temp_session ) {
			$badge = ' <span class="wawp-admin-bar-temp-badge" style="background: #16a34a; color: #ffffff; border-radius: 4px; padding: 2px 6px; font-size: 9px; font-weight: bold; margin-left: 6px; line-height: 1; display: inline-block; vertical-align: middle;">' . esc_html__( 'Temp access', 'automation-web-platform' ) . '</span>';
		} elseif ( $issues_count > 0 ) {
			$badge = ' <span class="wawp-admin-bar-badge" style="background: rgba(244, 63, 94, 0.2); color: #fda4af; border: 1px solid rgba(244, 63, 94, 0.3); border-radius: 4px; padding: 2px 6px; font-size: 9px; font-weight: bold; margin-left: 6px; line-height: 1; display: inline-block; vertical-align: middle;">' . esc_html( $issues_count ) . '</span>';
		}

		// Parent node.
		$wp_admin_bar->add_node(
			array(
				'id'    => 'wawp-admin-bar',
				'title' => $logo . $label . $badge,
				'href'  => admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG ),
				'meta'  => array(
					'title' => esc_html__( 'Wawp Dashboard', 'automation-web-platform' ),
				),
			)
		);

		// Child 1: Clear Cache.
		$wp_admin_bar->add_node(
			array(
				'parent' => 'wawp-admin-bar',
				'id'     => 'wawp-admin-bar-clear-cache',
				'title'  => esc_html__( 'Clear Cache', 'automation-web-platform' ),
				'href'   => wp_nonce_url( admin_url( 'admin-post.php?action=wawp_admin_bar_flush_cache' ), 'wawp_admin_bar_flush_cache' ),
			)
		);

		// Child 2: System Status.
		$wp_admin_bar->add_node(
			array(
				'parent' => 'wawp-admin-bar',
				'id'     => 'wawp-admin-bar-system-status',
				'title'  => esc_html__( 'System Information', 'automation-web-platform' ),
				'href'   => admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG . '&wawp_section=system_info' ),
			)
		);

		// Child 3: Setup Wizard (Onboard).
		$wp_admin_bar->add_node(
			array(
				'parent' => 'wawp-admin-bar',
				'id'     => 'wawp-admin-bar-onboard',
				'title'  => esc_html__( 'Onboard', 'automation-web-platform' ),
				'href'   => admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG . '&wawp_section=setup_wizard' ),
			)
		);

		// Child 4: Dashboard.
		$wp_admin_bar->add_node(
			array(
				'parent' => 'wawp-admin-bar',
				'id'     => 'wawp-admin-bar-dashboard',
				'title'  => esc_html__( 'Dashboard', 'automation-web-platform' ),
				'href'   => admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG ),
			)
		);
	}

	/**
	 * Perform the cache clearing logic.
	 */
	public static function execute_cache_flush() {
		// 1. Force bust React cache (updates asset version query args).
		update_option( 'wawp_force_cache_bust_version', time(), false );

		// 2. Clear WordPress Transients & Object Cache.
		wp_cache_flush();
		if ( function_exists( 'delete_transient' ) ) {
			// Delete specific transients.
			delete_transient( 'wawp_last_db_check' );
			delete_transient( 'wawp_online_instances' );
			delete_transient( 'wawp_due_abandoned_notifs' );
			delete_transient( 'wawp_dashboard_transients' );

			$user_id = get_current_user_id();
			delete_transient( 'wawp_dashboard_data_full_' . $user_id );

			// Also delete any other cached dashboard transient keys.
			$keys = get_option( 'wawp_dashboard_transient_keys', array() );
			if ( is_array( $keys ) ) {
				foreach ( $keys as $key ) {
					delete_transient( $key );
					wp_cache_delete( $key, 'wawp_database' );
				}
				update_option( 'wawp_dashboard_transient_keys', array(), false );
			}
		}

		// 3. OPcache reset if available.
		if ( function_exists( 'opcache_reset' ) ) {
			opcache_reset();
		}

		// Flush rewrites just in case.
		flush_rewrite_rules( false );
	}

	/**
	 * Clear all cached dashboard transients.
	 */
	public static function clear_all_dashboard_transients() {
		wp_cache_delete( 'wawp_otp_settings_raw', 'wawp_otp' );

		$keys = get_option( 'wawp_dashboard_transient_keys', array() );
		if ( is_array( $keys ) ) {
			foreach ( $keys as $key ) {
				delete_transient( $key );
				wp_cache_delete( $key, 'wawp_database' );
			}
			update_option( 'wawp_dashboard_transient_keys', array(), false );
		}
	}

	/**
	 * Handle admin bar flush cache action.
	 */
	public function handle_admin_bar_flush_cache() {
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'wawp_admin_bar_flush_cache' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'automation-web-platform' ) );
		}

		$capability = defined( 'WAWP_CAPABILITY' ) ? WAWP_CAPABILITY : 'manage_options';
		if ( ! current_user_can( $capability ) ) {
			wp_die( esc_html__( 'Permission denied.', 'automation-web-platform' ) );
		}

		self::execute_cache_flush();

		set_transient(
			'wawp_admin_notice_' . get_current_user_id(),
			array(
				'message' => esc_html__( 'Cache cleared successfully.', 'automation-web-platform' ),
				'type'    => 'success',
			),
			30
		);

		// Redirect back to the referrer or admin dashboard.
		$redirect_url = wp_get_referer();
		if ( ! $redirect_url ) {
			$redirect_url = admin_url( 'admin.php?page=' . WAWP_MAIN_MENU_SLUG );
		}
		wp_safe_redirect( $redirect_url );
		exit;
	}

	/**
	 * Render admin notices.
	 */
	public function wawp_render_admin_notices() {
		$notice_data = get_transient( 'wawp_admin_notice_' . get_current_user_id() );
		if ( $notice_data ) {
			delete_transient( 'wawp_admin_notice_' . get_current_user_id() );
			$message = isset( $notice_data['message'] ) ? $notice_data['message'] : '';
			$type    = isset( $notice_data['type'] ) ? $notice_data['type'] : 'success';
			if ( $message ) {
				echo '<div class="notice notice-' . esc_attr( $type ) . ' is-dismissible wawp-admin-notice"><p>' . esc_html( $message ) . '</p></div>';
			}
		}
	}
}
