<?php
/**
 * Activity Guard – Real Time Notifier to Slack Rest Route.
 *
 * This class is used to response and all rest route works.
 *
 * @package WPNTS\Inc
 */

namespace WPNTS\Inc;

use WPNTS\Inc\wpnts_nts_fs; // phpcs:ignore
use WPNTS\Inc\Activate; // phpcs:ignore
use WPNTS\Inc\Deactivate; // phpcs:ignore
use WPNTS\Inc\Database\DB; // phpcs:ignore
use WPNTS\Inc\SlackAttachment; // phpcs:ignore
use WPNTS\Inc\SlackChannelRouter; // phpcs:ignore

defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');
/**
 * Notify used to rest route created.
 *
 * @since 1.0.0
 */
class Notify {

	/**
	 * Construct method.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$wpnts_db_instance = new DB();
		$is_active = $wpnts_db_instance->is_pro_active();
		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings');
		$schedules_interval = json_decode($schedules_int);
		$wpnts_pluginactivation = $schedules_interval->pluginactivation ?? 'false';
		$wpnts_plugindeactivation = $schedules_interval->plugindeactivation ?? 'false';
		$wpnts_loginandout = $schedules_interval->loginandout ?? 'false';
		$wpnts_sitehelgth = $schedules_interval->sitehelgth ?? 'false';
		$wpnts_registration = $schedules_interval->registration ?? 'false';
		$rolechangenotification = $schedules_interval->rolechangenotification ?? 'false';
		$lostpassreset = $schedules_interval->lostpassreset ?? 'false';
		$accountpassreset = $schedules_interval->accountpassreset ?? 'false';
		$pluginupdate = $schedules_interval->pluginupdate ?? 'false';

		// Action hook for plugin activated.
		if ( true === $wpnts_pluginactivation ) {
			add_action( 'activated_plugin', [ $this, 'wpnts_plugin_activation' ], 10, 2 );
		}

		// Action hook for plugin deactivation.
		if ( true === $wpnts_plugindeactivation ) {
			add_action( 'deactivated_plugin', [ $this, 'wpnts_plugin_deactivated' ], 10, 2 );
		}

		// Site Helgth.
		if ( true === $wpnts_sitehelgth ) {
			 add_action( 'wpnts_corn_hook', [ $this, 'wpnts_site_health_status_notification' ] );
		}

		// Login and Logout.
		if ( true === $wpnts_loginandout ) {
			add_action( 'wp_login',[ $this, 'wpnts_user_activity_notification_login' ], 10, 2 );
			add_action( 'wp_login',[ $this, 'wpnts_user_login_total_count' ], 10, 2 );

			add_action( 'wp_logout',[ $this, 'wpnts_user_activity_notification_logout' ] );
			add_action('wp_login_failed', array( $this, 'wpnts_user_track_failed_login' ));

		}
		// New registration.
		if ( true === $wpnts_registration ) {
			add_action( 'user_register',[ $this, 'wpnts_new_user_notification' ], 10, 1 );
		}

		// Plugin update by whoom notify track.
		if ( true === $pluginupdate ) {
			add_action('upgrader_process_complete', [ $this, 'wpnts_plugin_updated' ], 10, 2);
		}
	}


	

	/**
	 * Handles the activation of a plugin, sending notifications to Slack and email, and updating the activity log.
	 *
	 * @param string $plugin The name of the activated plugin.
	 * @param bool   $network_wide Whether the activation is network-wide (for multisite).
	 * @since 1.0.0
	 */
	public function wpnts_plugin_activation( $plugin, $network_wide ) {
		try {
			$user_info = $this->get_current_user_safely();
			$current_user_name = $user_info['name'];

		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings' );
		$schedules_interval = json_decode( $schedules_int );
		$wpnts_webhook = $schedules_interval->webhook ?? '';
		$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

		$slack_webhook_url = $wpnts_webhook;

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		// Default template for plugin activation
		$default_template = ':face_with_peeking_eye: Plugin {plugin_name} has been *activated* by :arrow_right: {user_name} {site_url}';
		
		// Template data for placeholders
		$template_data = [
			'plugin_name' => $plugin,
			'user_name' => $current_user_name,
		];

		// Send templated notification with custom message support (automatically sends to both Slack and Telegram)
		$attachmentHandler->send_templated_notification( 
			$slack_webhook_url, 
			$default_template,
			$template_data,
			'Medium', 
			'Plugin Activation',
			'wpnts_schedules_interval_site_settings', // Settings option name
			'pluginactivation_message', // Template key
			$current_user_name
		);

		// Send In Mail.
		if ( $authorPaneltoMail === true ) {
			$this->sendEmailNotificationPluginActiveDeactive($plugin, $current_user_name, 'activated');
		}

		// Update for Dashboard.
		$activated_plugins = get_option( 'wpnts_activated_plugins', [] );
		$current_time = current_time( 'timestamp', false );

		// Check if more than 24 hours have passed since the last update.
		if ( empty( $activated_plugins ) || ( $current_time - $activated_plugins['last_updated'] ) >= 86400 ) {
			// Reset the entire array if 24 hours have passed.
			$activated_plugins = [
				'plugins'      => [],
				'last_updated' => $current_time,
			];
		}

		$plugin_key = $plugin . ' by ' . $current_user_name;

		if ( ! in_array( $plugin_key, $activated_plugins['plugins'] ) ) {
			$activated_plugins['plugins'][] = $plugin_key;
			$activated_plugins['last_updated'] = $current_time;
		}

		// Update the option in the database.
		update_option( 'wpnts_activated_plugins', $activated_plugins );

		/**
		 * Plugin activity log.
		 */
		$plugin_name = strstr($plugin, '/', true);
		$log_message = "Plugin <b>'$plugin_name'</b> has been activated by 👉 <b>$current_user_name.</b> <br>$site_url";
		$severity = 'High';
		$event_type = 'Activated';
		$time = current_time( 'mysql' );

		$ip = $attachmentHandler->get_user_ip();
		$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $current_user_name, $event_type, $log_message  );
		} catch ( Exception $e ) {
			// Log the error but don't break the activation process
			error_log( 'WPNTS Plugin Activation Error: ' . $e->getMessage() );
		}
	}


	/**
	 * Handles the deactivation of a plugin, sending notifications to Slack and email, and updating the activity log.
	 *
	 * @param string $plugin The name of the deactivated plugin.
	 * @param bool   $network_deactivating Whether the deactivation is network-wide (for multisite).
	 * @since 1.0.0
	 */
	public function wpnts_plugin_deactivated( $plugin, $network_deactivating ) {
		try {
			$user_info = $this->get_current_user_safely();
			$current_user_name = $user_info['name'];

			$schedules_int = get_option( 'wpnts_schedules_interval_site_settings');
			$schedules_interval = json_decode($schedules_int);
			$wpnts_webhook = $schedules_interval->webhook ?? '';
			$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

			$slack_webhook_url = $wpnts_webhook;

			// Get the site URL, including child site for multisite.
			$attachmentHandler = new SlackAttachment();
			$site_url = $attachmentHandler->getSiteURLAddOption();

			// Default template for plugin deactivation
			$default_template = ':face_with_raised_eyebrow: Plugin {plugin_name} has been *deactivated* by :arrow_right: {user_name} {site_url}';
			
			// Template data for placeholders
			$template_data = [
				'plugin_name' => $plugin,
				'user_name' => $current_user_name,
			];

			// Send templated notification with custom message support
			$attachmentHandler->send_templated_notification( 
				$slack_webhook_url, 
				$default_template,
				$template_data,
				'High', 
				'Plugin Deactivation',
				'wpnts_schedules_interval_site_settings', // Settings option name
				'plugindeactivation_message', // Template key
				$current_user_name
			);

			// Send In Mail.
			if ( $authorPaneltoMail === true ) {
				// Send email notification.
				$this->sendEmailNotificationPluginActiveDeactive($plugin, $current_user_name, 'deactivated');
			}

			// Update for Dashboard.
			$deactivated_plugins = get_option( 'wpnts_deactivated_plugins', [] );
			$current_time = current_time( 'timestamp', false );

			// Check if more than 24 hours have passed since the last update.
			if ( empty( $deactivated_plugins ) || ( $current_time - $deactivated_plugins['last_updated'] ) >= 86400 ) {
				// Reset the entire array if 24 hours have passed.
				$deactivated_plugins = [
					'plugins'      => [],
					'last_updated' => $current_time,
				];
			}

			$plugin_key = $plugin . ' by ' . $current_user_name;

			if ( ! in_array( $plugin_key, $deactivated_plugins['plugins'] ) ) {
				$deactivated_plugins['plugins'][] = $plugin_key;
				$deactivated_plugins['last_updated'] = $current_time;
			}

			// Update the option in the database.
			update_option( 'wpnts_deactivated_plugins', $deactivated_plugins );

			/**
			 * Save to DB for activity log.
			 */
			$plugin_name = strstr($plugin, '/', true);
			$log_message = "Plugin <b>'$plugin_name'</b> has been deactivated by 👉<b> $current_user_name</b> <br>$site_url";
			$severity = 'High';
			$event_type = 'Deactivated';
			$time = current_time( 'mysql' );
			$ip = $attachmentHandler->get_user_ip();
			$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $current_user_name, $event_type, $log_message  );
		} catch ( Exception $e ) {
			// Log the error but don't break the deactivation process
			error_log( 'WPNTS Plugin Deactivation Error: ' . $e->getMessage() );
		}
	}

	/**
	 * Sends an email notification when a plugin is activated or deactivated.
	 *
	 * @param string $plugin The name of the plugin.
	 * @param string $current_user_name The name of the user performing the action.
	 * @param string $action The action performed, either 'activated' or 'deactivated'.
	 * @since 1.0.0
	 */
	private function sendEmailNotificationPluginActiveDeactive( $plugin, $current_user_name, $action ) {
		$global_api_settings = get_option('wpnts_global_api_settings');
		$wpnts_global_api = json_decode($global_api_settings);

		$mailconfig = $wpnts_global_api->mailconfig ?? false;
		$recipiantmail = $wpnts_global_api->recipiantmail ?? '';

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		// Check if mail configuration is enabled and recipient email is not empty.
		if ( $mailconfig === true && ! empty($recipiantmail) ) {

			$email_message = 'Plugin ' . esc_html($plugin) . " has been $action by 👉 " . esc_html($current_user_name) . ' ' . $site_url;
			$subject = "Plugin $action Notification";
			$attachmentHandler->sendEmailNotification($recipiantmail, $subject, $email_message);

		}
	}



	/**
	 * Site Health notification.
	 */
	public function wpnts_site_health_status_notification() {

		$last_updates = get_option( 'wpnts_last_sitestatus_updates' );
		$current_time = time();

		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings');
		$schedules_interval = json_decode($schedules_int);

		$wpnts_time = isset($schedules_interval->interval_sitehelgth_update) ? (int) $schedules_interval->interval_sitehelgth_update : 10;

		$wpnts_webhook = $schedules_interval->webhook ?? '';
		$sitehelgth = $schedules_interval->sitehelgth ?? 'false';
		$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

		if ( true === $sitehelgth && isset($last_updates) && ( $current_time - $last_updates ) >= $wpnts_time ) {

			$slack_webhook_url = $wpnts_webhook;

			$site_status_transient = get_transient( 'health-check-site-status-result' );
			$site_status = json_decode( $site_status_transient, true );

			// Format the site health status as a string.
			$status_message = ':fire: Site Health Status: Good=' . $site_status['good'] . ', Recommended=' . $site_status['recommended'] . ', Critical=' . $site_status['critical'] . "\n";
			$status_message .= ':arrow_right: ' . '<' . get_bloginfo('url') . '/wp-admin/site-health.php|View details>';

			// Use reusable function for Slack notification with channel routing
			$attachmentHandler = new SlackAttachment();
			$site_url = $attachmentHandler->getSiteURLAddOption();
			$attachmentHandler->send_notification_and_log( 
				$slack_webhook_url, 
				$status_message, 
				'Medium', 
				'Site Health',
				'',
				[],
				'wpnts_schedules_interval_site_settings'
			);

			// Send In Mail.
			if ( $authorPaneltoMail === true ) {
				// Send email notification.
				$this->sendEmailNotificationSiteHelgth($site_status['good'], $site_status['recommended'], $site_status['critical'], get_bloginfo('url') );
			}

			update_option( 'wpnts_last_sitestatus_updates', time() );
		}
	}

	/**
	 * Sends an email notification about the site's health status.
	 *
	 * @param int    $good The number of 'Good' health checks.
	 * @param int    $recommended The number of 'Recommended' health checks.
	 * @param int    $critical The number of 'Critical' health checks.
	 * @param string $blogURL The base URL of the site.
	 * @since 1.0.0
	 */
	private function sendEmailNotificationSiteHelgth( $good, $recommended, $critical, $blogURL ) {
		$global_api_settings = get_option('wpnts_global_api_settings');
		$wpnts_global_api = json_decode($global_api_settings);

		$mailconfig = $wpnts_global_api->mailconfig ?? false;
		$recipiantmail = $wpnts_global_api->recipiantmail ?? '';

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		// Check if mail configuration is enabled and recipient email is not empty.
		if ( $mailconfig === true && ! empty($recipiantmail) ) {

			$viewDetailsLink = '<a href="' . esc_url($blogURL . '/wp-admin/site-health.php') . '">View details</a>';
			$status_message = 'Site Health Status ' . $site_url . ': Good=' . $good . ', Recommended=' . $recommended . ', Critical=' . $critical . "\n";
			$status_message .= '👉 ' . $viewDetailsLink;

			$subject = 'Site Health Status';
			$attachmentHandler->sendEmailNotification($recipiantmail, $subject, $status_message);

		}
	}


	/**
	 * Tracks the total number of logins for each user on a daily LOGIN AND LOGINOUT.
	 *
	 * @param string  $user_login The username of the user logging in.
	 * @param WP_User $user The user object containing details about the user.
	 * @since 1.0.0
	 */
	public function wpnts_user_activity_notification_login( $user_login, $user ) {
		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings' );
		$schedules_interval = json_decode( $schedules_int );
		$wpnts_webhook = $schedules_interval->webhook ?? '';

		$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

		$slack_webhook_url = $wpnts_webhook;

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$message = ":yawning_face: User $user_login has logged in. $site_url";

		// Use notification function for Slack, Telegram, and activity logging with channel routing
		$attachmentHandler->send_notification_and_log( 
			$slack_webhook_url, 
			$message, 
			'High', 
			'Login', 
			$user_login,
			[],
			'wpnts_schedules_interval_site_settings'
		);

		if ( $authorPaneltoMail === true ) {
			// Send email notification.
			$this->sendEmailNotificationSigninout('Login Notification', "User 👉 $user_login has logged in. $site_url");
		}

		// Start session only if not already started and headers not sent
		if ( session_status() === PHP_SESSION_NONE && !headers_sent() ) {
			session_start();
		}
		$_SESSION['wpnts_user_display_name'] = $user->display_name;

		// Add user login information to option table.
		$user_login_info = get_option( 'wpnts_user_login_info', [] );
		$current_time = current_time( 'timestamp', false );

		// Remove users from the login info array if 24 hours have passed since their login.
		foreach ( $user_login_info as $key => $login ) {
			if ( ( $current_time - $login['timestamp'] ) >= 86400 ) {
				unset( $user_login_info[ $key ] );
			}
		}

		// Add the new login information.
		$user_login_info[] = [
			'user'      => $user_login,
			'action'    => 'login',
			'timestamp' => $current_time,
		];

		// Update the option in the database.
		update_option( 'wpnts_user_login_info', array_values( $user_login_info ) );

		/**
		 * Save to DB for activity log.
		 */

		$log_message = "User 👉 <b> $user_login </b> has logged in. <br>$site_url";
		$severity = 'High';
		$event_type = 'Login';
		$time = current_time( 'mysql' );

		$ip = $attachmentHandler->get_user_ip();
		$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $user_login, $event_type, $log_message  );
	}

	/**
	 * Tracks the total number of logins for each user on a daily basis.
	 *
	 * This method tracks and stores the total number of times a user logs in each day.
	 * The login count is reset every week (on a specified reset day, e.g., Saturday),
	 * and the data is saved in the WordPress options table. If it's a new day, the login
	 * count is reset for that user.
	 *
	 * @param string  $user_login The username of the user logging in.
	 * @param WP_User $user The user object containing details about the user.
	 * @since 1.0.0
	 */
	public function wpnts_user_login_total_count( $user_login, $user ) {
		$_SESSION['wpnts_user_display_name'] = $user->display_name;

		// Add user login information to option table.
		$user_login_info = get_option( 'wpnts_user_daily_login_info', [] );

		if ( is_array( $user_login_info ) ) {
			$current_time = current_time( 'timestamp', false );
			$current_day = gmdate('l', $current_time); // Get the current day of the week.
			$current_date = gmdate('Y-m-d', $current_time); // Get the current date.

			// Define the day to reset the count (e.g., Saturday).
			$reset_day = 'Saturday';

			$first_saturday_reset_done = get_option('wpnts_first_saturday_reset_done', 'false');

			// Check if it's a new week and reset the daily login count for all users.
			if ( $current_day === $reset_day && $first_saturday_reset_done === 'false' ) {
				$user_login_info = []; // Reset the entire array.
				update_option('wpnts_first_saturday_reset_done', 'true');
			} else if ( $current_day !== $reset_day && $first_saturday_reset_done === 'true' ) {
				// Reset the flag when it's no longer Saturday
				update_option('wpnts_first_saturday_reset_done', 'false');
			}

			// Check if the user has logged in before.
			$user_found = false;
			foreach ( $user_login_info as &$login ) {
				if ( $login['user'] === $user_login ) {

					// Check if it's a new day.
					if ( $current_date !== $login['last_reset_day'] ) {
						// Reset the daily login count for a new day.
						$login['daily_login_count'] = 1;
						$login['last_reset_day'] = $current_date;
					} else {
						// If it's the same day, increment the daily login count for the current day.
						$login['daily_login_count']++;
					}

					// Update the timestamp to the current login time.
					$login['timestamp'] = $current_time;

					$user_found = true;
					break;
				}
			}

			if ( ! $user_found ) {
				// Add the new login information for a new user.
				$user_login_info[] = [
					'user'             => $user_login,
					'action'           => 'login',
					'timestamp'        => $current_time,
					'daily_login_count' => 1,
					'last_reset_day'   => $current_date,
				];
			}

			// Update the option in the database.
			update_option( 'wpnts_user_daily_login_info', array_values( $user_login_info ) );
		}
	}



	/**
	 * Tracks failed login attempts for a user.
	 *
	 * This method records failed login attempts for a specific user on a daily basis,
	 * allowing administrators to monitor and track login failures. If the user has already
	 * failed to log in on the current day, the count is incremented. If it's the user's
	 * first failed login of the day, a new log entry is created.
	 *
	 * @param string $username The username for which the failed login is being tracked.
	 * @since 1.0.0
	 */
	public function wpnts_user_track_failed_login( $username ) {
		$log_data = get_option('wpnts_user_track_failed_login', array()); // Get existing data.

		// Get the current date.
		$current_date = gmdate('Y-m-d'); // Use date format instead of weekday name
		$current_time = time();

		// Clean up old entries (older than 24 hours)
		foreach ( $log_data as $key => $log_entry ) {
			if ( ( $current_time - $log_entry['timestamp'] ) >= 86400 ) {
				unset( $log_data[ $key ] );
			}
		}

		// Initialize the daily login count for the user.
		$daily_failed_count = 1; // Default to 1 for a new day.

		// Flag to check if a matching entry was found.
		$entry_found = false;

		// Check if there are existing log entries for the user.
		foreach ( $log_data as &$log_entry ) {
			if ( $log_entry['user'] === $username && $log_entry['last_reset_day'] === $current_date ) {
				// If a log entry exists for the same user on the same day, increment the count.
				$log_entry['daily_failed_count']++;
				$log_entry['timestamp'] = $current_time; // Update timestamp
				$entry_found = true;
				break; // Exit the loop since we found a matching entry.
			}
		}

		// If no matching entry was found, create a new log entry.
		if ( ! $entry_found ) {
			// Log failed login attempt.
			$log_entry = array(
				'user' => $username,
				'timestamp' => $current_time,
				'last_reset_day' => $current_date, // Initialize or update 'last_reset_day'.
				'daily_failed_count' => $daily_failed_count,
				'action' => 'failed',
			);

			$log_data[] = $log_entry;
		}

		// Update the option in the database.
		update_option('wpnts_user_track_failed_login', array_values($log_data));
	}



	/**
	 * Sends a notification when a user logs out of the site.
	 *
	 * This method sends a notification to a specified Slack channel with the user's display name
	 * and the site URL. It also sends an email notification if configured in the site settings.
	 * Additionally, the logout event is logged in the database for activity tracking.
	 *
	 * @since 1.0.0
	 */
	public function wpnts_user_activity_notification_logout() {
		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings');
		$schedules_interval = json_decode($schedules_int);
		$wpnts_webhook = $schedules_interval->webhook ?? '';
		$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

		$slack_webhook_url = $wpnts_webhook;

		// Start session only if not already started and headers not sent
		if ( session_status() === PHP_SESSION_NONE && !headers_sent() ) {
			session_start();
		}
		$user_display_name = isset($_SESSION['wpnts_user_display_name']) ? sanitize_text_field($_SESSION['wpnts_user_display_name']) : '';

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$message = ":smiling_face_with_tear: User $user_display_name has logged out. $site_url";

		// Use notification function for Slack, Telegram, and activity logging with channel routing
		$attachmentHandler->send_notification_and_log( 
			$slack_webhook_url, 
			$message, 
			'Normal', 
			'Logout', 
			$user_display_name,
			[],
			'wpnts_schedules_interval_site_settings'
		);

		if ( $authorPaneltoMail === true ) {
			// Send email notification.
			$this->sendEmailNotificationSigninout('Logout Notification', "User 👉 $user_display_name has logged out. $site_url");
		}

		// Add user logout information to option table.
		$user_logout_info = get_option( 'wpnts_user_login_info', [] );
		$current_time = current_time( 'timestamp', false );

		// Remove users from the login info array if 24 hours have passed since their login.
		foreach ( $user_logout_info as $key => $login ) {
			if ( ( $current_time - $login['timestamp'] ) >= 86400 ) {
				unset( $user_logout_info[ $key ] );
			}
		}

		// Add the new logout information.
		$user_logout_info[] = [
			'user'      => $user_display_name,
			'action'    => 'logout', // This is a logout action, not login
			'timestamp' => $current_time,
		];

		// Update the option in the database.
		update_option( 'wpnts_user_login_info', array_values( $user_logout_info ) );

		/**
		 * Save to DB for activity log.
		 */

		 $log_message = "User 👉 <b>$user_display_name</b> has logged out. <br>$site_url";
		 $severity = 'Normal';
		 $event_type = 'Logout';
		 $time = current_time( 'mysql' );

		 $ip = $attachmentHandler->get_user_ip();
		 $attachmentHandler->log_activity_to_db( $severity, $time, $ip, $user_display_name, $event_type, $log_message  );
	}

	/**
	 * Sends a notification when a new user registers on the site.
	 *
	 * This method sends a notification to a specified Slack channel with the new user's details,
	 * including username and email. It also sends an email notification if configured in the
	 * site settings. Additionally, the registration event is logged in the database for activity
	 * tracking.
	 *
	 * @param int $user_id The ID of the newly registered user.
	 * @since 1.0.0
	 */
	public function wpnts_new_user_notification( $user_id ) {
		$user = get_userdata( $user_id );
		$schedules_int = get_option( 'wpnts_schedules_interval_site_settings');
		$schedules_interval = json_decode($schedules_int);
		$wpnts_webhook = $schedules_interval->webhook ?? '';
		$authorPaneltoMail = $schedules_interval->authorPaneltoMail ?? false;

		$slack_webhook_url = $wpnts_webhook;

		// Get the site URL, including child site for multisite.
		$attachmentHandler = new SlackAttachment();
		$site_url = $attachmentHandler->getSiteURLAddOption();

		$message = "New user registered $site_url on your site:\n\nUsername:" . $user->user_login . "\nEmail: " . $user->user_email;
		
		// Use reusable function for Slack notification with channel routing
		$attachmentHandler->send_notification_and_log( 
			$slack_webhook_url, 
			$message, 
			'High', 
			'User Registration',
			$user->user_login,
			[],
			'wpnts_schedules_interval_site_settings'
		);

		if ( $authorPaneltoMail === true ) {
			// Send email notification.
			$this->sendEmailNotificationSigninout('New User Notification', $message);
		}

		/**
		 * Save to DB for activity log.
		 */

		 $severity = 'High';
		 $event_type = 'Register';
		 $time = current_time( 'mysql' );

		 $ip = $attachmentHandler->get_user_ip();
		 $attachmentHandler->log_activity_to_db( $severity, $time, $ip, $user->user_login, $event_type, $message  );
	}


	 /**
	  * Sends an email notification for user sign-in and sign-out events.
	  *
	  * This method checks the global API settings to ensure email notifications are enabled
	  * and a recipient email address is provided. If both conditions are met, it sends an email
	  * notification with the specified subject and status message using the `SlackAttachment`
	  * class's `sendEmailNotification` method.
	  *
	  * @param string $subject The subject of the email notification.
	  * @param string $status_message The status message to include in the email body.
	  * @since 1.0.0
	  */
	private function sendEmailNotificationSigninout( $subject, $status_message = '' ) {
		$global_api_settings = get_option('wpnts_global_api_settings');
		$wpnts_global_api = json_decode($global_api_settings);

		$mailconfig = $wpnts_global_api->mailconfig ?? false;
		$recipiantmail = $wpnts_global_api->recipiantmail ?? '';

		$attachmentHandler = new SlackAttachment();

		// Check if mail configuration is enabled and recipient email is not empty.
		if ( $mailconfig === true && ! empty($recipiantmail) ) {
			$attachmentHandler->sendEmailNotification($recipiantmail, $subject, $status_message);
		}
	}

	/**
	 * Handles the notification and logging of WordPress plugin updates.
	 *
	 * Sends a Slack notification when a plugin is updated, including the plugin name
	 * and the user who performed the update. Logs the update activity in the database
	 * with details such as severity, event type, and timestamp.
	 *
	 * @param WP_Upgrader $upgrader_object The upgrader object responsible for updates.
	 * @param array       $options Array containing details about the update process.
	 * @since 1.0.0
	 */
	public function wpnts_plugin_updated( $upgrader_object, $options ) {
		try {
			if ( $options['action'] === 'update' && $options['type'] === 'plugin' ) {

				// Check if plugins array exists and is not empty
				if ( ! isset( $options['plugins'] ) || ! is_array( $options['plugins'] ) || empty( $options['plugins'] ) ) {
					return;
				}

				$user_info = $this->get_current_user_safely();
				$updated_by = $user_info['name'];
				foreach ( $options['plugins'] as $plugin ) {
					$plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
					$plugin_name = $plugin_data['Name'];

					// Get the site URL, including child site for multisite.
					$attachmentHandler = new SlackAttachment();

					// Default template for plugin update
					$default_template = ':package: Plugin {plugin_name} has been updated by {user_name}. {site_url}';
					
					// Template data for placeholders
					$template_data = [
						'plugin_name' => $plugin_name,
						'user_name' => $updated_by,
					];

					// Send templated notification with custom message support
					$attachmentHandler->send_templated_notification( 
						$attachmentHandler->getSiteURLAddOption() ? 
							json_decode(get_option('wpnts_schedules_interval_site_settings'))->webhook : '', 
						$default_template,
						$template_data,
						'High', 
						'Plugin Update',
						'wpnts_schedules_interval_site_settings', // Settings option name
						'pluginupdate_message', // Template key
						$updated_by
					);

					$log_message = "Plugin <b>'$plugin_name'</b> has been updated by 👉 <b>$updated_by.</b>. <br>" . $attachmentHandler->getSiteURLAddOption();
					$severity = 'High';
					$event_type = 'Updated';
					$time = current_time( 'mysql' );

					$ip = $attachmentHandler->get_user_ip();
					$attachmentHandler->log_activity_to_db( $severity, $time, $ip, $updated_by, $event_type, $log_message  );

				}
			}
		} catch ( Exception $e ) {
			// Log the error but don't break the update process
			error_log( 'WPNTS Plugin Update Error: ' . $e->getMessage() );
		}
	}

	/**
	 * Safely get the current user with fallback.
	 *
	 * @return array Array with 'name' and 'id' keys
	 * @since 1.0.0
	 */
	private function get_current_user_safely() {
		// Check if we're in admin context and WordPress is fully loaded
		if ( ! is_admin() && ! defined( 'DOING_CRON' ) ) {
			return array( 'name' => 'System', 'id' => 0 );
		}

		// Ensure WordPress functions are available
		if ( ! function_exists( 'wp_get_current_user' ) ) {
			if ( file_exists( ABSPATH . 'wp-includes/pluggable.php' ) ) {
				require_once( ABSPATH . 'wp-includes/pluggable.php' );
			} else {
				// If pluggable.php is not available, return system user
				return array( 'name' => 'System', 'id' => 0 );
			}
		}

		// Additional check to ensure function is callable
		if ( ! function_exists( 'wp_get_current_user' ) ) {
			return array( 'name' => 'System', 'id' => 0 );
		}

		$current_user = wp_get_current_user();
		
		// Check if we have a valid user
		if ( $current_user && $current_user->ID ) {
			return array( 
				'name' => $current_user->display_name, 
				'id' => $current_user->ID 
			);
		}
		
		// Fallback to system user
		return array( 'name' => 'System', 'id' => 0 );
	}


	/**
	 * Sends a notification message to a configured Slack webhook using reusable function with channel routing.
	 *
	 * This function formats a message with an optional emoji and sends it to the Slack webhook URL
	 * specified in the plugin's comment settings, with support for custom channels and user tags.
	 *
	 * @param string $message The message to send to Slack.
	 * @param string $emoji   An optional emoji to prepend to the message.
	 * @return void
	 */
	private function wpnts_notify_slack( $message, $emoji = '' ) {
		$formatted_message = $emoji . ' ' . $message;
		
		// Use SlackChannelRouter for channel and user tag support
		SlackChannelRouter::send_notification_with_routing(
			'wpnts_schedules_interval_site_settings',
			$formatted_message
		);
	}
}
