<?php
/**
 * Plugin Name: Activity Guard
 *
 * @author            wpazleen
 * @copyright         2024- wpazleen
 * @license           GPL-2.0-or-laters
 * @package Activity Guard
 *
 * @wordpress-plugin
 * Plugin Name: Activity Guard
 * Plugin URI: https://wordpress.org/plugins/notifier-to-slack/
 * Description: Activity Guard – A Real-Time Notifier for System & User Activity Logs with advanced security and analytics. Monitor user behavior, system events, WooCommerce activity, and support forums in real time with instant alerts via Slack, Telegram, and Email.
 * Version:           3.11.2
 * Requires at least: 5.9
 * Requires PHP:      5.6
 * Author:            wpazleen
 * Author URI:        https://profiles.wordpress.org/wpazleen/
 * Text Domain:       notifier-to-slack
 * Domain Path: /languages/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! function_exists( 'wpnts_nts_fs' ) ) { // Freemium SDK function also prefixed.
	/**
	 * Freemius SDK with smart initialization - "Pro Takes Ownership, Free Steps Aside" pattern.
	 *
	 * @since 1.0.0
	 * @return object Freemius SDK object.
	 */
	function wpnts_nts_fs() {
		global $wpnts_nts_fs;

		if ( ! isset( $wpnts_nts_fs ) ) {
			// Check if Pro version is active - if so, let Pro handle Freemius
			if ( is_plugin_active( 'notifier-to-slack-pro/notifier-to-slack-pro.php' ) ) {
				// Pro is active - Free steps aside, only load analytics
				return null; // Pro will handle all Freemius functionality
			}

			// Activate multisite network integration.
            if ( ! defined( 'WP_FS__PRODUCT_14342_MULTISITE' ) ) {
                define( 'WP_FS__PRODUCT_14342_MULTISITE', true );
            }

			// Include Freemius SDK.
			require_once __DIR__ . '/vendor/freemius/start.php';

			$wpnts_nts_fs = fs_dynamic_init( array(
				'id'                  => '14342',
				'slug'                => 'notifier-to-slack',
				'premium_slug'        => 'notifier-to-slack-pro',
				'type'                => 'plugin',
				'public_key'          => 'pk_bc3d08a262990e44dee3cb5bb42a8',
				'is_premium'          => false,
				'has_premium_version' => true,
				'has_paid_plans'      => true,
				'is_org_compliant'    => true,
				'menu'                => array(
					'slug'           => 'notifier-to-slack',
					'first-path'     => 'admin.php?page=notifier-to-slack',
					'network'        => true,
					'pricing'        => true,
					'contact'        => true,
					'support'        => true,
				),

				'parallel_activation' => array(
                    'enabled'                  => true,
                    'premium_version_basename' => 'notifier-to-slack-pro/notifier-to-slack-pro.php',
                ),

				// 'is_live'             => true,
			) );
		}

		return $wpnts_nts_fs;
	}
	
	// Only initialize if Pro is not active
	if ( ! is_plugin_active( 'notifier-to-slack-pro/notifier-to-slack-pro.php' ) ) {
		wpnts_nts_fs();
		do_action( 'wpnts_nts_fs_loaded' );
	}
}

/**
 * Helper function to check if Free should handle analytics when Pro is active.
 * Even when Pro takes ownership, Free can still collect analytics data.
 *
 * @since 3.11.2
 * @return bool Whether Free should handle analytics.
 */
function wpnts_should_handle_analytics() {
	// Free always handles its own analytics, even when Pro is active
	return true;
}

/**
 * Helper function to check if Freemius is available (either from Free or Pro).
 *
 * @since 3.11.2
 * @return object|null Freemius SDK object or null.
 */
function wpnts_get_freemius_instance() {
	// If Pro is active, get Freemius instance from Pro
	if ( is_plugin_active( 'notifier-to-slack-pro/notifier-to-slack-pro.php' ) ) {
		// Pro handles Freemius, so get it from Pro's function
		if ( function_exists( 'wpnts_pro_get_freemius_instance' ) ) {
			return wpnts_pro_get_freemius_instance();
		}
		// Fallback: try to get Pro's Freemius instance directly
		return function_exists( 'wpnts_nts_fs' ) ? wpnts_nts_fs() : null;
	}
	
	// Otherwise, Free handles it
	return function_exists( 'wpnts_nts_fs' ) ? wpnts_nts_fs() : null;
}

// If direct access than exit the file.
defined('ABSPATH') || die('Hey, what are you doing here? You silly human!');
define( 'WP_NOTIFIER_TO_SLACK_VERSION', '3.11.2' );
define( 'WP_NOTIFIER_TO_SLACK__FILE__', __FILE__ );
define( 'WP_NOTIFIER_TO_SLACK_DIR', __DIR__ );
define( 'WP_NOTIFIER_TO_SLACK_DIR_PATH', plugin_dir_path( WP_NOTIFIER_TO_SLACK__FILE__ ) );
define( 'WP_NOTIFIER_TO_SLACK_URL', plugins_url( '', __FILE__ ) );
define( 'WP_NOTIFIER_TO_SLACK_DIR_URL', plugin_dir_url( __FILE__ ) );
define( 'WP_NOTIFIER_TO_SLACK_NAME', plugin_dir_url( __FILE__ ) );
define('NOTIFIER_TO_SLACK_PLUGIN_BASENAME', plugin_basename(__FILE__));

if ( file_exists(__DIR__ . '/vendor/autoload.php') ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

/**
 * All Namespace.
 */
use WPNTS\Inc\Ajax\Ajax;
use WPNTS\Inc\Menu;
use WPNTS\Inc\Theme;
use WPNTS\Inc\Route;
use WPNTS\Inc\Media;
use WPNTS\Inc\Notify;
use WPNTS\Inc\Capcha;
use WPNTS\Inc\Enqueue;
use WPNTS\Inc\WPUpdate;
use WPNTS\Inc\Security;
use WPNTS\Inc\Notices;
use WPNTS\Inc\Scanner;
use WPNTS\Inc\Comment;
use WPNTS\Inc\Debuglog;
use WPNTS\Inc\Activate;
use WPNTS\Inc\DbTables;
use WPNTS\Inc\Websitecron;
use WPNTS\Inc\Postnotice;
use WPNTS\Inc\Wpwidgets;
use WPNTS\Inc\Deactivate;
use WPNTS\Inc\Database\DB;
use WPNTS\Inc\Maintenance;
use WPNTS\Inc\Integration;
use WPNTS\Inc\WooCommerce;
use WPNTS\Inc\PluginUpdate;
use WPNTS\Inc\AdminDashboard;
use WPNTS\Inc\BaseController;
use WPNTS\Inc\NotifierReview;
use WPNTS\Inc\NotifierSupport;
use WPNTS\Inc\SlackAttachment;
use WPNTS\Inc\SlackChannelRouter;
use WPNTS\Inc\TelegramNotifier;
use WPNTS\Inc\CartAbandonmentTracker;


if ( ! class_exists('WPNTSNotifier') ) {
	/**
	 * Main plugin class.
	 *
	 * @since 1.0.0
	 */
	class WPNTSNotifier {
		/**
		 * Holds the plugin base file
		 *
		 * @since 1.0.0
		 * @var WPNTS
		 */
		public $WP_NOTIFIER_TO_SLACK;
		/**
		 * Constructor of the plugin.
		 *
		 * @since 1.0.0
		 * @var WPNTS
		 */
		public function __construct() {
			$this->includes();
			$this->WP_NOTIFIER_TO_SLACK = plugin_basename(__FILE__);
		}
		/**
		 * Register
		 */
		public function register() {
			add_action('plugins_loaded', [ $this, 'wpnts_load' ]);
			add_action('admin_init', [ $this, 'wpnts_plugin_activation' ]);
			add_filter( 'cron_schedules', [ $this, 'add_custom_cron_intervals' ] );
		}
		/**
		 * Main Plugin Textdomain.
		 */
		public static function wpnts_load() {
			load_plugin_textdomain('notifier-to-slack', false,__DIR__ . 'languages');
		}
		/**
		 * Classes instantiating here.
		 */
		public function includes() {
			new AdminDashboard();
			$enqueue = new Enqueue();
			$enqueue->register();
			
			// Schedule daily cleanup for 7-day rolling analytics
			$this->schedule_seven_day_analytics_cleanup();
			
			// Schedule daily cleanup for incomplete orders
			$this->schedule_incomplete_orders_cleanup();

			new BaseController();
			new DbTables();
			new Route();
			// Calling Ajax.
			new Ajax();
			// Active and Deactivation notification.
			new Menu();
			new Debuglog();
			new Wpwidgets();
			new Comment();
			new Security();
			new Scanner();
			// Cart abandonment tracking with cron jobs
			new CartAbandonmentTracker();
			$active  = new Notify();
			$media  = new Media();
			$theme  = new Theme();
			$websitecron  = new Websitecron();
			$notice  = new Notices();
			$postnotice  = new Postnotice();
			$captchaactive  = new Capcha();
			// All plugin update notification.
			$update = new PluginUpdate();
			$update->wpnts_plugin_update_notification();
			// WordPress Core version update notification.
			$wpupdate = new WPUpdate();
			$wpupdate->wpnts_wordpress_core_update();
			// Plugin ORG support case notification.
			$load_support = new NotifierSupport();
			$load_support->wpnts_support_tickets();
			// Plugin review notification.
			$load_review = new NotifierReview();
			$load_review->wpnts_review_tickets();
			$maintenannotice_mode = new Maintenance();
			$integrations = new Integration();
			$woocoomerce_product = new WooCommerce();
			$slackattachment = new SlackAttachment();
		}
		/**
		 * While active the plugin redirect.
		 *
		 * @since 1.0.0
		 */
		public function wpnts_plugin_activation() {
			// Check if this is a fresh activation.
			$is_fresh_activation = ! get_option('NotifierActivationTime');

			if ( $is_fresh_activation ) {
				add_option('NotifierActivationTime', time());
				// Review Notice.
				add_option('NotifierReviewNotice', 0);
				add_option('DefaultNTReviewNoticeInterval', ( time() + 7 * 24 * 60 * 60 ));
				// Upgrade notice options.
				add_option('NotifierUpgradeNotice', 0);
				add_option('DefaultNTUpgradeInterval', ( time() + 10 * 24 * 60 * 60 ));
			}

			// Check if activation occurred within the last 5 days.
			$activation_time = get_option('NotifierActivationTime');
			// If we have an activation time, calculate the days since activation.
			if ( $activation_time ) {
				$days_since_activation = floor(( time() - $activation_time ) / ( 60 * 60 * 24 ));

				// Check if setup wizard was completed.
				$wizard_completed = get_option('notifier_ran_setup_wizard', false);

				// If user activated the plugin within the last 2 days and hasn't completed the wizard, ensure it's incomplete.
				if ( $days_since_activation <= 2 && ! $wizard_completed ) {
					update_option('notifier_ran_setup_wizard', false);
				} elseif ( $days_since_activation > 2 ) {
					update_option('notifier_ran_setup_wizard', true);
				}
			} else {
				update_option('notifier_ran_setup_wizard', false);
			}

			$redirect_to_admin_page = absint(get_option('nts_activation_redirect', 0));

			if ( 1 === $redirect_to_admin_page ) {
				delete_option('nts_activation_redirect');
				wp_safe_redirect(admin_url('admin.php?page=notifier-to-slack'));
				exit;
			}
		}

		/**
		 * Activation Hook.
		 */
		public function wpnts_activate() {
			Activate::wpnts_activate();
		}
		/**
		 * Deactivation Hook.
		 */
		public function wpnts_deactivate() {
			Deactivate::wpnts_deactivate();
		}

		/**
		 * Schedule daily cleanup for 7-day rolling analytics
		 */
		private function schedule_seven_day_analytics_cleanup() {
			// Schedule daily cleanup if not already scheduled
			if (!wp_next_scheduled('wpnts_seven_day_analytics_cleanup')) {
				wp_schedule_event(time(), 'daily', 'wpnts_seven_day_analytics_cleanup');
			}

			// Hook the cleanup function
			add_action('wpnts_seven_day_analytics_cleanup', [$this, 'run_seven_day_analytics_cleanup']);
		}

		/**
		 * Run the 7-day analytics cleanup
		 */
		public function run_seven_day_analytics_cleanup() {
			// Check if 7-day analytics is enabled
			$security_settings = get_option('wpnts_webhook_site_settings', '{}');
			$settings = json_decode($security_settings, true);
			
			if (isset($settings['seven_day_rolling_analytics']) && $settings['seven_day_rolling_analytics'] === true) {
				$seven_days_ago_timestamp = strtotime('-7 days');
				$seven_days_ago_date = date('Y-m-d', $seven_days_ago_timestamp);
				$cleaned_count = 0;

				// Clean up old login data (older than 7 days)
				$all_login_data = get_option('wpnts_user_login_info', []);
				$original_login_count = count($all_login_data);
				$cleaned_login_data = [];
				
				foreach ($all_login_data as $login) {
					if (isset($login['timestamp']) && $login['timestamp'] >= $seven_days_ago_timestamp) {
						$cleaned_login_data[] = $login;
					}
				}
				
				if (count($cleaned_login_data) !== $original_login_count) {
					update_option('wpnts_user_login_info', $cleaned_login_data);
					$cleaned_count += ($original_login_count - count($cleaned_login_data));
				}

				// Clean up old failed login data (older than 7 days)
				$all_failed_login_data = get_option('wpnts_user_track_failed_login', []);
				$original_failed_count = count($all_failed_login_data);
				$cleaned_failed_data = [];
				
				foreach ($all_failed_login_data as $failed_login) {
					if (isset($failed_login['last_reset_day']) && $failed_login['last_reset_day'] >= $seven_days_ago_date) {
						$cleaned_failed_data[] = $failed_login;
					}
				}
				
				if (count($cleaned_failed_data) !== $original_failed_count) {
					update_option('wpnts_user_track_failed_login', $cleaned_failed_data);
					$cleaned_count += ($original_failed_count - count($cleaned_failed_data));
				}

				// Clean up old daily login data (older than 7 days)
				$daily_login_data = get_option('wpnts_user_daily_login_info', []);
				$original_daily_count = count($daily_login_data);
				$cleaned_daily_data = [];
				
				foreach ($daily_login_data as $daily_login) {
					if (isset($daily_login['last_reset_day']) && $daily_login['last_reset_day'] >= $seven_days_ago_date) {
						$cleaned_daily_data[] = $daily_login;
					}
				}
				
				if (count($cleaned_daily_data) !== $original_daily_count) {
					update_option('wpnts_user_daily_login_info', $cleaned_daily_data);
					$cleaned_count += ($original_daily_count - count($cleaned_daily_data));
				}

				// Log the cleanup activity if any data was cleaned
				if ($cleaned_count > 0) {
					$slackattachment = new SlackAttachment();
					$slackattachment->log_activity_to_db(
						'Info',
						current_time('mysql'),
						'System',
						'System',
						'Cleanup',
						"7-Day Rolling Analytics: Cleaned up {$cleaned_count} old login/logout records older than 7 days."
					);
				}
			}
		}

		/**
		 * Schedule daily cleanup for incomplete orders
		 */
		private function schedule_incomplete_orders_cleanup() {
			// Schedule daily cleanup if not already scheduled
			if (!wp_next_scheduled('wpnts_incomplete_orders_cleanup')) {
				wp_schedule_event(time(), 'daily', 'wpnts_incomplete_orders_cleanup');
			}

			// Hook the cleanup function
			add_action('wpnts_incomplete_orders_cleanup', [$this, 'run_incomplete_orders_cleanup']);
		}

		/**
		 * Run the incomplete orders cleanup
		 */
		public function run_incomplete_orders_cleanup() {
			$wpnts_db_instance = new DB();
			$wpnts_db_instance->cleanup_old_incomplete_orders();
		}

		/**
		 * Add custom cron intervals
		 */
		public function add_custom_cron_intervals( $schedules ) {
			// Add 5-minute interval for cart abandonment checks
			$schedules['wpnts_five_minutes'] = [
				'interval' => 300, // 5 minutes in seconds
				'display'  => __( 'Every 5 Minutes', 'notifier-to-slack' )
			];
			
			// Add 15-minute interval as alternative
			$schedules['wpnts_fifteen_minutes'] = [
				'interval' => 900, // 15 minutes in seconds
				'display'  => __( 'Every 15 Minutes', 'notifier-to-slack' )
			];
			
			return $schedules;
		}

		
	}


	/**
	 * Instantiate an Object Class.
	 */
	$wpnts = new WPNTSNotifier();
	$wpnts->register();

	register_activation_hook (WP_NOTIFIER_TO_SLACK__FILE__, [ $wpnts, 'wpnts_activate' ] );
	register_deactivation_hook (WP_NOTIFIER_TO_SLACK__FILE__, [ $wpnts, 'wpnts_deactivate' ] );
}
