<?php
/**
 * Activity Guard – Real Time Notifier to Slack Activator
 *
 * This class is used to builds all of the tables when the plugin is activated
 *
 * @package WPNTS\Inc
 */

namespace WPNTS\Inc;

use WPNTS\Inc\wpnts_nts_fs; // phpcs:ignore

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');
/**
 * Admin dashboard created
 *
 * @since 1.0.0
 */
class AdminDashboard {

	/**
	 * Construct method.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action('admin_menu', [ $this, 'add_notifier_pages' ]);
		add_action('admin_init', [ $this, 'check_and_update_logdurationtime' ]);
		add_filter( 'plugin_row_meta', array( $this, 'add_plugin_row_meta' ), 10, 2 );
		
		// Version compatibility checks
		add_action('admin_init', [ $this, 'check_pro_version_compatibility' ]);
		add_action('admin_notices', [ $this, 'show_pro_upgrade_notice' ]);
		add_action('wp_ajax_dismiss_pro_upgrade_notice', [ $this, 'dismiss_pro_upgrade_notice' ]);
		add_action('activate_notifier-to-slack-pro/notifier-to-slack-pro.php', [ $this, 'prevent_old_pro_activation' ]);
		
		// Add reset option for testing (remove in production)
		add_action('wp_ajax_reset_pro_upgrade_notice', [ $this, 'reset_pro_upgrade_notice' ]);
	}
	/**
	 * Admin Menu pages
	 *
	 * @since 1.0.0
	 */
	public function add_notifier_pages() {
		$icon = plugin_dir_url(__FILE__) . '../assets/logo.png';
		add_menu_page(
			__( 'Activity Guard', 'notifier-to-slack' ),
			__( 'Activity Guard', 'notifier-to-slack' ),
			'manage_options',
			'notifier-to-slack',
			[ $this, 'notifier_pages' ],
			$icon,
			'2.5' );

		if ( current_user_can( 'manage_options' ) ) {
			global $submenu;

			$submenu['notifier-to-slack'][] = [ __( '📶 Dashboard', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/' ]; // phpcs:ignore

			$submenu['notifier-to-slack'][] = [ __( '📑 Activity Log', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/log' ]; // phpcs:ignore

			$submenu['notifier-to-slack'][] = [ __( '🔍 Scanner', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/scanner' ]; // phpcs:ignore

			// if ( class_exists( 'WooCommerce' ) ) {}
			$submenu['notifier-to-slack'][] = [ __( '📊 Woo Analytics', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/woo-analytics' ]; // phpcs:ignore

			$submenu['notifier-to-slack'][] = [ __( '🧑🏻‍💻 Author', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/author' ]; // phpcs:ignore

			$submenu['notifier-to-slack'][] = [ __( '⚙️ Configuration', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/settings' ]; // phpcs:ignore

			$submenu['notifier-to-slack'][] = [ __( '▶️ Get started', 'notifier-to-slack' ), 'manage_options', 'admin.php?page=notifier-to-slack#/doc' ]; // phpcs:ignore

		}
	}

	/**
	 * Dashboard page
	 *
	 * @since 1.0.0
	 */
	public function notifier_pages() {
		echo '<div id="wpcts_dashboard"></div>';
		echo '<div id="wpcts_portal"></div>';
	}


	/**
	 *  Get the option from the database and update time.
	 *
	 * @since 1.0.0
	 */
	public function check_and_update_logdurationtime() {
		// Check if the log update has already been done.
		$log_update_done = get_option('wpnts_log_update_done', false);

		if ( ! $log_update_done ) {
			// Get the wpnts_global_api_settings option from the database.
			$settings = get_option('wpnts_global_api_settings', false);

			if ( $settings ) {
				// Decode JSON settings.
				$settings_array = json_decode($settings, true);

				// Check if 'logdurationtime' is empty.
				if ( empty($settings_array['logdurationtime']) ) {
					// Update 'logdurationtime' with the current date.
					$settings_array['logdurationtime'] = gmdate('Y-m-d');

					// Save the updated settings back to the option.
					update_option('wpnts_global_api_settings', wp_json_encode($settings_array));

					// Mark that the update has been done.
					update_option('wpnts_log_update_done', true);
				}
			}
		}

		if ( ! wp_next_scheduled('wpnts_corn_hook') ) {
			wp_schedule_event(time(), 'added_schedules_interval', 'wpnts_corn_hook');
		}

		// Check and add thumb column to wpnts_activity_log table if needed.
		$this->check_and_add_columns();

		$this->add_default_security_exclusion();
	}


	/**
	 * Check if the wpnts_activity_log table has the thumb column; add it if missing.
	 *
	 * @since 1.0.0
	 */
	private function check_and_add_columns() {
		global $wpdb;
		$activity_log_table = $wpdb->prefix . 'wpnts_activity_log';

		// Check if the 'thumb' column exists. Since there are no user inputs, we don't need prepare() for this query.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe table name
		$thumb_column_exists = $wpdb->get_results(
			$wpdb->prepare(
				"SHOW COLUMNS FROM `$activity_log_table` LIKE %s",
				'thumb'
			)
		);

		// Check if the 'user_role' column exists. Since there are no user inputs, we don't need prepare() for this query.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe table name
		$role_column_exists = $wpdb->get_results(
			$wpdb->prepare(
				"SHOW COLUMNS FROM `$activity_log_table` LIKE %s",
				'user_role'
			)
		);

		// If 'thumb' column doesn't exist, add it. Since there are no user inputs, we don't need prepare() for this query.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe table name
		if ( empty($thumb_column_exists) ) {
			$wpdb->query("ALTER TABLE `$activity_log_table` ADD thumb VARCHAR(255)");
		}

		// If 'role' column doesn't exist, add it. Since there are no user inputs, we don't need prepare() for this query.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- safe table name
		if ( empty($role_column_exists) ) {
			$wpdb->query("ALTER TABLE `$activity_log_table` ADD user_role VARCHAR(50)");
		}
	}


	/**
	 * Adds default security exclusions if they don't already exist
	 */
	public function add_default_security_exclusion() {
		// Check if the option already exists
		if ( get_option('wps_security_scan_exclusions') === false ) {
			// Default exclusions structure
			$default_exclusions = array(
				'paths' => array(),
				'file_patterns' => array(),
				'php_functions' => array(),
				'core_files' => array( 'core' ),
				'plugins' => array(
					'notifier-to-slack/notifier-to-slack.php',
					'notifier-to-slack-pro/notifier-to-slack-pro.php',
					'prefix-notifier-to-slack-pro/notifier-to-slack-pro.php',
				),
				'themes' => array(),
			);

			// Add the option to the database
			add_option('wps_security_scan_exclusions', $default_exclusions);
		}
	}

	/**
	 * Add plugin row meta.
	 *
	 * @param array  $links Plugin row meta.
	 * @param string $file  Plugin file.
	 * @return array Modified plugin row meta.
	 */
	public function add_plugin_row_meta( $links, $file ) {
		if ( NOTIFIER_TO_SLACK_PLUGIN_BASENAME === $file ) {
			$row_meta = array(
				'docs' => '<a href="' . esc_url( 'https://wpazleen.com/docs/' ) . '" target="_blank" aria-label="' . esc_attr__( 'Documentation', 'notifier-to-slack' ) . '">' . esc_html__( 'Documentation', 'notifier-to-slack' ) . '</a>',
				'support' => '<a href="' . esc_url( 'https://wordpress.org/support/plugin/notifier-to-slack/' ) . '" target="_blank" aria-label="' . esc_attr__( 'Support forum', 'notifier-to-slack' ) . '">' . esc_html__( 'Support', 'notifier-to-slack' ) . '</a>',
				'review' => '<a href="' . esc_url( 'https://wordpress.org/plugins/notifier-to-slack/#reviews' ) . '" target="_blank" aria-label="' . esc_attr__( 'Review forum', 'notifier-to-slack' ) . '">' . esc_html__( '⭐⭐⭐⭐⭐', 'notifier-to-slack' ) . '</a>',
			);
			return array_merge( $links, $row_meta );
		}
		return $links;
	}

	/**
	 * Check Pro version compatibility and deactivate if incompatible.
	 * 
	 * @since 3.11.0
	 */
	public function check_pro_version_compatibility() {
		// Only run this check if Free version is 3.11.0 or higher
		$free_version = WP_NOTIFIER_TO_SLACK_VERSION;
		if ( version_compare( $free_version, '3.11.0', '<' ) ) {
			return;
		}

		// Check if Pro plugin is active
		if ( ! is_plugin_active( 'notifier-to-slack-pro/notifier-to-slack-pro.php' ) ) {
			return;
		}

		// Get Pro version
		$pro_version = $this->get_pro_plugin_version();
		if ( ! $pro_version ) {
			return;
		}

		// Check if Pro version is compatible (2.2.0 or higher)
		if ( version_compare( $pro_version, '2.2.0', '>=' ) ) {
			// Pro version is compatible - clear any existing upgrade flags
			$this->clear_pro_upgrade_flags();
			return;
		}

		// Check if Pro version is 2.1.1 or below (incompatible)
		if ( version_compare( $pro_version, '2.1.1', '<=' ) ) {
			// Deactivate the Pro plugin
			deactivate_plugins( 'notifier-to-slack-pro/notifier-to-slack-pro.php' );
			
			// Set flag to show upgrade notice
			update_option( 'wpnts_pro_upgrade_required', true );
			update_option( 'wpnts_pro_old_version', $pro_version );
			
			// Add admin notice
			add_action( 'admin_notices', function() use ( $pro_version ) {
				echo '<div class="notice notice-error"><p>';
				printf( 
					__( '<strong>Activity Guard Pro v%s has been deactivated!</strong> It\'s incompatible with Activity Guard Free v%s. Please upgrade to Pro v2.2.0 or higher.', 'notifier-to-slack' ),
					esc_html( $pro_version ),
					esc_html( WP_NOTIFIER_TO_SLACK_VERSION )
				);
				echo '</p></div>';
			});
		}
	}

	/**
	 * Clear Pro upgrade flags when compatible version is detected.
	 * 
	 * @since 3.11.0
	 */
	private function clear_pro_upgrade_flags() {
		// Clear upgrade flags if they exist
		if ( get_option( 'wpnts_pro_upgrade_required' ) ) {
			delete_option( 'wpnts_pro_upgrade_required' );
		}
		
		if ( get_option( 'wpnts_pro_upgrade_notice_dismissed' ) ) {
			delete_option( 'wpnts_pro_upgrade_notice_dismissed' );
		}
		
		if ( get_option( 'wpnts_pro_old_version' ) ) {
			delete_option( 'wpnts_pro_old_version' );
		}
	}

	/**
	 * Get Pro plugin version.
	 * 
	 * @since 3.11.0
	 * @return string|false Pro version or false if not found.
	 */
	private function get_pro_plugin_version() {
		$pro_plugin_file = WP_PLUGIN_DIR . '/notifier-to-slack-pro/notifier-to-slack-pro.php';
		
		if ( ! file_exists( $pro_plugin_file ) ) {
			return false;
		}

		// Check if Pro is active and has version constant
		if ( defined( 'WP_NOTIFIER_TO_SLACK_PRO_VERSION' ) ) {
			return WP_NOTIFIER_TO_SLACK_PRO_VERSION;
		}

		// Fallback: Read version from plugin header
		$plugin_data = get_file_data( $pro_plugin_file, array( 'Version' => 'Version' ) );
		return isset( $plugin_data['Version'] ) ? $plugin_data['Version'] : false;
	}

	/**
	 * Show Pro upgrade notice.
	 * 
	 * @since 3.11.0
	 */
	public function show_pro_upgrade_notice() {
		// Only show if upgrade is required and notice hasn't been dismissed
		if ( ! get_option( 'wpnts_pro_upgrade_required' ) || get_option( 'wpnts_pro_upgrade_notice_dismissed' ) ) {
			return;
		}

		$old_version = get_option( 'wpnts_pro_old_version', '2.1.1' );
		$current_user = wp_get_current_user();
		
		?>
		<div id="wpnts-pro-upgrade-notice" class="notice notice-warning is-dismissible" style="position: relative; padding: 20px; border-left: 4px solid #ffba00;">
			<div style="display: flex; align-items: center; gap: 15px;">
				<div style="font-size: 24px;">🚀</div>
				<div style="flex: 1;">
					<h3 style="margin: 0 0 10px 0; color: #d63638;">
						<?php _e( 'Activity Guard Pro Upgrade Required!', 'notifier-to-slack' ); ?>
					</h3>
					<p style="margin: 0 0 15px 0; font-size: 14px;">
						<?php 
						printf( 
							__( 'Your Activity Guard Pro v%s is incompatible with the new Activity Guard Free v%s. The Pro version has been automatically deactivated to prevent conflicts.', 'notifier-to-slack' ),
							'<strong>' . esc_html( $old_version ) . '</strong>',
							'<strong>' . esc_html( WP_NOTIFIER_TO_SLACK_VERSION ) . '</strong>'
						);
						?>
					</p>
					<div style="display: flex; gap: 10px; align-items: center;">
						<a href="https://customers.freemius.com/" target="_blank" class="button button-primary" style="background: #d63638; border-color: #d63638;">
							<?php _e( '🔄 Download Pro v2.2.0+', 'notifier-to-slack' ); ?>
						</a>
						<span style="color: #666; font-size: 12px;">
							<?php _e( 'Login to your Freemius account to get the latest version', 'notifier-to-slack' ); ?>
						</span>
					</div>
				</div>
				<button type="button" class="notice-dismiss" onclick="wpntsDismissProUpgradeNotice()">
					<span class="screen-reader-text"><?php _e( 'Dismiss this notice.', 'notifier-to-slack' ); ?></span>
				</button>
			</div>
		</div>

		<script type="text/javascript">
		function wpntsDismissProUpgradeNotice() {
			jQuery.post(ajaxurl, {
				action: 'dismiss_pro_upgrade_notice',
				nonce: '<?php echo wp_create_nonce( 'wpnts_dismiss_notice' ); ?>'
			}, function(response) {
				if (response.success) {
					jQuery('#wpnts-pro-upgrade-notice').fadeOut();
				} else {
					console.error('Failed to dismiss notice:', response.data ? response.data.message : 'Unknown error');
					// Still hide the notice on client side to prevent user frustration
					jQuery('#wpnts-pro-upgrade-notice').fadeOut();
				}
			}).fail(function(xhr, status, error) {
				console.error('AJAX request failed:', error);
				// Still hide the notice on client side to prevent user frustration
				jQuery('#wpnts-pro-upgrade-notice').fadeOut();
			});
		}
		</script>

		<style>
		#wpnts-pro-upgrade-notice .notice-dismiss {
			position: absolute;
			top: 10px;
			right: 10px;
		}
		</style>
		<?php
	}

	/**
	 * Dismiss Pro upgrade notice via AJAX.
	 * 
	 * @since 3.11.0
	 */
	public function dismiss_pro_upgrade_notice() {
		// Check if user has proper capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Insufficient permissions' );
		}

		// Verify nonce with proper sanitization
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wpnts_dismiss_notice' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed' ) );
			return;
		}

		// Mark notice as dismissed
		update_option( 'wpnts_pro_upgrade_notice_dismissed', true );
		
		wp_send_json_success( array( 'message' => 'Notice dismissed successfully' ) );
	}

	/**
	 * Prevent activation of old Pro versions.
	 * 
	 * @since 3.11.0
	 */
	public function prevent_old_pro_activation() {
		// Get Pro version being activated
		$pro_version = $this->get_pro_plugin_version();
		
		if ( ! $pro_version ) {
			return;
		}

		// Check if Free version is 3.11.0+ and Pro version is 2.1.1 or below
		$free_version = WP_NOTIFIER_TO_SLACK_VERSION;
		if ( version_compare( $free_version, '3.11.0', '>=' ) && version_compare( $pro_version, '2.1.1', '<=' ) ) {
			// Deactivate the Pro plugin immediately
			deactivate_plugins( 'notifier-to-slack-pro/notifier-to-slack-pro.php' );
			
			// Set upgrade flags
			update_option( 'wpnts_pro_upgrade_required', true );
			update_option( 'wpnts_pro_old_version', $pro_version );
			
			// Show error message
			wp_die(
				sprintf(
					__( '<h1>Activation Failed!</h1><p><strong>Activity Guard Pro v%s</strong> is incompatible with <strong>Activity Guard Free v%s</strong>.</p><p>Please upgrade to <strong>Pro v2.2.0 or higher</strong> from your <a href="https://customers.freemius.com/" target="_blank">Freemius account</a>.</p><p><a href="%s" class="button">← Go Back</a></p>', 'notifier-to-slack' ),
					esc_html( $pro_version ),
					esc_html( $free_version ),
					esc_url( admin_url( 'plugins.php' ) )
				),
				__( 'Plugin Activation Error', 'notifier-to-slack' ),
				array( 'back_link' => true )
			);
		} else if ( version_compare( $free_version, '3.11.0', '>=' ) && version_compare( $pro_version, '2.2.0', '>=' ) ) {
			// Compatible Pro version activated - clear any existing upgrade flags
			$this->clear_pro_upgrade_flags();
		}
	}

	/**
	 * Reset Pro upgrade notice for testing purposes.
	 * 
	 * @since 3.11.0
	 */
	public function reset_pro_upgrade_notice() {
		// Check if user has proper capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'Insufficient permissions' );
		}

		// Verify nonce with proper sanitization
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wpnts_reset_notice' ) ) {
			wp_send_json_error( array( 'message' => 'Security check failed' ) );
			return;
		}

		// Reset all upgrade notice options
		delete_option( 'wpnts_pro_upgrade_required' );
		delete_option( 'wpnts_pro_upgrade_notice_dismissed' );
		delete_option( 'wpnts_pro_old_version' );
		
		wp_send_json_success( array( 'message' => 'Pro upgrade notice reset successfully' ) );
	}
}
