<?php
/*
Plugin Name: AutoPoly - AI Translation For Polylang (Pro)
Plugin URI: https://coolplugins.net/?utm_source=atfp_plugin&utm_medium=inside&utm_campaign=product_site&utm_content=plugin_list
Version: 1.3.0
Author: Cool Plugins
Author URI: https://coolplugins.net/?utm_source=atfp_plugin&utm_medium=inside&utm_campaign=author_page&utm_content=plugin_list
Description: AutoPoly - AI Translation for Polylang simplifies your translation process by automatically translating all pages/posts content from one language to another.
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: autopoly-ai-translation-for-polylang-pro
*/

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! defined( 'ATFPP_V' ) ) {
	define( 'ATFPP_V', '1.3.0' );
}
if ( ! defined( 'ATFPP_DIR_PATH' ) ) {
	define( 'ATFPP_DIR_PATH', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'ATFPP_URL' ) ) {
	define( 'ATFPP_URL', plugin_dir_url( __FILE__ ) );
}

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

if ( ! defined( 'ATFPP_FEEDBACK_API' ) ) {
	define( 'ATFPP_FEEDBACK_API', "https://feedback.coolplugins.net/" );
}

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

require_once __DIR__ . '/vendor/autoload.php';

use ATFPP\AI_Translate\Plugin_Main;

if ( ! class_exists( 'AutoPolyPro' ) ) {
	final class AutoPolyPro {

		/**
		 * Plugin instance.
		 *
		 * @var AutoPolyPro
		 * @access private
		 */
		private static $instance = null;

		/**
		 * Get plugin instance.
		 *
		 * @return AutoPolyPro		
		 * @static
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}
		/**
		 * Constructor
		 */
		private function __construct() {
			$this->atfpp_ai_main_file_load();
			$this->atfpp_load_files();
			add_action( 'plugins_loaded', array( $this, 'atfpp_init' ) );
			register_activation_hook( ATFPP_FILE, array( $this, 'atfpp_activate' ) );
			register_deactivation_hook( ATFPP_FILE, array( $this, 'atfpp_deactivate' ) );
			add_action('init', array($this, 'load_plugin_textdomain'));
			add_action('init', array($this, 'onInit'));
			add_action( 'media_buttons', array( $this, 'atfpp_classic_editor_button' ) );
			add_action( 'activated_plugin', array( $this, 'atfpp_plugin_redirection' ) );
			add_action('current_screen', array($this, 'atfpp_append_view_languages_link'));
			add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'atfpp_plugin_action_links' ) );
			add_action('atfpp_display_admin_notices', array($this, 'atfpp_display_admin_notices'));
			add_action( 'after_plugin_row_' . ATFPP_PLUGIN_BASE, array( $this, 'atfpp_plugin_custom_notice' ), 10, 2);
			add_filter( 'site_transient_update_plugins', array( $this, 'atfpp_hide_plugin_update_notice' ) );

			// Initialize cron
			$this->init_cron();

			// Initialize feedback notice.
			$this->init_feedback_notice();

			$page=isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
			if($page == 'polylang-atfpp-dashboard'){
				add_action('admin_print_scripts', array($this, 'atfpp_hide_unrelated_notices'));
			}

			if(!class_exists('Atfpp_Dashboard')) {
				require_once ATFPP_DIR_PATH . 'admin/cpt_dashboard/cpt_dashboard.php';
				new Atfpp_Dashboard();
			}
			if(!class_exists('Atfpp_Glossary')) {
				require_once ATFPP_DIR_PATH . 'admin/atfpp-glossary/atfpp-glossary.php';
				new Atfpp_Glossary();
			}
		}

		/**
		 * Initialize the cron job for the plugin.
		 */
		public function init_cron(){
			// if (is_admin()) {
			require_once ATFPP_DIR_PATH . '/admin/cpfm-feedback/cron/atfpp-cron.php';
			$cron = new ATFPP_cronjob();
			$cron->atfpp_cron_init_hooks();
			// }
			}

		/**
		 * Initialize the feedback notice for the plugin.
		 */

		public function init_feedback_notice() {

			if (is_admin()) {

				if(!class_exists('CPFM_Feedback_Notice')){
					require_once ATFPP_DIR_PATH . '/admin/cpfm-feedback/cpfm-common-notice.php';

				}

			add_action('cpfm_register_notice', function () {
				if (!class_exists('CPFM_Feedback_Notice') || !current_user_can('manage_options')) {
					return;
				}
				
				$notice = [
					'title' => __('AutoPoly - AI Translation For Polylang (Pro)', 'ATFPP'),
					'message' => __('Help us make this plugin more compatible with your site by sharing non-sensitive site data.', 'ATFPP'),
					'pages' => ['polylang-atfpp-dashboard'],
					'always_show_on' => ['polylang-atfpp-dashboard'], // This enables auto-show
					'plugin_name'=>'atfpp'
				];
				CPFM_Feedback_Notice::cpfm_register_notice('cool_translations', $notice);
					if (!isset($GLOBALS['cool_plugins_feedback'])) {
						$GLOBALS['cool_plugins_feedback'] = [];
					}
					$GLOBALS['cool_plugins_feedback']['cool_translations'][] = $notice;
			});

			add_action('cpfm_after_opt_in_atfpp', function($category) {
				if ($category === 'cool_translations') {
					ATFPP_cronjob::atfpp_send_data();
					$options = get_option('atfp_feedback_opt_in');
					$options = 'yes';
					update_option('atfp_feedback_opt_in', $options);	
				}
				});
			}
		}

		public function atfpp_plugin_action_links($links) {
			$links[] = '<a href="admin.php?page=polylang-atfpp-dashboard&tab=settings">Settings</a>';
			return $links;
		}

		public function atfpp_plugin_redirection($plugin) {
			if ( ! is_plugin_active( 'polylang/polylang.php' ) && ! is_plugin_active( 'polylang-pro/polylang.php' ) ) {
				return false;
			}

			if ( $plugin == plugin_basename( __FILE__ ) ) {
				exit( wp_safe_redirect( admin_url( 'admin.php?page=polylang-atfpp-dashboard&tab=dashboard' ) ) );
			}	
		}

		public function atfpp_append_view_languages_link($current_screen) {
			if(is_admin()) {
				if(class_exists('ATFPP_Helper') && ATFPP_Helper::bulk_translation_render($current_screen)){
					add_filter( "views_{$current_screen->id}", array($this, 'atfpp_list_table_views_filter') );
				}
			}
		}
		
		public function atfpp_list_table_views_filter($views) {
			if(!function_exists('PLL') || !function_exists('pll_count_posts') || !function_exists('get_current_screen') || !property_exists(PLL(), 'model') || !function_exists('pll_current_language')){
				return $views;
			}
			
			$pll_languages =  PLL()->model->get_languages_list();
			$current_screen=get_current_screen();
			$index=0;
			$total_languages=count($pll_languages);
			$pll_active_languages=function_exists('pll_current_language') ? pll_current_language() : '';
			$pll_active_languages = !$pll_active_languages || empty($pll_active_languages) ? 'all' : $pll_active_languages;
			$pll_active_languages=pll_current_language();
			$taxonomy=isset($current_screen->taxonomy) ? $current_screen->taxonomy : '';

			if($taxonomy && !empty($taxonomy)){
				return $views;
			}
			
			$post_type=isset($current_screen->post_type) ? $current_screen->post_type : '';
			$post_status=(isset($_GET['post_status']) && 'trash' === sanitize_text_field(wp_unslash($_GET['post_status']))) ? 'trash' : 'publish';
			$all_translated_post_count=0;
			$list_html='';
			if(count($pll_languages) > 1){
				echo wp_kses("<div class='atfp_subsubsub' style='display:none; clear:both;'>
					<ul class='subsubsub atfp_subsubsub_list'>", array(
						'div' => array('class' => true, 'style' => true),
						'ul' => array('class' => true)
					));
					
					foreach($pll_languages as $lang){
						
						$flag=isset($lang->flag) ? $lang->flag : '';
						$language_slug=isset($lang->slug) ? $lang->slug : '';
						$current_class=$pll_active_languages && $pll_active_languages == $language_slug ? 'current' : '';
						$translated_post_count=pll_count_posts($language_slug, array('post_type'=>$post_type, 'post_status'=>$post_status));
						$url=function_exists('add_query_arg') ? add_query_arg('lang', $language_slug) : 'edit.php?post_type='.esc_attr($post_type).'&lang='.esc_attr($language_slug);

						if('publish' === $post_status){
							$draft_post_count=pll_count_posts($language_slug, array('post_type'=>$post_type, 'post_status'=>'draft'));
							$translated_post_count+=$draft_post_count;

							$pending_post_count=pll_count_posts($language_slug, array('post_type'=>$post_type, 'post_status'=>'pending'));
							$translated_post_count+=$pending_post_count;
						}

						$all_translated_post_count+=$translated_post_count;
						$list_html.="<li class='atfp_pll_lang_".esc_attr($language_slug)."'><a href='".esc_url($url)."' class='".esc_attr($current_class)."'>".esc_html(wp_kses($lang->name, array()))." <span class='count'>(".esc_html($translated_post_count).")</span></a>".($index < $total_languages-1 ? ' |&nbsp;' : '')."</li>";
						$index++;
					}

					
					$all_url=function_exists('add_query_arg') ? add_query_arg('lang', 'all') : 'edit.php?post_type='.esc_attr($post_type).'&lang=all';
					
					echo "<li class='atfp_pll_lang_all'><a href='".esc_url($all_url)."' class=''>All Languages<span class='count'>(".esc_html($all_translated_post_count).")</span></a> |&nbsp;</li>";
					
					$allowed = [
						'ul'   => [ 'class' => true ],
						'ol'   => [ 'class' => true ],
						'li'   => [ 'class' => true ],
						'a'    => [ 'href' => true, 'title' => true, 'target' => true, 'rel' => true ],
						'span' => [ 'class' => true, 'aria-hidden' => true ],
						'strong' => [],
						'em'     => [],
					];
						
					echo wp_kses( (string) $list_html, $allowed );
				echo "</ul>
				</div>";
			}

			return $views;
		}

				/**
		 * Display custom update notices for the AI Translation For TranslatePress (Pro) plugin in the WordPress plugins list table.
		 *
		 * This function checks the plugin's license status and update availability, and then conditionally
		 * displays messages in the plugin list:
		 *
		 * - If an update is available but the license key is not entered, it shows a warning to activate the license.
		 * - If the license or support period has expired, it displays a renewal message with appropriate links.
		 * - If the license is valid, no custom notice is shown.
		 *
		 * Hooked into the 'after_plugin_row' action to insert notices below the plugin row.
		 *
		 * @param string $plugin_file The plugin file path relative to the plugins directory.
		 * @param array  $plugin_data An array of plugin header data.
		*/

		public function atfpp_plugin_custom_notice( $plugin_file, $plugin_data ) {
			
		if ( ! class_exists( 'AI_Automatic_Translations_For_Polylang_Base' ) ) {
			return;
		}
					
			// Get license info and update info for the plugin
		$license_info = AI_Automatic_Translations_For_Polylang_Base::GetRegisterInfo();
		$update_info = AI_Automatic_Translations_For_Polylang_Base::getInstance()->el_plugin_update_info();

		$version_available_message = AutoPolyPro::atfppGetVersionAvailableMessage();

		$plugin_basename = plugin_basename(ATFPP_FILE);

		if ( ! AIAutomaticTranslationsForPolylang::$form_status &&  $plugin_basename === ATFPP_PLUGIN_BASE ) {
				
				$renew_link = wp_kses_post(
					__( $version_available_message.' Please <a href="admin.php?page=polylang-atfpp-dashboard&tab=license">enter your license key</a> to enable automatic updates and premium support for AI Translation For TranslatePress (Pro)', 'atfpp' ),
					array(
						'a' => array(
							'href' => array()
						)
					)
				);

			} else {

				if ( empty( $update_info->download_link ) ) {
					
					$is_expired = (empty($update_info->is_downloadable) ) ? 'license' : 'support';
					
					$message = ' Your ' . $is_expired . ' has expired,';
					$renew_text = ( ! empty( $license_info->market ) && $license_info->market === 'E' ) 
						? 'Please renew your ' . $is_expired . ' to continue receiving automatic updates and priority support.'
						: 'Please <a href="https://my.coolplugins.net/account/subscriptions/" target="_blank" rel="noopener noreferrer">Renew now</a> to continue receiving automatic updates and priority support.';
					
					$renew_link = $version_available_message . $message . ' ' . $renew_text;
				}
			}

			if ( ! empty( $renew_link )) {
					?>
					<tr class="plugin-update-tr active atfpp-pro">
						<td colspan="4" class="plugin-update colspanchange">
							<div class="update-message notice inline notice-warning notice-alt"> 
								<p><?php echo wp_kses_post( $renew_link ); ?></p>
							</div>
						</td>
					</tr>
					<?php
			}
		}

				/**
		 * Hide WordPress core plugin update notice when license is not valid
		 * 
		 * @param object $transient The site transient for plugin updates
		 * @return object Modified transient
		 */
		public function atfpp_hide_plugin_update_notice( $transient ) {
			if ( ! class_exists( 'AI_Automatic_Translations_For_Polylang_Base' ) ) {
				return $transient;
			}

			$update_info = AI_Automatic_Translations_For_Polylang_Base::getInstance()->el_plugin_update_info();
			$license_info = AI_Automatic_Translations_For_Polylang_Base::GetRegisterInfo();

			if ( empty($update_info->download_link) || $license_info == null){
					if ( isset( $transient->response ) && isset( $transient->response[ATFPP_PLUGIN_BASE] ) ) {
						unset( $transient->response[ATFPP_PLUGIN_BASE] );
					}
				}
			
			return $transient;
		}

			/**
			 * Get version available message if update is available
			 * 
			 * @return string Version available message or empty string
			 */
			public static function atfppGetVersionAvailableMessage() {
				
				// Get license info and update info for the plugin
				$update_info = AI_Automatic_Translations_For_Polylang_Base::getInstance()->el_plugin_update_info();

				// Initialize and sanitize version information
				$latest_version = isset($update_info->new_version) ? sanitize_text_field($update_info->new_version) : '';
				$version_available_message = '';

				// Prepare update available message if current version is outdated
				$plugin_basename = plugin_basename(ATFPP_FILE);
				if ( ! empty($latest_version) && version_compare(ATFPP_V, $latest_version, '<') ) {

					list($plugin_slug, $plugin_file) = explode('/', $plugin_basename);

					$plugin_info_url = add_query_arg([
						'tab'       => 'plugin-information',
						'plugin'    => $plugin_slug . '/' . $plugin_file,
						'section'   => 'changelog',
						'TB_iframe' => 'true',
						'width'     => 772,
						'height'    => 390,
					], admin_url('plugin-install.php'));

					$version_available_message = sprintf(
						/* translators: %s: version number with link */
						__('Version %s is available.', 'atfpp'),
						sprintf(
							'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s">%s</a>',
							esc_url($plugin_info_url),
							esc_attr(sprintf(__('View changelog for version %s', 'atfpp'), $latest_version)),
							esc_html(sprintf(__('%s (View details)', 'atfpp'), $latest_version))
						)
					);
				}
				
				return $version_available_message;
			}

		public function atfpp_ai_main_file_load() {
			static $loaded=false;

			if($loaded) return;

			$loaded=true;

			// init ai services
			if(class_exists(Plugin_Main::class)){
				$plugin_main = new Plugin_Main(ATFPP_FILE);
				$plugin_main->add_hooks();
			}
		}

		public function atfpp_load_files() {
			require_once ATFPP_DIR_PATH . 'includes/ai-translate/api.php';

			require_once ATFPP_DIR_PATH . '/helper/class-atfp-register-route.php';
			if(class_exists('ATFP_Register_Route')){
				new ATFP_Register_Route('atfpp-translate');
			}

			require_once ATFPP_DIR_PATH . '/includes/bulk-translation/class-atfp-sync-post.php';
			require_once ATFPP_DIR_PATH . '/includes/bulk-translation/class-atfp-posts-clone.php';
			require_once ATFPP_DIR_PATH . '/includes/bulk-translation/class-atfp-term-clone.php';
			require_once ATFPP_DIR_PATH . '/includes/bulk-translation/class-atfp-bulk-translation.php';
			require_once ATFPP_DIR_PATH . '/helper/class-atfp-helper.php';
			require_once ATFPP_DIR_PATH . 'admin/atfp-menu-pages/class-atfp-custom-block-post.php';
			if(is_admin()) {
				require_once ATFPP_DIR_PATH . 'includes/class-atfp-register-backend-assets.php';
			}
			require_once ATFPP_DIR_PATH . 'includes/elementor-translate/class-atfpp-elementor-translate.php';
		}

		/*
		|------------------------------------------------------------------------
		|  Hide unrelated notices
		|------------------------------------------------------------------------
		*/
		public function atfpp_hide_unrelated_notices()
			{ // phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded, Generic.Metrics.NestingLevel.MaxExceeded
				$cfkef_pages = false;

				$page=isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
				if($page == 'polylang-atfpp-dashboard'){
					$cfkef_pages = true;
				}

				if ($cfkef_pages) {
					global $wp_filter;
					// Define rules to remove callbacks.
					$rules = [
						'user_admin_notices' => [], // remove all callbacks.
						'admin_notices'      => [],
						'all_admin_notices'  => [],
						'admin_footer'       => [
							'render_delayed_admin_notices', // remove this particular callback.
						],
					];
					$notice_types = array_keys($rules);
					foreach ($notice_types as $notice_type) {
						if (empty($wp_filter[$notice_type]->callbacks) || ! is_array($wp_filter[$notice_type]->callbacks)) {
							continue;
						}
						$remove_all_filters = empty($rules[$notice_type]);
						foreach ($wp_filter[$notice_type]->callbacks as $priority => $hooks) {
							foreach ($hooks as $name => $arr) {
								if (is_object($arr['function']) && is_callable($arr['function'])) {
									if ($remove_all_filters) {
										unset($wp_filter[$notice_type]->callbacks[$priority][$name]);
									}
									continue;
								}
								$class = ! empty($arr['function'][0]) && is_object($arr['function'][0]) ? strtolower(get_class($arr['function'][0])) : '';
								// Remove all callbacks except WPForms notices.
								if ($remove_all_filters && strpos($class, 'wpforms') === false) {
									unset($wp_filter[$notice_type]->callbacks[$priority][$name]);
									continue;
								}
								$cb = is_array($arr['function']) ? $arr['function'][1] : $arr['function'];
								// Remove a specific callback.
								if (! $remove_all_filters) {
									if (in_array($cb, $rules[$notice_type], true)) {
										unset($wp_filter[$notice_type]->callbacks[$priority][$name]);
									}
									continue;
								}
							}
						}
					}
				}

				add_action( 'admin_notices', [ $this, 'atfpp_admin_notices' ], PHP_INT_MAX );
			}

		function atfpp_admin_notices() {
			do_action( 'atfpp_display_admin_notices' );
		}

		/*
		|------------------------------------------------------------------------
		|  Get user info
		|------------------------------------------------------------------------
		*/

		public static function atfpp_get_user_info() {
			global $wpdb;
			$server_info = [
			'server_software'        => sanitize_text_field($_SERVER['SERVER_SOFTWARE'] ?? 'N/A'),
			'mysql_version'          => sanitize_text_field($wpdb->get_var("SELECT VERSION()")),
			'php_version'            => sanitize_text_field(phpversion()),
			'wp_version'             => sanitize_text_field(get_bloginfo('version')),
			'wp_debug'               => sanitize_text_field(defined('WP_DEBUG') && WP_DEBUG ? 'Enabled' : 'Disabled'),
			'wp_memory_limit'        => sanitize_text_field(ini_get('memory_limit')),
			'wp_max_upload_size'     => sanitize_text_field(ini_get('upload_max_filesize')),
			'wp_permalink_structure' => sanitize_text_field(get_option('permalink_structure', 'Default')),
			'wp_multisite'           => sanitize_text_field(is_multisite() ? 'Enabled' : 'Disabled'),
			'wp_language'            => sanitize_text_field(get_option('WPLANG', get_locale()) ?: get_locale()),
			'wp_prefix'              => sanitize_key($wpdb->prefix), // Sanitizing database prefix
			];
			$theme_data = [
			'name'      => sanitize_text_field(wp_get_theme()->get('Name')),
			'version'   => sanitize_text_field(wp_get_theme()->get('Version')),
			'theme_uri' => esc_url(wp_get_theme()->get('ThemeURI')),
			];
			if (!function_exists('get_plugins')) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}
			$plugin_data = array_map(function ($plugin) {
			$plugin_info = get_plugin_data(WP_PLUGIN_DIR . '/' . sanitize_text_field($plugin));
			$author_url = ( isset( $plugin_info['AuthorURI'] ) && !empty( $plugin_info['AuthorURI'] ) ) ? esc_url( $plugin_info['AuthorURI'] ) : 'N/A';
			$plugin_url = ( isset( $plugin_info['PluginURI'] ) && !empty( $plugin_info['PluginURI'] ) ) ? esc_url( $plugin_info['PluginURI'] ) : '';
			return [
				'name'       => sanitize_text_field($plugin_info['Name']),
				'version'    => sanitize_text_field($plugin_info['Version']),
				'plugin_uri' => !empty($plugin_url) ? $plugin_url : $author_url,
			];
			}, get_option('active_plugins', []));
			return [
				'server_info' => $server_info,
				'extra_details' => [
					'wp_theme' => $theme_data,
					'active_plugins' => $plugin_data,
				]
			];
		}

		public function atfpp_display_admin_notices() {
			$license_key = get_option('AIAutomaticTranslationsForPolylang_lic_Key', '');

			if (empty($license_key)) {
				printf(
					'<div class="notice notice-error is-dismissible atfp-license-notice"><p>%1$s</p></div>',
					sprintf(
						esc_html__(
							'Your license key is missing. Please enter your license key on the %s page to access all premium features of %s.',
							'autopoly-ai-translation-for-polylang-pro'
						),
						'<a href="admin.php?page=polylang-atfpp-dashboard&tab=license"><strong>' . esc_html__('License', 'autopoly-ai-translation-for-polylang-pro') . '</strong></a>',
						'<strong>' . esc_html('AutoPoly - AI Translation For Polylang (Pro)') . '</strong>'
					)
				);
			}
		}

		/**
		 * Initialize the Automatic Translation for Polylang plugin.
		 *
		 * @return void
		 */
		function atfpp_init() {
			// Check Polylang plugin is installed and active
			global $polylang;
			$atfpp_polylang = $polylang;

			if ( isset( $atfpp_polylang ) && is_admin() ) {

				// Loading Licenser Manager
				require_once ATFPP_DIR_PATH . '/admin/Register/AIAutomaticTranslationsForPolylang.php';

				require_once ATFPP_DIR_PATH . '/helper/class-atfp-ajax-handler.php';
				if ( class_exists( 'ATFPP_Ajax_Handler' ) ) {
					ATFPP_Ajax_Handler::get_instance();
				}

				add_action( 'add_meta_boxes', array( $this, 'atfpp_gutenberg_metabox' ) );

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

				$this->atfpp_register_backend_assets();
				
				$this->initialize_elementor_translation_instance();

				// Review Notice
				if(class_exists('Atfpp_Dashboard')) {
					Atfpp_Dashboard::review_notice(
						'atfp', // Required
						'AutoPoly - AI Translation For Polylang (Pro)', // Required
						'https://wordpress.org/support/plugin/automatic-translations-for-polylang/reviews/#new-post', // Required
					);
				}
			} else {
				add_action( 'admin_notices', array( self::$instance, 'atfpp_plugin_required_admin_notice' ) );
			}
		}

		public function onInit() {
			if ( in_array(
				'automatic-translations-for-polylang/automatic-translation-for-polylang.php',
				apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
			) ) {
				include_once ABSPATH . 'wp-admin/includes/plugin.php';
				// Ensure the plugin is deactivated securely
				if ( current_user_can( 'activate_plugins' ) ) {
					deactivate_plugins( 'automatic-translations-for-polylang/automatic-translation-for-polylang.php' );
					add_action('admin_notices', array($this, 'atfp_free_plugin_notice'));
				}
				return;
			}
		}

		public function atfp_free_plugin_notice() {
			echo '<div class="error"><p>';
			// translators: 1: Pro plugin name, 2: Free plugin name
			echo sprintf(
				esc_html__(
					'The %1$s plugin is active and the %2$s plugin has been deactivated. Enjoy exploring more advanced features in the Pro version!',
					'autopoly-ai-translation-for-polylang-pro'
				),
				'<strong>AutoPoly - AI Translation For Polylang (Pro)</strong>',
				'<strong>AutoPoly - AI Translation for Polylang (Free)</strong>'
			) . '</p></div>';
		}

		/**
		 * Load plugin textdomain.
		 */
		public function load_plugin_textdomain() {
			load_plugin_textdomain( 'autopoly-ai-translation-for-polylang-pro', false, basename( dirname( __FILE__ ) ) . '/languages/' );
		}


		/**
		 * Display admin notice for required plugin activation.
		 *
		 * @return void
		 */
		function atfpp_plugin_required_admin_notice() {
			if ( current_user_can( 'activate_plugins' ) ) {
				$url         = 'plugin-install.php?tab=plugin-information&plugin=polylang&TB_iframe=true';
				$title       = 'Polylang';
				$plugin_info = get_plugin_data( __FILE__, true, true );
				echo '<div class="error"><p>' .
				sprintf(
					// translators: 1: Plugin Name, 2: Plugin URL
					esc_html__(
						'In order to use %1$s plugin, please install and activate the latest version  of %2$s',
						'autopoly-ai-translation-for-polylang-pro'
					),
					wp_kses( '<strong>' . esc_html( $plugin_info['Name'] ) . '</strong>', array('strong' => array()) ),
					wp_kses( '<a href="' . esc_url( $url ) . '" class="thickbox" title="' . esc_attr( $title ) . '">' . esc_html( $title ) . '</a>', array('a' => array('href' => array(), 'class' => array(), 'title' => array())) )
				) . '.</p></div>';
			}
		}

		/**
		 * Register backend assets for Automatic Translation for Polylang plugin.
		 *
		 * @return void
		 */
		function atfpp_register_backend_assets() {
			if(class_exists('ATFPP_Register_Backend_Assets')) {
				ATFPP_Register_Backend_Assets::get_instance();
			}
		}

		/**
         * Initialize the Automatic Translation instance for Elementor pages using Polylang plugin.
         *
         * @return void
         */
		function initialize_elementor_translation_instance() {
			if(class_exists('ATFPP_Elementor_Translate')) {
				ATFPP_Elementor_Translate::get_instance();
			}
		}
		/**
		 * Register and display the automatic translation metabox.
		 */
		function atfpp_gutenberg_metabox() {
			if ( isset( $_GET['from_post'], $_GET['new_lang'], $_GET['_wpnonce'] ) &&
				 wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'new-post-translation' ) ) {
				$post_id = isset( $_GET['from_post'] ) ? absint( $_GET['from_post'] ) : 0;

				if ( 0 === $post_id ) {
					return;
				}

				$editor = '';
				if ( 'builder' === get_post_meta( $post_id, '_elementor_edit_mode', true ) && defined('ELEMENTOR_VERSION') ) {
					$editor = 'Elementor';
				}
				if ( 'on' === get_post_meta( $post_id, '_et_pb_use_builder', true ) && defined('ET_CORE') ) {
					$editor = 'Divi';
				}

				$current_screen = get_current_screen();
				if ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() && ! in_array( $editor, array( 'Elementor', 'Divi' ), true ) ) {
					if ( 'post-new.php' === $GLOBALS['pagenow'] && isset( $_GET['from_post'], $_GET['new_lang'] ) ) {
						global $post;

						if ( ! ( $post instanceof WP_Post ) ) {
							return;
						}

						if ( ! function_exists( 'PLL' ) || ! PLL()->model->is_translated_post_type( $post->post_type ) ) {
							return;
						}
						add_meta_box( 'atfp-meta-box', __( 'Automatic Translate', 'autopoly-ai-translation-for-polylang-pro' ), array( $this, 'atfpp_metabox_text' ), null, 'side', 'high' );
					}
				}
			}
		}

		function atfpp_classic_editor_button() {
			global $polylang;
			global $post;

			if(!isset($post) || !isset($post->ID)){
				return;
			}

			$atfpp_polylang = $polylang;
			$post_translate_status = get_post_meta($post->ID, '_atfpp_translate_status', true);
			$post_parent_post_id = get_post_meta($post->ID, '_atfpp_parent_post_id', true);

			if ( isset( $atfpp_polylang ) && is_admin() ) {
				if ( (isset( $_GET['from_post'], $_GET['new_lang'], $_GET['_wpnonce'] ) &&
				 wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'new-post-translation' ))) {

				$post_id = isset( $_GET['from_post'] ) ? absint( $_GET['from_post'] ) : 0;
				$post_id = !empty($post_parent_post_id) ? $post_parent_post_id : $post_id;

				if ( 0 === $post_id ) {
					return;
				}
				
				$editor = '';
				if ( 'builder' === get_post_meta( $post_id, '_elementor_edit_mode', true ) && defined('ELEMENTOR_VERSION') ) {
					$editor = 'Elementor';
				}
				if ( 'on' === get_post_meta( $post_id, '_et_pb_use_builder', true ) && defined('ET_CORE') ) {
					$editor = 'Divi';
				}

				$current_screen = get_current_screen();
				if ( method_exists( $current_screen, 'is_block_editor' ) && !$current_screen->is_block_editor() && ! in_array( $editor, array( 'Elementor', 'Divi' ), true ) ) {
					if ( ('post-new.php' === $GLOBALS['pagenow'] && isset( $_GET['from_post'], $_GET['new_lang'] )) || (!empty($post_translate_status) && $post_translate_status === 'pending' && !empty($post_parent_post_id)) ) {

						if ( ! ( $post instanceof WP_Post ) ) {
							return;
						}

						if ( ! function_exists( 'PLL' ) || ! PLL()->model->is_translated_post_type( $post->post_type ) ) {
							return;
						}

						if(empty($post_translate_status) && empty($post_parent_post_id)) {
							update_post_meta($post->ID, '_atfpp_translate_status', 'pending');
							update_post_meta($post->ID, '_atfpp_parent_post_id', $post_id);
						}
						
						echo '<button class="button button-primary" id="atfp-classic-editor-translate-button">' . esc_html__( 'Translate Page', 'autopoly-ai-translation-for-polylang-pro' ) . '</button>';
					}
				}
			}
			}
		}

		/**
		 * Display the automatic translation metabox button.
		 */
		function atfpp_metabox_text() {
			if ( isset( $_GET['_wpnonce'] ) &&
				 wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'new-post-translation' ) ) {
				$target_language = '';
				if ( function_exists( 'PLL' ) ) {
					$parent_post_id = absint(isset( $_GET['from_post'] ) ? sanitize_key( $_GET['from_post'] ) : '');
					$parent_post_language = pll_get_post_language( $parent_post_id, 'name' );
					$target_code = isset( $_GET['new_lang'] ) ? sanitize_key( $_GET['new_lang'] ) : '';
					$languages   = PLL()->model->get_languages_list();
					foreach ( $languages as $lang ) {
						if ( $lang->slug === $target_code ) {
							$target_language = $lang->name;
						}
					}
				}
				?>
				<input type="button" class="button button-primary" name="atfp_meta_box_translate" id="atfp-translate-button" value="<?php echo esc_attr__( 'Translate Page', 'autopoly-ai-translation-for-polylang-pro' ); ?>" readonly/><br><br>
				<p style="margin-bottom: .5rem;"><?php echo esc_html( sprintf( __( 'Translate or duplicate content from %s to %s', 'autopoly-ai-translation-for-polylang-pro' ), $parent_post_language, $target_language ) ); ?></p>
				<?php
				if(class_exists('Atfpp_Dashboard') && !Atfpp_Dashboard::atfpp_hide_review_notice_status('atfp')){
					?>
					<hr>
				<div class="atfp-review-meta-box">
				<p><?php echo esc_html__( 'We hope you find our plugin helpful for your translation needs. Your feedback is valuable to us!', 'autopoly-ai-translation-for-polylang-pro' ); ?>
				<br>
					<a href="<?php echo esc_url( 'https://wordpress.org/plugins/automatic-translations-for-polylang/reviews/#new-post' ); ?>" class="components-button is-primary is-small" target="_blank"><?php echo esc_html__( 'Rate Us', 'autopoly-ai-translation-for-polylang-pro' ); ?><span> ★★★★★</span></a>
					</p>
				</div>
				<?php
				}
			}
		}

		/*
		|----------------------------------------------------------------------------
		| Run when activate plugin.
		|----------------------------------------------------------------------------
		*/
		public static function atfpp_activate() {
			$previous_version=get_option('atfp-v', false);
			$migration_status=get_option('atfp_translation_string_migration', false);

			if($previous_version && version_compare($previous_version, '1.4.0', '<') && !$migration_status && class_exists('ATFPP_Helper')){
				ATFPP_Helper::translation_data_migration();
			}

			update_option( 'atfpp-v', ATFPP_V );
			update_option( 'atfpp-type', 'FREE' );
			update_option( 'atfpp-installDate', gmdate( 'Y-m-d h:i:s' ) );

			if(!get_option('atfpp-install-date')) {
				add_option('atfpp-install-date', gmdate('Y-m-d h:i:s'));
			}

			if (!get_option( 'atfpp_initial_save_version' ) ) {
				add_option( 'atfpp_initial_save_version', ATFPP_V );
			}

			$get_opt_in = get_option('atfp_feedback_opt_in');
			
			if ($get_opt_in =='yes' && !wp_next_scheduled('atfpp_extra_data_update')) {

				wp_schedule_event(time(), 'every_30_days', 'atfpp_extra_data_update');
			}
		}

		/*
		|----------------------------------------------------------------------------
		| Run when de-activate plugin.
		|----------------------------------------------------------------------------
		*/
		public static function atfpp_deactivate() {
			wp_clear_scheduled_hook('atfpp_extra_data_update');
		}

	}

}

function AutoPolyPro() {
	return AutoPolyPro::get_instance();
}

$AutoPolyPro = AutoPolyPro();
