<?php
/**
 * Plugin Name: Automation Web Platform – Notifications, OTP, and Advanced Phone Field
 * Plugin URI: https://wawp.net
 * Description: Automation Web Platform (Wawp) - Automate notifications, secure your store with OTP, and optimize checkout with an advanced phone field.
 * Version: 5.6.3
 * Author: wawp.net
 * Author URI: https://wawp.net
 * License: GPLv3 or later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 * Text Domain: automation-web-platform
 * Domain Path: /languages
 *
 * @package automation-web-platform
 */

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


if ( ! defined( 'WAWP_PLUGIN_DIR' ) ) {
	define( 'WAWP_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}

if ( ! defined( 'WAWP_PLUGIN_URL' ) ) {
	define( 'WAWP_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}

if ( ! defined( 'WAWP_PLUGIN_FILE' ) ) {
	define( 'WAWP_PLUGIN_FILE', __FILE__ );
}

if ( ! defined( 'WAWP_PLUGIN_VERSION' ) ) {
	define( 'WAWP_PLUGIN_VERSION', '5.6.3' );
}

if ( ! defined( 'WAWP_CAPABILITY' ) ) {
	define( 'WAWP_CAPABILITY', 'manage_wawp' );
}

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

require_once WAWP_PLUGIN_DIR . 'includes/traits/trait-wawp-settings-handler.php';
require_once WAWP_PLUGIN_DIR . 'includes/traits/trait-wawp-security-trait.php';
require_once WAWP_PLUGIN_DIR . 'includes/helpers/class-wawp-cache-compat.php';
add_action( 'plugins_loaded', array( 'WAWP_Cache_Compat', 'init' ), 1 );


/**
 * Main WAWP Class.
 */
final class WAWP {
	use WAWP_Settings_Handler;
	use WAWP_Security_Trait;

	/**
	 * Singleton instance.
	 *
	 * @var WAWP|null
	 */
	private static $instance = null;

	/**
	 * Cache for user data to avoid redundant DB/Transient calls.
	 *
	 * @var array|null
	 */
	private $user_data_cache = null;

	/**
	 * Database Manager instance.
	 *
	 * @var WAWP_Database_Manager|null
	 */
	public $db = null;

	/**
	 * Unified log instance.
	 *
	 * @var WAWP_Unified_Log|null
	 */
	public $unified_log;

	/**
	 * Block manager instance.
	 *
	 * @var WAWP_Block_Manager|null
	 */
	public $block_manager;

	/**
	 * Instance manager.
	 *
	 * @var WAWP_Instance_Manager|null
	 */
	public $instance_manager;

	/**
	 * Notification manager.
	 *
	 * @var WAWP_Notification_Manager|null
	 */
	public $notification_manager;

	/**
	 * User manager.
	 *
	 * @var WAWP_User_Manager|null
	 */
	public $user_manager;

	/**
	 * Campaigns manager.
	 *
	 * @var WAWP_Campaigns_Advanced|null
	 */
	public $campaigns;

	/**
	 * Flow builder instance.
	 *
	 * @var WAWP_Flow_Builder|null
	 */
	public $flow_builder;

	/**
	 * Enabled features map.
	 *
	 * @var array
	 */
	public $enabled_features = array();

	/**
	 * Connector instance.
	 *
	 * @var WAWP_Connector|null
	 */
	public $connector = null;

	/**
	 * Senders instance.
	 *
	 * @var WAWP_Senders|null
	 */
	public $senders = null;

	/**
	 * System info instance.
	 *
	 * @var WAWP_System_Info|null
	 */
	public $system_info;

	/**
	 * Chat widget instance.
	 *
	 * @var WAWP_Chat_Widget|null
	 */
	public $chat_widget;

	/**
	 * Custom pages manager.
	 *
	 * @var WAWP_Custom_Login_Pages|null
	 */
	public $custom_pages;

	/**
	 * Stats manager.
	 *
	 * @var WAWP_Stats_Manager|null
	 */
	public $stats_manager;

	/**
	 * OTP login manager.
	 *
	 * @var WAWP_Otp_Login|null
	 */
	public $otp;

	/**
	 * Abandoned carts manager.
	 *
	 * @var WAWP_Abandoned_Carts|null
	 */
	public $abandoned_carts;

	/**
	 * Messaging service.
	 *
	 * @var WAWP_Messaging_Service|null
	 */
	public $messenger;

	/**
	 * Email templates manager.
	 *
	 * @var WAWP_Email_Templates|null
	 */
	public $email_templates;

	/**
	 * Others manager.
	 *
	 * @var WAWP_Others|null
	 */
	public $others;

	/**
	 * Admin users manager.
	 *
	 * @var WAWP_Admin_Users|null
	 */
	public $admin_users;

	/**
	 * Instances alias (backward compatibility).
	 *
	 * @var WAWP_Senders|null
	 */
	public $instances;

	/**
	 * Main instance of WAWP.
	 *
	 * @return WAWP
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * WAWP Constructor.
	 */
	private function __construct() {
		$this->define_constants();
		$this->includes();
		$this->init_hooks();
	}

	/**
	 * Define constants.
	 */
	private function define_constants() {
		// Constants are already defined at the top of this file to support trait loading.
	}

	/**
	 * Include core files.
	 */
	private function includes() {
		require_once WAWP_PLUGIN_DIR . 'includes/autoload.php';
		require_once WAWP_PLUGIN_DIR . 'views/class-wawp-enqueue-scripts.php';
		require_once WAWP_PLUGIN_DIR . 'views/wawp-deactivation-survey.php';

		// Load Action Scheduler.
		if ( file_exists( WAWP_PLUGIN_DIR . 'includes/libraries/action-scheduler/action-scheduler.php' ) ) {
			require_once WAWP_PLUGIN_DIR . 'includes/libraries/action-scheduler/action-scheduler.php';
		}
	}

	/**
	 * Initialize hooks.
	 */
	private function init_hooks() {
		add_action( 'plugins_loaded', array( $this, 'handle_missing_js_chunk_fallback' ), 5 );
		add_action( 'init', array( $this, 'ensure_capabilities' ) );
		add_action( 'init', array( $this, 'record_system_cron' ) );
		add_action( 'init', array( $this, 'handle_email_tracking' ) );
		add_action( 'init', array( $this, 'register_bricks_elements' ), 11 );
		add_action( 'admin_init', array( $this, 'handle_activation_redirect' ) );
		add_action( 'plugins_loaded', array( $this, 'init_plugin' ), 10 );
		add_action( 'plugins_loaded', array( $this, 'check_version_update' ), 20 );
		add_action( 'cron_schedules', array( $this, 'add_cron_schedules' ) );
		add_action( 'rest_api_init', array( $this, 'init_rest_apis' ) );
		add_action( 'init', array( $this, 'register_legacy_woocommerce_post_types' ), 5 );

		register_activation_hook( WAWP_PLUGIN_FILE, array( $this, 'activate' ) );
		register_deactivation_hook( WAWP_PLUGIN_FILE, array( $this, 'deactivate' ) );

		// Cron actions.
		add_action( 'wawp_cron_refresh_system_info', array( $this, 'cron_refresh_system_info' ) );
		add_action( 'wawp_cron_hourly_self_repair', array( $this, 'cron_hourly_self_repair' ) );
		add_action( 'wawp_cron_process_abandoned_cart_notifications', array( $this, 'cron_process_abandoned_cart_notifications' ) );
		add_action( 'wawp_cron_daily_cleanup', array( $this, 'cron_daily_cleanup' ) );

		add_action( 'updated_option', array( $this, 'clear_dashboard_cache_on_option_update' ), 10, 1 );
		add_action( 'added_option', array( $this, 'clear_dashboard_cache_on_option_update' ), 10, 1 );
		add_filter( 'plugin_row_meta', array( $this, 'add_plan_label_to_plugin_list' ), 10, 2 );
	}

	/**
	 * Clear the dashboard data cache when a WAWP option is updated.
	 *
	 * @param string $option Option name.
	 */
	public function clear_dashboard_cache_on_option_update( $option ) {
		if ( 'wawp_dashboard_transient_keys' === $option ) {
			return;
		}
		if ( strpos( $option, 'wawp_' ) === 0 ) {
			$keys = get_option( 'wawp_dashboard_transient_keys', array() );
			if ( ! empty( $keys ) && is_array( $keys ) ) {
				foreach ( $keys as $key ) {
					delete_transient( $key );
					wp_cache_delete( $key, 'wawp_database' );
				}
				delete_option( 'wawp_dashboard_transient_keys' );
			}
			wp_cache_delete( 'wawp_dashboard_transients', 'wawp_dashboard' );
		}
	}

	/**
	 * Record last system cron hit.
	 *
	 * @return void
	 */
	public function record_system_cron() {
		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
			$script_name = isset( $_SERVER['SCRIPT_NAME'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SCRIPT_NAME'] ) ) : '';
			$is_external = ( PHP_SAPI === 'cli' ) || ( $script_name && strpos( $script_name, 'wp-cron.php' ) !== false );
			if ( $is_external ) {
				update_option( WAWP_Settings_Registry::LAST_SYSTEM_CRON_HIT, time() );
			}
		}
	}

	/**
	 * Handle email tracking pixel requests.
	 *
	 * @return void
	 */
	public function handle_email_tracking() {
		$get_email_open = filter_input( INPUT_GET, 'wawp_email_open', FILTER_SANITIZE_NUMBER_INT );
		if ( empty( $get_email_open ) ) {
			return;
		}

		$log_id = absint( $get_email_open );
		if ( ! $log_id ) {
			status_header( 400 );
			exit;
		}

		global $wpdb;
		$table     = $this->db->get_unified_table_name();
		$cache_key = 'wawp_log_row_' . $log_id;
		$row       = wp_cache_get( $cache_key, 'wawp_database' );

		if ( false === $row ) {
			$results = $this->db->get_results_cached( $wpdb->prepare( 'SELECT details FROM %i WHERE id = %d', $table, $log_id ), $cache_key, 'wawp_database', 300 );
			$row     = ! empty( $results ) ? (object) $results[0] : null;
		}

		if ( $row ) {
			$details               = json_decode( $row->details, true );
			$details               = is_array( $details ) ? $details : array();
			$details['open_count'] = (int) ( $details['open_count'] ?? 0 ) + 1;
			if ( empty( $details['first_opened_at'] ) ) {
				$details['first_opened_at'] = gmdate( 'Y-m-d H:i:s' );
			}
			$this->db->update_row( 'unified_activity_logs', array( 'details' => wp_json_encode( $details ) ), array( 'id' => $log_id ) );
			wp_cache_delete( $cache_key, 'wawp_database' );
		}

		// Output 1x1 transparent GIF.
		header( 'Content-Type: image/gif' );
		header( 'Cache-Control: no-cache, no-store, must-revalidate' );
		header( 'Pragma: no-cache' );
		$pixel         = hex2bin( '47494638396101000100800000000000ffffff21f90401000000002c00000000010001000002024401003b' );
		$output_stream = call_user_func( 'fopen', 'php://output', 'w' );
		if ( $output_stream ) {
			call_user_func( 'fwrite', $output_stream, $pixel );
			call_user_func( 'fclose', $output_stream );
		}
		exit;
	}

	/**
	 * Handle fallback for missing dynamic JS chunks during/after deployment.
	 *
	 * Returns a reload command to old client browser sessions.
	 */
	public function handle_missing_js_chunk_fallback() {
		$req_uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		if ( false !== strpos( $req_uri, 'wp-content/plugins/automation-web-platform/app/dist/assets/' ) ) {
			$clean_path = strtok( $req_uri, '?#' );
			if ( '.js' === substr( $clean_path, -3 ) ) {
				header( 'Content-Type: application/javascript; charset=UTF-8' );
				header( 'Cache-Control: no-cache, no-store, must-revalidate' );
				status_header( 200 );
				echo "console.warn('Wawp: Missing dynamic chunk detected, forcing reload...'); window.location.reload(true);";
				exit;
			}
		}
	}

	/**
	 * Initialize plugin components on plugins_loaded.
	 *
	 * @return void
	 */
	public function init_plugin() {
		// Force loading local plugin translations first to ensure updates take effect immediately.
		add_filter(
			'load_textdomain_mofile',
			function ( $mofile, $domain ) {
				if ( 'automation-web-platform' === $domain ) {
					$filename   = basename( $mofile );
					$local_file = WAWP_PLUGIN_DIR . 'languages/' . $filename;
					if ( file_exists( $local_file ) ) {
						return $local_file;
					}

					// Fallback locale filter: if a region-specific translation like fr_FR.mo is missing, try loading the language-only fr.mo file if it exists.
					$parts = explode( '_', $filename );
					if ( count( $parts ) > 1 ) {
						$fallback_file = WAWP_PLUGIN_DIR . 'languages/' . $parts[0] . '.mo';
						if ( file_exists( $fallback_file ) ) {
							return $fallback_file;
						}
					}
				}
				return $mofile;
			},
			10,
			2
		);
		load_plugin_textdomain( 'automation-web-platform', false, dirname( plugin_basename( WAWP_PLUGIN_FILE ) ) . '/languages' );

		$senders_opts = $this->get_wawp_setting(
			WAWP_Settings_Registry::SENDERS_ENABLED,
			array(
				'email'       => 1,
				'wa'          => 1,
				'meta'        => 0,
				'block'       => 1,
				'system_info' => 1,
			)
		);

		$this->enabled_features = array(
			'wa'              => ! empty( $senders_opts['wa'] ),
			'meta'            => ! empty( $senders_opts['meta'] ),
			'email'           => ! empty( $senders_opts['email'] ),
			'chat_widget'     => $this->get_wawp_setting( WAWP_Settings_Registry::CHAT_WIDGET_ENABLED, 1 ),
			'otp_login'       => $this->get_wawp_setting( WAWP_Settings_Registry::PASSWORDLESS_LOGIN_ENABLED, 1 ),
			'signup'          => $this->get_wawp_setting( WAWP_Settings_Registry::SIGNUP_ENABLED, 1 ),
			'checkout_otp'    => $this->get_wawp_setting( WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED, 1 ),
			'custom_pages'    => $this->get_wawp_setting( WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED, 1 ),
			'countrycode'     => $this->get_wawp_setting( WAWP_Settings_Registry::COUNTRYCODE_ENABLED, 1 ),
			'campaigns'       => $this->get_wawp_setting( WAWP_Settings_Registry::CAMPAIGNS_ENABLED, 0 ),
			'abandoned_carts' => $this->get_wawp_setting( WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED, 1 ),
			'system_info'     => $this->get_wawp_setting( WAWP_Settings_Registry::SYSTEM_INFO_ENABLED, 1 ),
			'notifications'   => $this->get_wawp_setting( WAWP_Settings_Registry::NOTIFICATIONS_ENABLED, 1 ),
			'email_templates' => $this->get_wawp_setting( WAWP_Settings_Registry::EMAIL_TEMPLATES_ENABLED, 1 ),
		);

		$enabled_features = $this->enabled_features;

		// Initialize Core Managers First.
		$this->db = new WAWP_Database_Manager();
		if ( class_exists( 'WAWP_Connector' ) ) {
			$this->connector = new WAWP_Connector();
		}
		$this->instance_manager     = new WAWP_Instance_Manager();
		$this->notification_manager = new WAWP_Notification_Manager();
		$this->user_manager         = new WAWP_User_Manager();

		// Core managers and components.
		$this->load_core_files( $enabled_features );

		$this->senders = new WAWP_Senders();
		$this->senders->init();
		$this->instances = $this->senders; // Alias for backward compatibility.

		$this->others = new WAWP_Others();
		new WAWP_Assets_Optimizer();
		$this->admin_users = new WAWP_Admin_Users();
		new WAWP_Shortcode_Manager();

		// Component initialization.
		$this->unified_log = class_exists( 'WAWP_Unified_Log' ) ? new WAWP_Unified_Log() : null;

		if ( $enabled_features['notifications'] && class_exists( 'WAWP_Flow_Builder' ) ) {
			$this->flow_builder = WAWP_Flow_Builder::get_instance();
		}

		$this->block_manager = class_exists( 'WAWP_Block_Manager' ) ? new WAWP_Block_Manager( $this ) : null;

		if ( $enabled_features['countrycode'] && class_exists( 'WAWP_CountryCode' ) ) {
			$countrycode = new WAWP_CountryCode();
			$countrycode->init();
		}

		$this->messenger   = WAWP_Messaging_Service::get_instance();
		$this->system_info = class_exists( 'WAWP_System_Info' ) ? new WAWP_System_Info() : null;

		if ( class_exists( 'WAWP_Stats_Manager' ) ) {
			$this->stats_manager = new WAWP_Stats_Manager();
		}

		$this->chat_widget = ( $enabled_features['chat_widget'] && class_exists( 'WAWP_Chat_Widget' ) ) ? new WAWP_Chat_Widget() : null;

		if ( ( $enabled_features['campaigns'] || is_admin() ) && class_exists( 'WAWP_Campaigns_Advanced' ) ) {
			$this->campaigns = new WAWP_Campaigns_Advanced();
		}

		if ( ( $enabled_features['abandoned_carts'] || is_admin() ) && class_exists( 'WAWP_Abandoned_Carts' ) ) {
			$this->abandoned_carts           = new WAWP_Abandoned_Carts();
			$GLOBALS['wawp_abandoned_carts'] = $this->abandoned_carts;
		}

		$menu = new WAWP_Menu();
		$menu->init();

		new WAWP_Privacy();

		if ( $enabled_features['email_templates'] && class_exists( 'WAWP_Email_Templates' ) ) {
			$this->email_templates = WAWP_Email_Templates::get_instance();
		}

		$this->custom_pages = class_exists( 'WAWP_Custom_Login_Pages' ) ? new WAWP_Custom_Login_Pages() : null;
		$this->otp          = ( $enabled_features['otp_login'] && class_exists( 'WAWP_Otp_Login' ) ) ? new WAWP_Otp_Login( $this->db, $this->senders ) : null;

		if ( $this->otp ) {
			$this->otp->init();
		}

		if ( class_exists( 'WAWP_OTP_Service' ) ) {
			WAWP_OTP_Service::get_instance();
		}

		if ( $enabled_features['signup'] && class_exists( 'WAWP_Signup' ) ) {
			WAWP_Signup::get_instance();
		}

		if ( $enabled_features['checkout_otp'] && class_exists( 'WAWP_Checkout_Otp' ) && class_exists( 'WooCommerce' ) ) {
			WAWP_Checkout_Otp::get_instance();
		}

		if ( $enabled_features['notifications'] && class_exists( 'WooCommerce' ) ) {
			require_once WAWP_PLUGIN_DIR . 'includes/helpers/class-wawp-order-actions.php';
		}
		$get_page          = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS );
		$get_section       = filter_input( INPUT_GET, 'wawp_section', FILTER_SANITIZE_SPECIAL_CHARS );
		$is_recaptcha_page = is_admin() && WAWP_MAIN_MENU_SLUG === $get_page && 'recaptcha' === $get_section;

		$ajax_action       = filter_input( INPUT_POST, 'action', FILTER_SANITIZE_SPECIAL_CHARS );
		$is_recaptcha_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX && strpos( $ajax_action, 'recaptcha' ) !== false;

		if ( ( $this->get_wawp_setting( WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED, 0 ) || $is_recaptcha_page || $is_recaptcha_ajax ) && class_exists( 'WAWP_Google_Recaptcha' ) ) {
			WAWP_Google_Recaptcha::get_instance();
		}

		if ( class_exists( 'WAWP_Orders_Status_Settings' ) ) {
			WAWP_Orders_Status_Settings::get_instance();
		}
	}

	/**
	 * Load core class files based on enabled features.
	 *
	 * @param array $features Enabled features.
	 */
	private function load_core_files( $features ) {
		if ( $features['abandoned_carts'] ) {
			if ( file_exists( WAWP_PLUGIN_DIR . 'includes/abandoned-cart/class-wawp-abandoned-carts.php' ) ) {
				require_once WAWP_PLUGIN_DIR . 'includes/abandoned-cart/class-wawp-abandoned-carts.php';
			}
		}

		if ( $features['custom_pages'] ) {
			require_once WAWP_PLUGIN_DIR . 'includes/helpers/class-wawp-custom-pages-settings.php';
			if ( class_exists( 'WooCommerce' ) && get_option( 'wawp_replace_wc_forms' ) ) {
				require_once WAWP_PLUGIN_DIR . 'integrations/woocommerce-myaccount.php';
			}
		}

		require_once WAWP_PLUGIN_DIR . 'includes/general/class-wawp-stats-manager.php';
		require_once WAWP_PLUGIN_DIR . 'includes/helpers/class-wawp-privacy.php';
	}

	/**
	 * Plugin Activation logic.
	 *
	 * @return void
	 */
	public function activate() {
		require_once WAWP_PLUGIN_DIR . 'includes/autoload.php';

		if ( empty( $this->db ) ) {
			$this->db = new WAWP_Database_Manager();
		}

		if ( empty( $this->connector ) && class_exists( 'WAWP_Connector' ) ) {
			$this->connector = new WAWP_Connector();
		}

		$this->db->create_all_tables();
		$this->db->ensure_all_columns();
		if ( $this->connector ) {
			$this->connector->on_activate();
		}

		if ( class_exists( 'WAWP_Shortcode_Manager' ) ) {
			WAWP_Shortcode_Manager::on_activate();
		}

		// Handle block list migration.
		$old_list = (array) $this->get_wawp_setting( WAWP_Settings_Registry::BLOCK_LIST, array() );
		if ( $old_list && $this->block_manager ) {
			$this->block_manager->upsert_blocked_numbers( $old_list );
			delete_option( 'wawp_block_list' );
		}

		// Capability.
		$role = get_role( 'administrator' );
		if ( $role ) {
			$role->add_cap( WAWP_CAPABILITY );
		}

		require_once WAWP_PLUGIN_DIR . 'includes/general/class-wawp-stats-manager.php';

		// Initial System Checks.
		require_once WAWP_PLUGIN_DIR . 'includes/general/class-wawp-system-info.php';
		if ( class_exists( 'WAWP_System_Info' ) ) {
			$sys = new WAWP_System_Info();
			$sys->run_checks_and_set_transient();
		}

		$this->ensure_default_options();
		set_transient( '_wawp_activation_redirect', true, 30 );

		add_action( 'init', array( $this, 'schedule_initial_tasks' ), 20 );
	}

	/**
	 * Ensure default options are set on activation.
	 */
	private function ensure_default_options() {
		$defaults = array(
			WAWP_Settings_Registry::CAMPAIGNS_ENABLED  => 0,
			WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED => 0,
			WAWP_Settings_Registry::MULTILANG_ENABLED  => 0,
			WAWP_Settings_Registry::SUB_NOTIFS_ENABLED => 0,
			WAWP_Settings_Registry::OTP_ENABLED        => 1,
		);

		foreach ( $defaults as $key => $val ) {
			if ( false === $this->get_wawp_setting( $key ) ) {
				add_option( $key, $val );
			}
		}

		if ( false === $this->get_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS ) ) {
			add_option(
				WAWP_Settings_Registry::OTP_SETTINGS,
				array(
					'instance'                 => 0,
					'otp_message_whatsapp'     => esc_html__( 'Your OTP code is: {{otp}}', 'automation-web-platform' ),
					'otp_message_email'        => esc_html__( 'Please click the link below to verify your identity: {{magic_link}}', 'automation-web-platform' ),
					'login_method'             => 'whatsapp_otp',
					'enable_whatsapp'          => 1,
					'enable_email'             => 1,
					'enable_email_password'    => 1,
					'redirect_rules'           => array(),
					'title'                    => esc_html__( 'Welcome back', 'automation-web-platform' ),
					'description'              => esc_html__( 'Choose a sign-in method to continue', 'automation-web-platform' ),
					'request_otp_button_color' => '#22c55e',
					'verify_otp_button_color'  => '#22c55e',
					'resend_otp_button_color'  => '#22c55e',
					'login_button_color'       => '#22c55e',
				)
			);
		}

		$wcc_opts                        = $this->get_wawp_setting( WAWP_Settings_Registry::INTL_TEL_OPTIONS, array() );
		$wcc_opts['enable_ip_detection'] = 1;

		if ( empty( $wcc_opts['default_country_code'] ) ) {
			$wcc_opts['default_country_code'] = 'eg';
		}

		if ( empty( $wcc_opts['enabled_countries'] ) ) {
			require_once WAWP_PLUGIN_DIR . 'includes/helpers/class-wawp-country-code-list.php';
			if ( function_exists( 'WAWP\\wawp_get_all_countries' ) ) {
				$all_countries                 = \WAWP\wawp_get_all_countries();
				$wcc_opts['enabled_countries'] = array_column( $all_countries, 'iso2' );
			}
		}

		if ( empty( $wcc_opts['phone_fields'] ) ) {
			$wcc_opts['phone_fields'] = array(
				array(
					'id'      => '#billing-phone',
					'name'    => 'Woocommerce Gutenberg React',
					'enabled' => '1',
				),
				array(
					'id'      => '#billing_phone',
					'name'    => 'Normal Woocommerce Checkout',
					'enabled' => '1',
				),
				array(
					'id'      => '#wawp_phone',
					'name'    => 'Wawp Login & Signup Forms',
					'enabled' => '1',
				),
				array(
					'id'      => '#billing_phone_popup',
					'name'    => 'Abandoned Cart Popup',
					'enabled' => '1',
				),
			);
		}
		$this->update_wawp_setting( WAWP_Settings_Registry::INTL_TEL_OPTIONS, $wcc_opts );
	}

	/**
	 * Schedule initial tasks via Task Scheduler.
	 */
	public function schedule_initial_tasks() {
		if ( ! class_exists( 'WAWP_Task_Scheduler' ) ) {
			return;
		}

		WAWP_Task_Scheduler::schedule_recurring( time(), 300, 'wp_campaigns_cron_send_advanced' );
		WAWP_Task_Scheduler::schedule_recurring( time(), 43200, 'wawp_cron_refresh_system_info' );
		WAWP_Task_Scheduler::schedule_recurring( time(), 3600, 'wawp_cron_hourly_self_repair' );
		WAWP_Task_Scheduler::schedule_recurring( time(), 300, 'wawp_cron_process_abandoned_cart_notifications' );
		WAWP_Task_Scheduler::schedule_recurring( time(), 86400, 'wawp_cron_daily_cleanup' );
	}

	/**
	 * Plugin Deactivation logic.
	 */
	public function deactivate() {
		require_once WAWP_PLUGIN_DIR . 'includes/general/class-wawp-task-scheduler.php';

		if ( $this->connector ) {
			$this->connector->on_deactivate();
		}

		$tasks = array(
			'wawp_notif_send_scheduled_notification_action',
			'wawp_cron_refresh_system_info',
			'wawp_cron_process_abandoned_cart_notifications',
			'wawp_cron_hourly_self_repair',
			'wawp_cron_clear_expired_otps',
			'wp_campaigns_cron_send_advanced',
			'wawp_mrsb_auto_sync_event',
		);

		foreach ( $tasks as $task ) {
			WAWP_Task_Scheduler::unschedule_all( $task );
		}
	}

	/**
	 * Add custom cron schedules.
	 *
	 * @param array $schedules Existing schedules.
	 * @return array Modified schedules.
	 */
	public function add_cron_schedules( $schedules ) {
		$schedules['five_minutes'] = array(
			'interval' => 300,
			'display'  => 'Every 5 Minutes',
		);
		$schedules['six_hours']    = array(
			'interval' => 6 * HOUR_IN_SECONDS,
			'display'  => 'Every 6 Hours',
		);
		$schedules['hourly']       = array(
			'interval' => HOUR_IN_SECONDS,
			'display'  => 'Every 1 Hour',
		);
		$schedules['twelve_hours'] = array(
			'interval' => 12 * HOUR_IN_SECONDS,
			'display'  => 'Every 12 Hours',
		);

		return $schedules;
	}

	/**
	 * Ensure the admin has the manage_wawp capability.
	 */
	public function ensure_capabilities() {
		if ( current_user_can( 'manage_options' ) && ! current_user_can( WAWP_CAPABILITY ) ) {
			$role = get_role( 'administrator' );
			if ( $role ) {
				$role->add_cap( WAWP_CAPABILITY );
			}
		}
	}

	/**
	 * Handle redirect after activation.
	 */
	public function handle_activation_redirect() {
		if ( ! get_transient( '_wawp_activation_redirect' ) ) {
			return;
		}
		delete_transient( '_wawp_activation_redirect' );

		if ( isset( $_GET['page'] ) && 'automation-web-platform' === $_GET['page'] && isset( $_GET['action'] ) ) {
			$action = sanitize_text_field( wp_unslash( $_GET['action'] ) );
			$id     = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;

			if ( 'delete_instance' === $action && $id ) {
				check_admin_referer( 'wawp_delete_instance_' . $id );
				$this->instance_manager->delete_instance( $id );
				wp_safe_redirect( admin_url( 'admin.php?page=automation-web-platform&wawp_notice=instance_deleted' ) );
				exit;
			}
		}

		if ( is_network_admin() || isset( $_GET['activate-multi'] ) ) {
			return;
		}

		if ( ! WAWP_Connector()->has_auth() ) {
			return;
		}

		wp_safe_redirect( admin_url( 'admin.php?page=wawp&wawp_section=account&wawp_popup_step=1' ) );
		exit;
	}

	/**
	 * Check for version update and run DB migrations.
	 */
	public function check_version_update() {
		if ( ! is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
			return;
		}

		$current_version   = WAWP_PLUGIN_VERSION;
		$installed_version = $this->get_wawp_setting( WAWP_Settings_Registry::PLUGIN_INSTALLED_VERSION, '0.0.0' );

		if ( version_compare( $installed_version, $current_version, '<' ) || ! get_transient( 'wawp_last_db_check' ) ) {
			require_once WAWP_PLUGIN_DIR . 'includes/class-wawp-database-manager.php';
			if ( $this->db ) {
				$this->db->create_all_tables();
				$this->db->ensure_all_columns();
			}
			update_option( WAWP_Settings_Registry::PLUGIN_INSTALLED_VERSION, $current_version );
			set_transient( 'wawp_last_db_check', 1, WEEK_IN_SECONDS );
		}
	}

	/**
	 * Get user data with memoization.
	 *
	 * @param bool $force_refresh Whether to force a refresh.
	 * @return array User data.
	 */
	public function get_user_data( $force_refresh = false ) {
		if ( $force_refresh ) {
			$this->user_data_cache = null;
			if ( function_exists( 'wp_cache_delete' ) ) {
				wp_cache_delete( 'wawp_site_b_user_data', 'transient' );
				wp_cache_delete( 'wawp_site_b_user_data_persistent', 'options' );
			}
		}

		if ( null !== $this->user_data_cache && ! $force_refresh ) {
			return $this->user_data_cache;
		}

		$data = get_transient( 'wawp_site_b_user_data' );
		if ( false === $data ) {
			$data = $this->get_wawp_setting( WAWP_Settings_Registry::USER_DATA_PERSISTENT );
		}

		$this->user_data_cache = is_array( $data ) ? $data : array();

		return $this->user_data_cache;
	}

	/**
	 * Refresh system information.
	 *
	 * @return void
	 */
	public function cron_refresh_system_info() {
		if ( $this->system_info ) {
			$this->system_info->run_checks_and_set_transient();
		}
	}

	/**
	 * Perform hourly self-repair.
	 *
	 * @return void
	 */
	public function cron_hourly_self_repair() {
		if ( $this->system_info ) {
			$this->system_info->run_all_repairs();
		}
	}

	/**
	 * Process abandoned cart notifications.
	 *
	 * @return void
	 */
	public function cron_process_abandoned_cart_notifications() {
		global $wpdb;
		$log_table = $wpdb->prefix . 'wawp_abandoned_cart_notifications_log';
		$cache_key = 'wawp_due_abandoned_notifs';
		$due_rows  = wp_cache_get( $cache_key, 'wawp_notifications' );

		if ( false === $due_rows ) {
			$due_rows = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT DISTINCT cart_id, notification_type, notification_index FROM %i WHERE status = %s AND scheduled_at <= %s ORDER BY scheduled_at ASC LIMIT 50', $log_table, 'scheduled', gmdate( 'Y-m-d H:i:s' ) ), $cache_key, 'wawp_notifications', 30 );
			// Convert arrays to objects for backward compatibility if the original used get_results without ARRAY_A.
			if ( is_array( $due_rows ) && ! empty( $due_rows ) && is_array( $due_rows[0] ) ) {
				$due_rows = array_map(
					function ( $item ) {
						return (object) $item;
					},
					$due_rows
				);
			}
		}

		if ( empty( $due_rows ) ) {
			return;
		}

		if ( ! class_exists( 'WAWP_Abandoned_Cart_Notifications' ) ) {
			$file = WAWP_PLUGIN_DIR . 'includes/abandoned-cart/class-wawp-abandoned-cart-notifications.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'WAWP_Abandoned_Cart_Notifications' ) && ! has_action( 'wawp_send_abandoned_cart_notification_step' ) ) {
			WAWP_Abandoned_Cart_Notifications::get_instance();
		}

		foreach ( $due_rows as $row ) {
			do_action( 'wawp_send_abandoned_cart_notification_step', (int) $row->cart_id, $row->notification_type, (int) $row->notification_index );
			WAWP_Task_Scheduler::unschedule_all( 'wawp_send_abandoned_cart_notification_step', array( (int) $row->cart_id, $row->notification_type, (int) $row->notification_index ) );
		}
	}

	/**
	 * Register Bricks elements.
	 *
	 * @return void
	 */
	public function register_bricks_elements() {
		if ( ! class_exists( '\Bricks\Elements' ) ) {
			return;
		}

		$dir = WAWP_PLUGIN_DIR . 'integrations/bricks/';
		\Bricks\Elements::register_element( $dir . 'class-wawp-bricks-login-element.php', 'my-wawp-login', 'WAWP_Bricks_Login_Element' );
		\Bricks\Elements::register_element( $dir . 'class-wawp-bricks-signup-element.php', 'my-wawp-signup', 'WAWP_Bricks_Signup_Element' );
		\Bricks\Elements::register_element( $dir . 'class-wawp-bricks-fast-login-element.php', 'my-wawp-fast-login', 'WAWP_Bricks_Fast_Login_Element' );
	}

	/**
	 * Daily Database Cleanup.
	 *
	 * @return void
	 */
	public function cron_daily_cleanup() {
		if ( $this->db ) {
			$this->db->cleanup_old_logs( 30 );
		}
	}

	/**
	 * Initialize REST API classes on rest_api_init hook.
	 *
	 * @return void
	 */
	public function init_rest_apis() {
		if ( class_exists( 'WAWP_Global_Search' ) ) {
			WAWP_Global_Search::get_instance()->register_routes();
		}

		if ( class_exists( 'WAWP_Rest_Settings_API' ) ) {
			WAWP_Rest_Settings_API::get_instance();
		}

		if ( class_exists( 'WAWP_Rest_AI_API' ) ) {
			WAWP_Rest_AI_API::get_instance();
		}

		if ( class_exists( 'WAWP_Rest_Cart_API' ) ) {
			new WAWP_Rest_Cart_API();
		}
	}

	/**
	 * Add a plan status label next to the plugin version in the plugins list.
	 *
	 * @param array  $plugin_meta Plugin meta links.
	 * @param string $plugin_file Plugin file path.
	 * @return array
	 */
	public function add_plan_label_to_plugin_list( $plugin_meta, $plugin_file ) {
		if ( strpos( $plugin_file, 'class-wawp.php' ) !== false || strpos( $plugin_file, 'automation-web-platform' ) !== false ) {
			if ( ! function_exists( 'wawp_get_user_data' ) ) {
				include_once WAWP_PLUGIN_DIR . 'includes/helpers/wawp-helper-functions.php';
			}

			$user_data = wawp_get_user_data();
			$plan_name = ! empty( $user_data['plan_name'] ) ? $user_data['plan_name'] : __( 'Guest Free', 'automation-web-platform' );

			// Basic style for free/guest users.
			$badge_style = 'background: #f1f5f9; color: #475569; padding: 1px 10px; border-radius: 20px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; display: inline-block; border: 1px solid #cbd5e1; vertical-align: middle; line-height: 1.6;';

			if ( ! empty( $user_data['is_lifetime'] ) ) {
				// Premium Lifetime style.
				$badge_style = 'background: #fffbeb; color: #92400e; padding: 1px 10px; border-radius: 20px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; display: inline-block; border: 1px solid #f59e0b; vertical-align: middle; line-height: 1.6;';
			} elseif ( ! empty( $user_data['plan_name'] ) && 'Guest Mode' !== $user_data['plan_name'] && 'Guest Free' !== $user_data['plan_name'] ) {
				// Pro/Subscription style.
				$badge_style = 'background: #f0fdf4; color: #166534; padding: 1px 10px; border-radius: 20px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; display: inline-block; border: 1px solid #22c55e; vertical-align: middle; line-height: 1.6;';
			}

			$plugin_meta[] = sprintf( '<span style="%s">%s</span>', esc_attr( $badge_style ), esc_html( $plan_name ) );
		}
		return $plugin_meta;
	}

	/**
	 * Register legacy WooCommerce post types if WooCommerce is inactive.
	 * This prevents "Doing it Wrong" notices in the dashboard activity widget.
	 */
	public function register_legacy_woocommerce_post_types() {
		if ( ! is_admin() || class_exists( 'WooCommerce' ) ) {
			return;
		}

		$post_types = array( 'shop_order', 'product', 'shop_coupon' );
		foreach ( $post_types as $pt ) {
			if ( ! post_type_exists( $pt ) ) {
				register_post_type(
					$pt,
					array(
						'public'             => false,
						'show_ui'            => false,
						'show_in_menu'       => false,
						'show_in_nav_menus'  => false,
						'show_in_admin_bar'  => false,
						'publicly_queryable' => false,
						'query_var'          => false,
						'rewrite'            => false,
						'capability_type'    => 'post',
						'hierarchical'       => false,
						'supports'           => array(),
					)
				);
			}
		}
	}
}

require_once WAWP_PLUGIN_DIR . 'includes/helpers/wawp-helper-functions.php';

// Global initialization.
wawp();
