<?php
/**
 * Spacetree Admin Menus
 * 
 * Root-level admin menus for Spacetree plugin.
 * Includes ProQyz Migrate menu that appears above the ProQyz menu.
 *
 * @package Spacetree
 * @since   2.1.0
 */

defined( 'ABSPATH' ) || exit;

class ST_Admin_Menus {

	/**
	 * Constructor
	 */
	public function __construct() {
		//add_action( 'admin_menu', array( $this, 'register_menus' ), 5 ); // Priority 5 to load before ProQyz menu
		add_action( 'admin_notices', array( $this, 'show_update_notice' ) );
		add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widget' ) );
		// Handle welcome page redirect after plugin update
		add_action( 'admin_init', array( $this, 'check_plugin_update_redirect' ) );
	}

	/**
	 * Register admin menus
	 */
	public function register_menus() {
		// Use constant directly instead of global variable
		$db_version_key = 'ST_DB_VERSION'; // Database schema version option key
		
		// Get current DB version
		$current_db_version = get_option( $db_version_key, '2.0' );
		
		// Check if DB version constant is defined
		$target_db_version = defined('ST_DB_VERSION') ? ST_DB_VERSION : '2.0';
		
		// Determine states
		$migration_required = version_compare( $current_db_version, $target_db_version, '<' );
		$migration_completed = version_compare( $current_db_version, $target_db_version, '>=' );
		$plugin_disabled = defined('ST_PLUGIN_DISABLED') && ST_PLUGIN_DISABLED;

		// ALWAYS show menu if:
		// 1. Migration is required (DB v1) - user needs to migrate
		// 2. Plugin is disabled (needs update after migration) - user needs to update
		// 3. Migration completed but plugin old - user needs to see status
		$show_menu = $migration_required;
		
		if ( $show_menu ) {
			// Determine menu title - always "Spacetree" with alert badge if plugin disabled
			$menu_title = 'Spacetree';
			if ( $plugin_disabled ) {
				$menu_title .= ' <span class="awaiting-mod" style="background: #dc3232;">1</span>';
			}

			// Add top-level menu
			add_menu_page(
				__( 'Spacetree', 'spacetree' ), // Page title
				$menu_title,                    // Menu title (with badge if needed)
				'manage_options',               // Capability
				'st-welcome',                   // Menu slug (default to welcome page)
				array( $this, 'render_welcome_page' ), // Callback
				'dashicons-palmtree',           // Icon
				25                              // Position (25 = above ProQyz at 40)
			);
			
			// Add Welcome submenu (this will replace the auto-generated first submenu)
			add_submenu_page(
				'st-welcome',                   // Parent slug
				__( 'Welcome to ProQyz LMS', 'spacetree' ), // Page title
				__( 'Welcome', 'spacetree' ),   // Menu title
				'manage_options',               // Capability
				'st-welcome',                   // Menu slug (same as parent)
				array( $this, 'render_welcome_page' ) // Callback
			);
			
			// Add ProQyz Status submenu
			add_submenu_page(
				'st-welcome',                   // Parent slug
				__( 'ProQyz migration', 'spacetree' ), // Page title
				__( 'ProQyz migration', 'spacetree' ), // Menu title
				'manage_options',               // Capability
				'st-proqyz-migrate',             // Menu slug
				array( $this, 'render_migration_page' ) // Callback (uses migration page)
			);
			
			// Add Support submenu
			add_submenu_page(
				'st-welcome',                   // Parent slug
				__( 'Support', 'spacetree' ),   // Page title
				__( 'Support', 'spacetree' ),   // Menu title
				'manage_options',               // Capability
				'st-support',                   // Menu slug
				array( $this, 'render_support_page' ) // Callback
			);
			
			// Add Changelog submenu
			$spacetree = Spacetree::instance();
			$version_menu_title = 'v' . $spacetree->version;
			add_submenu_page(
				'st-welcome',                   // Parent slug
				__( 'Changelog', 'spacetree' ), // Page title
				$version_menu_title,            // Menu title (e.g., "v2.1.0")
				'manage_options',               // Capability
				'st-changelog',                 // Menu slug
				array( $this, 'render_changelog_page' ) // Callback
			);
			
			// Add diagnostic submenu if WP_DEBUG is enabled
			if ( defined('WP_DEBUG') && WP_DEBUG ) {
				add_submenu_page(
					'st-welcome',               // Parent slug
					'Migration Diagnostic',     // Page title
					'🔍 Diagnostic',            // Menu title
					'manage_options',           // Capability
					'st-proqyz-diagnostic',     // Menu slug
					array( $this, 'render_diagnostic_page' ) // Callback
				);
			}
		} else {
			$menu_title = 'Spacetree';
			if ( $plugin_disabled ) {
				$menu_title .= ' <span class="awaiting-mod" style="background: #dc3232;">1</span>';
			}

			// Add top-level menu
			add_menu_page(
				__( 'Spacetree', 'spacetree' ), // Page title
				$menu_title,                    // Menu title (with badge if needed)
				'manage_options',               // Capability
				'st-welcome',                   // Menu slug (default to welcome page)
				array( $this, 'render_welcome_page' ), // Callback
				'dashicons-palmtree',           // Icon
				25                              // Position (25 = above ProQyz at 40)
			);
			// Even if main menu is not shown, still add welcome page (hidden from menu bar, accessible via URL)
			add_submenu_page(
				null,                           // No parent (hidden from menu)
				__( 'Welcome to ProQyz LMS', 'spacetree' ), // Page title
				__( 'Welcome', 'spacetree' ),   // Menu title (not shown)
				'manage_options',               // Capability
				'st-welcome',                   // Menu slug
				array( $this, 'render_welcome_page' ) // Callback
			);
		}
	}

	/**
	 * Show admin notice when plugin needs update
	 */
	public function show_update_notice() {
		// Only show if plugin is disabled (migration complete but plugin outdated)
		if ( ! defined('ST_PLUGIN_DISABLED') || ! ST_PLUGIN_DISABLED ) {
			return;
		}

		// Don't show on the migration page itself
		$screen = get_current_screen();
		if ( $screen && strpos( $screen->id, 'st-proqyz-migrate' ) !== false ) {
			return;
		}

		?>
		<div class="notice notice-error" style="border-left-color: #dc3232;">
			<div style="display: flex; align-items: center; margin-bottom: 10px;">
				<span style="font-size: 16px; margin-right: 8px;">⚠️</span>
				<strong style="font-size: 14px;">ProQyz Plugin Update Required</strong>
				<button type="button" class="button button-link" onclick="toggleProqyzMenuDetails()" style="margin-left: auto; font-size: 12px;">
					<span id="proqyz-menu-toggle-text">Show Details</span>
					<span id="proqyz-menu-toggle-arrow">▼</span>
				</button>
			</div>
			<p style="font-size: 13px; color: #646970; margin: 0;">
				Database migration is complete, but your plugin needs to be updated to <strong>v2.1.0+</strong> 
				to activate the new features.
			</p>
			
			<div id="proqyz-menu-details" style="display: none; margin-top: 15px; padding: 10px; background: #f9f9f9; border-radius: 4px;">
				<p style="margin: 0 0 10px 0;">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=st-proqyz-migrate' ) ); ?>" 
					   class="button button-primary">
						View Update Instructions
					</a>
					<a href="<?php echo esc_url( admin_url( 'update-core.php' ) ); ?>" 
					   class="button button-secondary" 
					   style="margin-left: 5px;">
						Check for Updates
					</a>
				</p>
				<p style="font-size: 12px; color: #646970; margin: 0;">
					💡 All ProQyz features are temporarily disabled until you update the plugin.
				</p>
			</div>
		</div>
		
		<script>
		function toggleProqyzMenuDetails() {
			const details = document.getElementById('proqyz-menu-details');
			const text = document.getElementById('proqyz-menu-toggle-text');
			const arrow = document.getElementById('proqyz-menu-toggle-arrow');
			
			if (details.style.display === 'none') {
				details.style.display = 'block';
				text.textContent = 'Hide Details';
				arrow.textContent = '▲';
			} else {
				details.style.display = 'none';
				text.textContent = 'Show Details';
				arrow.textContent = '▼';
			}
		}
		</script>
		<?php
	}

	/**
	 * Add dashboard widget when update is required
	 */
	public function add_dashboard_widget() {
		// Only add if plugin is disabled (needs update)
		if ( ! defined('ST_PLUGIN_DISABLED') || ! ST_PLUGIN_DISABLED ) {
			return;
		}

		wp_add_dashboard_widget(
			'proqyz_update_required',
			'⚠️ ProQyz Plugin Update Required',
			array( $this, 'render_dashboard_widget' )
		);
		
		// Make it high priority so it shows at the top
		global $wp_meta_boxes;
		$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
		$widget = array( 'proqyz_update_required' => $dashboard['proqyz_update_required'] );
		unset( $dashboard['proqyz_update_required'] );
		$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $widget, $dashboard );
	}

	/**
	 * Render dashboard widget content
	 */
	public function render_dashboard_widget() {
		$db_version_key = 'ST_DB_VERSION'; // Database schema version option key
		$current_db_version = get_option( $db_version_key, '1.0' );
		$plugin_version = defined('ST_VERSION') ? ST_VERSION : '2.0.5.2';
		
		?>
		<div style="padding: 10px;">
			<div style="background: #fff8e5; border-left: 4px solid #ffb900; padding: 15px; margin-bottom: 15px; border-radius: 4px;">
				<h3 style="margin: 0 0 10px 0; color: #856404;">
					🎉 Database Migration Completed!
				</h3>
				<p style="margin: 0 0 10px 0; font-size: 14px; line-height: 1.6;">
					Your database has been successfully migrated to <strong>v<?php echo esc_html($current_db_version); ?></strong>.
					<br>
					However, your plugin version (<strong>v<?php echo esc_html($plugin_version); ?></strong>) needs to be updated 
					to <strong>v2.1.0+</strong> to activate the new features.
				</p>
			</div>

			<div style="background: #ffebee; border-left: 4px solid #dc3232; padding: 15px; margin-bottom: 15px; border-radius: 4px;">
				<p style="margin: 0 0 10px 0; font-size: 14px; font-weight: 600; color: #8a2424;">
					⚠️ ProQyz Features Temporarily Disabled
				</p>
				<p style="margin: 0; font-size: 13px; color: #646970;">
					All ProQyz shortcodes and features are currently disabled to prevent compatibility issues 
					between the new database structure and old plugin code.
				</p>
			</div>

			<div style="display: flex; gap: 10px; margin-bottom: 10px;">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=st-proqyz-migrate' ) ); ?>" 
				   class="button button-primary">
					📋 View Migration Status
				</a>
				<a href="<?php echo esc_url( admin_url( 'update-core.php' ) ); ?>" 
				   class="button button-primary" 
				   style="background: #46b450; border-color: #46b450;">
					🔄 Check for Updates Now
				</a>
			</div>

			<p style="font-size: 12px; color: #646970; margin: 15px 0 0 0; line-height: 1.6;">
				<strong>💡 What to do:</strong>
				<br>1. Click "Check for Updates Now" to see if v2.1.0+ is available
				<br>2. Update the ProQyz plugin to the latest version
				<br>3. All features will automatically activate after update
				<br>4. Enjoy 99% faster performance with the optimized v2 architecture!
			</p>
		</div>
		<?php
	}

	/**
	 * Render migration page
	 */
	public function render_migration_page() {
		// Include the new V2 migration admin page
		require_once ST_ABSPATH . 'includes/admin/pages/page-migration-v2.php';
	}

	/**
	 * Render welcome page
	 */
	public function render_welcome_page() {
		// Include the welcome page
		require_once ST_ABSPATH . 'includes/admin/pages/page-welcome.php';
	}

	/**
	 * Render support page
	 */
	public function render_support_page() {
		// Include the support page
		require_once ST_ABSPATH . 'includes/admin/pages/page-support.php';
	}

	/**
	 * Render changelog page
	 */
	public function render_changelog_page() {
		// Include the changelog page
		require_once ST_ABSPATH . 'includes/admin/pages/page-changelog.php';
	}

	/**
	 * Check if plugin was updated and redirect to welcome page
	 */
	public function check_plugin_update_redirect() {
		// Only run for administrators
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Don't redirect during AJAX requests or REST API calls
		if ( wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
			return;
		}

		// Get current plugin version
		$spacetree = Spacetree::instance();
		$current_version = $spacetree->version;

		// Get stored welcome version
		$welcome_version = get_option( 'spacetree-welcome', '' );

		// Check if we need to show welcome page
		$should_redirect = false;

		if ( empty( $welcome_version ) ) {
			// First time - redirect and set version
			$should_redirect = true;
		} elseif ( version_compare( $welcome_version, $current_version, '<' ) ) {
			// Version upgraded - redirect and update version
			$should_redirect = true;
		}

		if ( $should_redirect ) {
			// Update the welcome version to current version BEFORE redirecting
			update_option( 'spacetree-welcome', $current_version );

			// Skip redirect if we're already on the welcome page
			if ( isset( $_GET['page'] ) && $_GET['page'] === 'st-welcome' ) {
				return;
			}

			// Skip redirect if we're on the plugin activation page
			if ( isset( $_GET['activate'] ) || isset( $_GET['activate-multi'] ) ) {
				return;
			}

			// Redirect to welcome page
			wp_safe_redirect( admin_url( 'admin.php?page=st-welcome' ) );
			exit;
		}
	}

	/**
	 * Render diagnostic page
	 */
	public function render_diagnostic_page() {
		// Include the diagnostic page
		require_once ST_ABSPATH . 'includes/admin/pages/page-diagnostic.php';
	}
}

// Initialize
new ST_Admin_Menus();
