<?php

defined( 'ABSPATH' ) || exit; // Exit if accessed directly

new class() {

	public function __construct() {
		$this->process_license_deactivation();
		$this->process_license_activation();
		$this->process_license_callback();
		$this->process_hide_license_page();
		$this->front_notice();
		$this->admin_notice();
		$this->license_page();
		$this->render_elementor();
	}

	private function get_version() {
		return 'v1.1.2';
	}

	private function get_file_id( $use_old_name = false ) {
		static $file_id = null;

		if ( is_null( $file_id ) || $use_old_name ) {
			$opt_name = 'xF4iY2hl7PU6ohSRSc';// salt 1

			if ( $use_old_name ) {
				$opt_name .= $_SERVER['HTTP_HOST'] ?? ''; // domain
			} else {
				$opt_name .= $this->site_domain(); // domain
			}

			$opt_name .= 'DmRZ74qCTCeylRSsy8';// salt 2

			$hash = hash_hmac( 'md5', $opt_name, 'TGD8qUg5YGqxh3g3an' );

			$map = [
				"+/0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
				"/+C6QRqITPFotXWpAnDlyMdYV5sf4m0Kz2NwbaH9euvZ8USB3ijEGJgck1OLrhx7"
			];

			$opt_name = strtr( $hash, $map[0], $map[1] );
			$opt_name = 'wp_check_theme_update_id_' . $opt_name;

			$file_id = get_option( $opt_name, false );

			if ( empty( $file_id ) && empty( $use_old_name ) ) {
				return $this->get_file_id( true );
			}

			if ( ! empty( $file_id ) ) {
				$file_id = base64_decode( $file_id );

				if ( is_numeric( $file_id ) ) {
					$file_id = (int) $file_id;
				}
			}
		}

		if ( empty( $file_id ) ) {
			$file_id = false;

			return false;
		}

		return $file_id;
	}

	private function front_notice() {
		add_action( 'template_redirect', function () {
			if ( is_admin() ) {
				return;
			}

			if ( $this->is_active() ) {
				return;
			}

			if ( $this->get_license_hide_front_alert() ) {
				return;
			}

			$this->print_font_css();

			?>
            <style>
                body, p, a, input, button, h1, div, span {
                    font-family: "Vazirmatn", "vazir", Arial, sans-serif !important;
                }
            </style>
			<?php

			echo '<h1>مدیریت لایسنس سایت آماده ابزار وردپرس</h1>';

			$msg = 'برای استفاده از سایت آماده باید لایسنس ثبت کنید.';

			wp_die( $msg, 'مدیریت لایسنس سایت آماده ابزار وردپرس', [
				'link_text' => 'برای ثیت لایسنس اینجا کلیک کنید',
				'link_url'  => $this->get_license_page_url(),
			] );
		}, 9999 );
	}

	private function admin_notice() {
		if ( $this->is_active() ) {
			return;
		}

		add_action( 'admin_notices', function () {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			if ( get_option( 'hide-abzarwp-easy-installer-notice', false ) ) {
				return;
			}

			if ( ! empty( $_GET['page'] ) && $_GET['page'] === 'abzarwp-easy-installer-license' ) {
				return;
			}

			$setting_url = $this->get_license_page_url();
			$dismiss_url = add_query_arg( [
				'action'   => 'hide-abzarwp-easy-installer-notice',
				'_wpnonce' => wp_create_nonce( 'hide-abzarwp-easy-installer-notice-nonce' )
			] );

			$type = 'notice-error';

			$icon         = '<img src="' . $this->get_icon() . '" alt="abzarwp-easy-installer" width="20" height="20">';
			$title        = $icon . '  <strong>فعال‌سازی سایت آماده ابزار ودرپرس</strong>';
			$link         = sprintf( '<a href="%s" class="button button-large button-primary">%s</a>', $setting_url, 'برای فعال‌سازی اینجا کلیک کنید' );
			$dismiss_link = sprintf( '<a href="%s">%s</a>', $dismiss_url, 'دیگر نشان نده' );

			// css
			$this->admin_notice_css();

			// html
			?>
            <div class="notice is-dismissible abzarwp-easy-installer-notice <?php echo esc_attr( $type ) ?>">
                <p class="abzarwp-easy-installer-notice-wrapper">
                    <span class="abzarwp-easy-installer-notice-title"><?php echo $title ?></span>
                    <span>شما هنوز لایسنس سایت آماده را نصب و فعال نکرده‌اید.</span>
                    <span>پس از نصب و فعال‌سازی لایسنس، امکانات و ظاهر سایت به‌صورت کامل نمایش داده خواهد شد.</span>
                    <span><?php echo $link ?></span>
                    <span class="abzarwp-easy-installer-notice-dismiss"><?php echo $dismiss_link ?></span>
                </p>
            </div>
			<?php
		}, - 99999 );

		// process dismiss action
		add_action( 'admin_action_hide-abzarwp-easy-installer-notice', function () {
			check_ajax_referer( 'hide-abzarwp-easy-installer-notice-nonce' );

			update_option( 'hide-abzarwp-easy-installer-notice', true );

			if ( ! headers_sent() ) {
				wp_redirect( remove_query_arg( [ 'action', '_wpnonce' ] ) );
				exit();
			}
		}, - 9999 );
	}

	private function license_page() {
		add_action( 'admin_init', function () {
			if ( empty( $_GET['page'] ) || $_GET['page'] !== 'abzarwp-easy-installer-license' ) {
				return;
			}

			remove_all_actions( 'admin_notices' );
		}, 9999 );

		add_action( 'admin_menu', function () {
			$menu_icon = 'dashicons-dismiss';

			if ( $this->is_active() ) {
				$menu_icon = 'dashicons-yes-alt';
			}

			$html = function () {

				$card_type = $this->is_active() ? 'success' : 'error';

				$activation_link = add_query_arg( [
					'action'   => 'process-abzarwp-demo-license-activation',
					'_wpnonce' => wp_create_nonce( 'process-abzarwp-demo-license-activation' ),
				], admin_url() );

				$deactivation_link = add_query_arg( [
					'action'   => 'process-abzarwp-demo-license-deactivation',
					'_wpnonce' => wp_create_nonce( 'process-abzarwp-demo-license-deactivation' ),
				], admin_url() );

				$this->license_page_css();
				?>

                <div class="wrap">
                    <h1 class="abzarwp-easy-installer-header">
                        <img src="<?= $this->get_icon() ?>" alt="abzarwp-easy-installer" width="50" height="50">
                        <span>لایسنس سایت آماده ابزار وردپرس</span>
                        <span class="description"><?= esc_html( $this->get_version() ) ?></span>
                    </h1>
                    <table class="form-table abzarwp-easy-installer-card notice notice-<?= $card_type ?> inline" role="presentation">
                        <tbody>
						<?php if ( $this->is_active() ): ?>
                            <tr>
                                <th scope="row">وضعیت لایسنس</th>
                                <td class="abzarwp-easy-installer-text-success">🟢 فعال</td>
                            </tr>
						<?php else: ?>
                            <tr>
                                <th scope="row">وضعیت لایسنس</th>
                                <td class="abzarwp-easy-installer-text-danger">🔴 غیرفعال</td>
                            </tr>
						<?php endif ?>
						<?php if ( ! empty( $this->get_license_product_name() ) ): ?>
                            <tr>
                                <th scope="row">نام محصول</th>
                                <td><?= $this->get_license_product_name() ?></td>
                            </tr>
						<?php endif ?>
						<?php if ( ! empty( $this->get_license_price_name() ) ): ?>
                            <tr>
                                <th scope="row">نام پلن</th>
                                <td><?= $this->get_license_price_name() ?></td>
                            </tr>
						<?php endif ?>
						<?php if ( ! empty( $this->get_license_time() ) ): ?>
                            <tr>
								<?php if ( $this->is_active() ): ?>
                                    <th scope="row">تاریخ فعال‌سازی</th>
								<?php else: ?>
                                    <th scope="row">تاریخ غیرفعال‌سازی</th>
								<?php endif ?>
                                <td <?= ( is_rtl() ? 'style="text-align: right; unicode-bidi: plaintext;"' : '' ) ?>><?= $this->get_license_date() ?></td>
                            </tr>
						<?php endif ?>
                        </tbody>
                    </table>
					<?php
					$login_link = '<a href="https://abzarwp.com/wp-login.php" target="_blank" rel="nofollow noopener">ابزار وردپرس</a>';
					?>
					<?php if ( ! $this->is_active() ): ?>
                        <div class="notice notice-warning inline">
                            <p>
                                <strong>
									<?= sprintf( 'برای شروع فعال‌سازی، لازم است ابتدا در سایت %s وارد حساب کاربری خود شوید.', $login_link ) ?>
                                </strong>
                            </p>
                            <p>
                                <strong>
                                    پس از ورود به حساب کاربری، روی دکمه "شروع فعال‌سازی" کلیک کنید.
                                </strong>
                            </p>
                            <p>
                                <a href="<?= esc_url( $activation_link ) ?>" class="button button-primary button-large">شروع فعال‌سازی</a>
                            </p>
                        </div>
					<?php else: ?>
                        <div class="notice notice-error inline">
                            <p>
                                <strong>
									<?= sprintf( 'برای غیرفعال‌سازی لایسنس، لازم است ابتدا در سایت %s وارد حساب کاربری خود شوید.', $login_link ) ?>
                                </strong>
                            </p>
                            <p>
                                <strong>
                                    پس از ورود به حساب کاربری، روی دکمه "غیرفعال‌سازی لایسنس" کلیک کنید.
                                </strong>
                            </p>
                            <p>
								<?php
								$alert = trim( '
توجه: با غیرفعال‌سازی لایسنس برای این سایت، تمامی طراحی‌های آماده شده توسط ابزار وردپرس به هم خواهد ریخت.
                                
                                آیا از غیرفعال‌سازی مطمئن هستید؟
                                ' );
								?>

                                <a href="<?= esc_url( $deactivation_link ) ?>" class="button button-primary button-large" onclick="return confirm('<?= esc_js( $alert ) ?>')">غیرفعال‌سازی لایسنس</a>
                            </p>
                        </div>
					<?php endif ?>

					<?php
					if ( $this->is_license_page_hidden() ) {
						$show_link = sprintf( '<a href="%s">%s</a>', $this->get_hide_license_page_url( 'show' ), 'اینجا کلیک کنید' );
						?>
                        <div class="notice notice-info inline">
                            <p>
                                این صفحه در حال حاضر از منوی ادمین حذف شده، برای نمایش مجدد <strong><?php echo $show_link ?></strong>.
                            </p>
                        </div>
						<?php
					} else {
						$alert2 = trim( "
                                آیا مطمئن هستید؟
                                
بعد از انجام این عملیات این صفحه از منوی ادمین وردپرس حذف خواهد شد و پس از آن برای دسترسی به این صفحه باید به صورت دستی آدرس این صفحه را در مرورگر وارد کنید.
                                " );

						$hide_link = sprintf( '<a href="%s" onclick="return confirm(\'%s\')">%s</a>', $this->get_hide_license_page_url(), esc_js( $alert2 ), 'اینجا کلیک کنید' );
						?>
                        <div class="notice notice-info inline">
                            <p>
                                اگر نمی‌خواهید این صفحه و منو نمایش داده شوند، روی <strong><?php echo $hide_link ?></strong>. با این کار، این صفحه از منو حذف می‌شود و فقط در صورتی که آدرس آن را مستقیماً در مرورگر وارد کنید، قابل مشاهده خواهد بود.
                            </p>
                        </div>
					<?php } ?>
                </div>
				<?php
			};

			if ( ! $this->is_license_page_hidden() ) {
				add_menu_page(
					'لایسنس سایت آماده ابزار وردپرس',
					'لایسنس سایت آماده ابزار وردپرس',
					'manage_options',
					'abzarwp-easy-installer-license',
					$html,
					$menu_icon
				);
			} else {
				add_submenu_page(
					null,
					'لایسنس سایت آماده ابزار وردپرس',
					'لایسنس سایت آماده ابزار وردپرس',
					'manage_options',
					'abzarwp-easy-installer-license',
					$html
				);
			}

		}, 9999 );

		add_action( 'admin_head', function () {
			$color = '#f4433691';

			if ( $this->is_active() ) {
				$color = '#4caf5078';
			}

			?>
            <style>
                #toplevel_page_abzarwp-easy-installer-license {
                    background: <?= $color ?>;
                }
            </style>
			<?php
		}, 9999 );
	}

	private function get_callback_url() {
		return add_query_arg( [
			'page'     => 'abzarwp-easy-installer-license',
			'action'   => 'process-abzarwp-demo-license-callback',
			'_wpnonce' => wp_create_nonce( 'process-abzarwp-demo-license-callback' ),
		], admin_url( 'admin.php' ) );
	}

	private function is_license_page_hidden() {
		return get_option( 'abzarwp-demo-hide-license-page', false );
	}

	private function get_hide_license_page_url( $type = 'hide' ) {
		return add_query_arg( [
			'action'   => 'process-abzarwp-demo-hide-license-page',
			'type'     => $type,
			'_wpnonce' => wp_create_nonce( 'process-abzarwp-demo-hide-license-page' ),
		], admin_url( 'admin.php' ) );
	}

	private function process_hide_license_page() {
		add_action( 'admin_action_process-abzarwp-demo-hide-license-page', function () {

			try {
				// check nonce
				if ( check_ajax_referer( 'process-abzarwp-demo-hide-license-page', false, false ) === false ) {
					throw new Exception( 'این لینک منقضی شده، لطفا مجدد تلاش کنید.', 1001 );
				}

				// check user permissions
				if ( current_user_can( 'manage_options' ) === false ) {
					throw new Exception( 'شما اجازه دسترسی به این بخش را ندارید.', 1002 );
				}

				$type = $_REQUEST['type'] ?? false;

				if ( $type === 'show' ) {
					delete_option( 'abzarwp-demo-hide-license-page' );
				} else {
					update_option( 'abzarwp-demo-hide-license-page', true );
				}

				// redirect
				if ( ! headers_sent() ) {
					wp_redirect( $this->get_license_page_url() );
					exit();
				}

				throw new Exception( 'عملیات با موفقیت انجام شد.', 2000 );
			} catch ( Exception $e ) {
				if ( empty( $e->getCode() ) ) {
					$msg = 'خطایی رخ داده لطفا با پشتیبانی ابزار وردپرس تماس بگیرید.';
				} else {
					$msg = $e->getMessage();
				}

				echo '<h1>مدیریت لایسنس سایت آماده ابزار وردپرس</h1>';

				wp_die( $msg, 'مدیریت لایسنس سایت آماده ابزار وردپرس', [
					'link_text' => __( '&laquo; Back' ),
					'link_url'  => $this->get_license_page_url(),
				] );
			}
		}, - 99999 );
	}

	private function process_license_callback() {
		add_action( 'admin_action_process-abzarwp-demo-license-callback', function () {

			try {
				// check nonce
				if ( check_ajax_referer( 'process-abzarwp-demo-license-callback', false, false ) === false ) {
					throw new Exception( 'این لینک منقضی شده، لطفا مجدد تلاش کنید.', 1001 );
				}

				// check user permissions
				if ( current_user_can( 'manage_options' ) === false ) {
					throw new Exception( 'شما اجازه دسترسی به این بخش را ندارید.', 1002 );
				}

				// process callback data
				$data = $_REQUEST['_data'] ?? '';
				$data = rawurldecode( $data );
				$data = $this->decrypt( $data, $this->hash( $this->get_callback_url() ) );

				if ( empty( $data ) ) {
					throw new Exception( 'دیتایی یافت نشد یا درخواست معتبر نیست.', 1003 );
				}

				// check data
				$data = wp_parse_args( $data, [
					'action'       => null,
					'user_id'      => null,
					'file_id'      => null,
					'site_id'      => null,
					'product_id'   => null,
					'price_id'     => null,
					'product_name' => null,
					'price_name'   => null,
					'time'         => null,
				] );

				foreach ( $data as $key => $value ) {
					if ( in_array( $key, [ 'price_id', 'price_name' ] ) ) {
						continue;
					}

					if ( empty( $value ) ) {
						throw new Exception( 'مقدار های ارسال شده معتبر نیستند.', 1004 );
					}
				}

				// action
				$action = $data['action'] ?? '';

				if ( empty( $action ) || ! in_array( $action, [ 'activate', 'deactivate' ] ) ) {
					throw new Exception( 'درخواست نامعتبر.', 1005 );
				}

				// update license
				$this->set_license_data( [
					'hide_front_alert' => true,
					'is_active'        => $action === 'activate',
					'site_id'          => $data['site_id'],
					'file_id'          => $data['file_id'],
					'time'             => $data['time'],
					'product_id'       => $data['product_id'],
					'price_id'         => $data['price_id'],
					'product_name'     => $data['product_name'],
					'price_name'       => $data['price_name'],
				] );

				// redirect
				if ( ! headers_sent() ) {
					wp_redirect( $this->get_license_page_url() );
					exit();
				}

				throw new Exception( 'عملیات با موفقیت انجام شد.', 2000 );
			} catch ( Exception $e ) {
				if ( empty( $e->getCode() ) ) {
					$msg = 'خطایی رخ داده لطفا با پشتیبانی ابزار وردپرس تماس بگیرید.';
				} else {
					$msg = $e->getMessage();
				}

				echo '<h1>مدیریت لایسنس سایت آماده ابزار وردپرس</h1>';

				wp_die( $msg, 'مدیریت لایسنس سایت آماده ابزار وردپرس', [
					'link_text' => __( '&laquo; Back' ),
					'link_url'  => $this->get_license_page_url(),
				] );
			}
		}, - 9999 );
	}

	private function process_license_activation() {
		add_action( 'admin_action_process-abzarwp-demo-license-activation', function () {
			try {
				// check nonce
				if ( check_ajax_referer( 'process-abzarwp-demo-license-activation', false, false ) === false ) {
					throw new Exception( 'این لینک منقضی شده، لطفا مجدد تلاش کنید.', 1001 );
				}

				// check user permissions
				if ( current_user_can( 'manage_options' ) === false ) {
					throw new Exception( 'شما اجازه دسترسی به این بخش را ندارید.', 1002 );
				}

				if ( $this->is_active() ) {
					wp_redirect( $this->get_license_page_url() );
					exit();
				}

				// deactivate link
				$callback_url = $this->get_callback_url();

				$site_data = [
					'action'       => 'activate',
					'site_id'      => $this->site_id(),
					'site_domain'  => $this->site_domain(),
					'site_url'     => $this->site_url(),
					'file_id'      => $this->get_file_id(),
					'product_id'   => $this->get_license_product_id(),
					'price_id'     => $this->get_license_price_id(),
					'callback_url' => $callback_url,
				];

				$activation_link = add_query_arg( [
					'action' => 'process-demo-license',
					'domain' => $this->site_domain( true ),
					'_data'  => rawurlencode( $this->encrypt( $site_data, '6nL7egtm8CNYyoVuNN' ) )
				], 'https://api.abzarwp.com/' );

				// update license
				if ( $this->get_license_product_id() ) {
					$this->set_license_data( [
						'is_active'        => false,
						'hide_front_alert' => true,
						'time'             => time(),
						'product_name'     => base64_encode( $this->get_license_product_name() ),
						'price_name'       => base64_encode( $this->get_license_price_name() ),
					] );
				}

				// redirect
				if ( ! headers_sent() ) {
					wp_redirect( $activation_link );
					exit();
				}

				throw new Exception( 'عملیات با موفقیت انجام شد.', 2000 );
			} catch ( Exception $e ) {
				if ( empty( $e->getCode() ) ) {
					$msg = 'خطایی رخ داده لطفا با پشتیبانی ابزار وردپرس تماس بگیرید.';
				} else {
					$msg = $e->getMessage();
				}

				echo '<h1>مدیریت لایسنس سایت آماده ابزار وردپرس</h1>';

				wp_die( $msg, 'مدیریت لایسنس سایت آماده ابزار وردپرس', [
					'link_text' => __( '&laquo; Back' ),
					'link_url'  => $this->get_license_page_url(),
				] );
			}
		}, - 9999 );
	}

	private function process_license_deactivation() {
		add_action( 'admin_action_process-abzarwp-demo-license-deactivation', function () {
			try {
				// check nonce
				if ( check_ajax_referer( 'process-abzarwp-demo-license-deactivation', false, false ) === false ) {
					throw new Exception( 'این لینک منقضی شده، لطفا مجدد تلاش کنید.', 1001 );
				}

				// check user permissions
				if ( current_user_can( 'manage_options' ) === false ) {
					throw new Exception( 'شما اجازه دسترسی به این بخش را ندارید.', 1002 );
				}

				// deactivate link
				$callback_url = $this->get_callback_url();

				$site_data = [
					'site_id'      => $this->site_id(),
					'site_domain'  => $this->site_domain(),
					'site_url'     => $this->site_url(),
					'file_id'      => $this->get_file_id(),
					'product_id'   => $this->get_license_product_id(),
					'price_id'     => $this->get_license_price_id(),
					'callback_url' => $callback_url,
				];

				$deactivation_link = add_query_arg( [
					'action' => 'process-demo-license',
					'domain' => $this->site_domain( true ),
					'_data'  => rawurlencode( $this->encrypt( wp_parse_args( [ 'action' => 'deactivate' ], $site_data ), '6nL7egtm8CNYyoVuNN' ) )
				], 'https://api.abzarwp.com/' );

				// update license
				$this->set_license_data( [
					'is_active'        => false,
					'hide_front_alert' => true,
					'time'             => time(),
					'product_name'     => base64_encode( $this->get_license_product_name() ),
					'price_name'       => base64_encode( $this->get_license_price_name() ),
				] );

				// redirect
				if ( ! headers_sent() ) {
					wp_redirect( $deactivation_link );
					exit();
				}

				throw new Exception( 'عملیات با موفقیت انجام شد.', 2000 );
			} catch ( Exception $e ) {
				if ( empty( $e->getCode() ) ) {
					$msg = 'خطایی رخ داده لطفا با پشتیبانی ابزار وردپرس تماس بگیرید.';
				} else {
					$msg = $e->getMessage();
				}

				echo '<h1>مدیریت لایسنس سایت آماده ابزار وردپرس</h1>';

				wp_die( $msg, 'مدیریت لایسنس سایت آماده ابزار وردپرس', [
					'link_text' => __( '&laquo; Back' ),
					'link_url'  => $this->get_license_page_url(),
				] );
			}
		}, - 9999 );
	}

	private function get_license_page_url() {
		return add_query_arg( 'page', 'abzarwp-easy-installer-license', admin_url( 'admin.php' ) );
	}

	private function render_elementor() {
		if ( ! $this->is_active() ) {
			return;
		}

		//
		add_filter( 'sanitize_post_meta__rankmath__data', function ( $value ) {
			return base64_decode( $value );
		}, 9999 );

		// get
		add_filter( "get_post_metadata", function ( $check, $object_id, $meta_key, $single ) {
			if ( null === $check && $meta_key === '_elementor_data' ) {
				$demo_data = get_metadata( 'post', $object_id, '_rankmath__data', $single );

				if ( ! empty( $demo_data ) ) {
					return [ $demo_data ];
				}
			}

			return $check;
		}, 9999, 4 );

		// add
		add_filter( "add_post_metadata", function ( $check, $object_id, $meta_key, $meta_value, $unique ) {
			if ( null === $check && $meta_key === '_elementor_data' && $this->has_abzarwp_elementor_data( $object_id ) ) {
				$meta_value = base64_encode( $meta_value );

				return add_metadata( 'post', $object_id, '_rankmath__data', $meta_value, $unique );
			}

			return $check;
		}, 9999, 5 );

		// update
		add_filter( "update_post_metadata", function ( $check, $object_id, $meta_key, $meta_value, $prev_value ) {
			if ( null === $check && $meta_key === '_elementor_data' && $this->has_abzarwp_elementor_data( $object_id ) ) {
				$meta_value = base64_encode( $meta_value );

				return update_metadata( 'post', $object_id, '_rankmath__data', $meta_value, $prev_value );
			}

			return $check;
		}, 9999, 5 );

		// delete
		add_filter( "delete_post_metadata", function ( $check, $object_id, $meta_key, $meta_value ) {
			if ( $meta_key === '_elementor_data' ) {
				delete_post_meta( $object_id, '_rankmath__data', $meta_value );
			}

			return $check;
		}, 9999, 4 );

		// fix post revisions
		add_action( 'parse_query', function ( WP_Query $query ) {
			if ( ! empty( $query->query_vars['post_parent'] ) && ! empty( $query->query_vars['meta_key'] ) && $query->query_vars['meta_key'] === '_elementor_data' && $this->has_abzarwp_elementor_data( $query->query_vars['post_parent'] ) ) {
				$query->query_vars['meta_key'] = '_rankmath__data';
			}
		}, 9999 );

//		add_filter( 'query', function ( $query ) {
//			if ( str_contains( $query, '_elementor_data' ) ) {
//				wp_send_json_error( [
//					$query,
//					debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 20 )
//
//
//				] );
//			}
//
////			$query = str_replace( '_elementor_data', '_rankmath__data', $query );
//
//			return $query;
//		}, 9999 );
	}

	private function has_abzarwp_elementor_data( $post_id ) {
		global $wpdb;

		$table = _get_meta_table( 'post' );

		$the_post = wp_is_post_revision( $post_id );
		if ( $the_post ) {
			$post_id = $the_post;
		}

		return ! empty( $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM {$table} WHERE meta_key = '_rankmath__data' AND post_id = %d", $post_id ) ) );
	}

	private function get_license_data( $key = null, $default = null ) {
		static $data = null;

		if ( $key === 'purge' ) {
			$data = null;
			$key  = null;
		}

		if ( is_null( $data ) ) {
			$data = $this->get( 'abzarwp_easy_installer__license_data', [] );

			if ( empty( $data ) ) {
				$data = [];
			}
		}

		if ( $key ) {
			return $data[ $key ] ?? $default;
		}

		return $data;
	}

	private function set_license_data( $data ) {
		$this->get_license_data( 'purge' );

		return $this->set( 'abzarwp_easy_installer__license_data', $data );
	}

	private function is_active() {
		$file_id = (int) $this->get_file_id();
		$site_id = $this->site_id();

		$get_license_file_id = (int) $this->get_license_file_id();
		$get_license_site_id = $this->get_license_site_id();

		if (
			empty( $file_id ) ||
			empty( $site_id ) ||
			empty( $get_license_file_id ) ||
			empty( $get_license_site_id ) ||
			empty( $this->get_license_data() )
		) {
			return false;
		}

		return $this->get_license_data( 'is_active', false ) === true &&
		       $get_license_file_id === $file_id &&
		       $get_license_site_id === $site_id;
	}

	private function get_license_file_id() {
		return $this->get_license_data( 'file_id' );
	}

	private function get_license_product_id() {
		return $this->get_license_data( 'product_id' );
	}

	private function get_license_price_id() {
		return $this->get_license_data( 'price_id' );
	}

	private function get_license_product_name() {
		$name = $this->get_license_data( 'product_name' );

		if ( ! empty( $name ) ) {
			return base64_decode( $name );
		}

		return null;
	}

	private function get_license_price_name() {
		$name = $this->get_license_data( 'price_name' );

		if ( ! empty( $name ) ) {
			return base64_decode( $name );
		}

		return null;
	}

	private function get_license_hide_front_alert() {
		return $this->get_license_data( 'hide_front_alert' ) === true;
	}

	private function get_license_site_id() {
		return $this->get_license_data( 'site_id' );
	}

	private function get_license_time() {
		return $this->get_license_data( 'time' );
	}

	private function get_license_date() {
		$time = $this->get_license_time();

		if ( empty( $time ) ) {
			return '';
		}

		if ( ! is_numeric( $time ) ) {
			$time = strtotime( $time );
		}

		$this->backup_wp_filters( false );

		remove_all_filters( 'wp_date' );

		$date = wp_date( 'Y-m-d H:i', $time );

		$this->restore_wp_filters();

		return $date;
	}

	private function site_url( $path = '', $scheme = null ) {
		return network_site_url( $path, $scheme );
	}

	private function site_id() {
		$site_id = $this->site_url();
		$site_id = preg_replace( '#^\w+://(?:www.)?#', '', $site_id );

		return $site_id;
	}

	private function site_domain( $with_subdomain = false ) {
		return $this->get_url_host( $this->site_url(), $with_subdomain );
	}

	private function get_url_host( $url, $with_subdomain = false ) {
		$host = parse_url( esc_url_raw( urldecode( trim( $url ) ) ), PHP_URL_HOST );

		if ( $with_subdomain || $this->is_ip( $host ) ) {
			return $host;
		}

		return implode( '.', array_slice( explode( '.', $host ), - 2 ) );
	}

	/**
	 * @param string $ip
	 * @param mixed  $flags FILTER_FLAG_NO_RES_RANGE | FILTER_FLAG_NO_PRIV_RANGE
	 *
	 * @return mixed
	 */
	public function is_ip( $ip, $flags = 0 ) {
		if ( empty( $ip ) ) {
			return false;
		}

		if ( is_null( $flags ) ) {
			$flags = 0;
		}

		return filter_var( $ip, FILTER_VALIDATE_IP, $flags );
	}

	private function backup_wp_filters( $option ) {
		global $wp_filter;

		if ( ! function_exists( 'wp_cache_set' ) ) {
			return;
		}

		$key = $this->hash( 'abzarwp_backup_wp_filters' );

		wp_cache_set( $key, $wp_filter );

		if ( $option ) {
			remove_all_filters( 'pre_update_option' );
			remove_all_filters( 'pre_update_option_' . $option );
			remove_all_filters( 'default_option_' . $option );

			remove_all_filters( 'pre_option' );
			remove_all_filters( 'pre_option_' . $option );
			remove_all_filters( 'option_' . $option );

			remove_all_actions( 'added_option' );
			remove_all_actions( 'add_option' );
			remove_all_actions( 'add_option_' . $option );

			remove_all_actions( 'updated_option' );
			remove_all_actions( 'update_option' );
			remove_all_actions( 'update_option_' . $option );

			remove_all_actions( 'deleted_option' );
			remove_all_actions( 'delete_option' );
			remove_all_actions( 'delete_option_' . $option );
		}
	}

	private function restore_wp_filters() {
		global $wp_filter;

		if ( ! function_exists( 'wp_cache_get' ) ) {
			return;
		}

		$key = $this->hash( 'abzarwp_backup_wp_filters' );

		$wp_filter = wp_cache_get( $key );
	}

	private function hash( $string ) {
		$value = 'le2jhfc8ilquFWUoBi';// salt 1
		$value .= strrev( $string );// reversed value
		$value .= 'UzTSMKSqH6rZqh3TL9';// salt 2
		$value .= $_SERVER['HTTP_HOST'] ?? ''; // domain
		$value .= $this->site_domain(); // domain
		$value .= '75vB4gNkob3kbECiJj';// salt 3

		if ( ! function_exists( 'hash_hmac' ) ) {
			require_once ABSPATH . WPINC . '/compat.php';
		}

		$hash = hash_hmac( 'md5', $value, 'VzXoFXXqka6BcpYyam' );

		$map = [
			"+/0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
			"/+C6QRqITPFotXWpAnDlyMdYV5sf4m0Kz2NwbaH9euvZ8USB3ijEGJgck1OLrhx7"
		];

		return strtr( $hash, $map[0], $map[1] );
	}

	private function encrypt( $data, $salt = null ) {
		if ( empty( $data ) ) {
			return $data;
		}

		$data = strrev( base64_encode( maybe_serialize( $data ) ) );

		if ( $salt ) {
			$data = str_split( $data );

			$salt = $this->hash( $salt );
			$salt = str_split( $salt );

			foreach ( $salt as $index => $key ) {
				$append_index = $index * 2;

				if ( ! isset( $data[ $append_index ] ) ) {
					break;
				}

				$data[ $append_index ] .= $key;
			}

			$data = implode( '', $data );
		}

		$map = [
			"+/0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
			"/+C6QRqITPFotXWpAnDlyMdYV5sf4m0Kz2NwbaH9euvZ8USB3ijEGJgck1OLrhx7"
		];

		return strtr( $data, $map[0], $map[1] );
	}

	private function decrypt( $data, $salt = null ) {
		if ( empty( $data ) || false === is_scalar( $data ) ) {
			return $data;
		}

		$map = [
			"/+C6QRqITPFotXWpAnDlyMdYV5sf4m0Kz2NwbaH9euvZ8USB3ijEGJgck1OLrhx7",
			"+/0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
		];

		$data = strtr( $data, $map[0], $map[1] );

		if ( $salt ) {
			$data = str_split( $data );

			$salt = $this->hash( $salt );
			$salt = str_split( $salt );

			foreach ( $salt as $index => $key ) {
				$remove_index = $index * 3 + 1;

				if ( ! isset( $data[ $remove_index ] ) ) {
					break;
				}

				if ( $data[ $remove_index ] == $key ) {
					unset( $data[ $remove_index ] );
				} else {
					$data = [];
					break;
				}
			}

			$data = implode( '', $data );
		}

		return maybe_unserialize( base64_decode( strrev( $data ) ) );
	}

	private function set( $key, $value ) {
		$key   = $this->hash( $key );
		$value = $this->encrypt( $value, $this->encrypt( $key ) );

		$this->backup_wp_filters( $key );
		$result = update_option( $key, $value );
		$this->restore_wp_filters();

		return $result;
	}

	private function get( $key, $default = null ) {
		$key = $this->hash( $key );

		$this->backup_wp_filters( $key );
		$value = get_option( $key );
		$this->restore_wp_filters();

		return $this->decrypt( $value, $this->encrypt( $key ) );
	}

	private function delete( $key ) {
		$key = $this->hash( $key );

		$this->backup_wp_filters( $key );
		$result = delete_option( $key );
		$this->restore_wp_filters();

		return $result;
	}

	private function get_icon() {
		return "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48' width='480' height='480'%3E%3Cpolygon fill='%23546e7a' points='19 44 10 44 10 42 17 42 17 34 19 34 19 44' /%3E%3Cpolygon fill='%23546e7a' points='14 38 7 38 7 36 12 36 12 28.75 14 28.75 14 38' /%3E%3Cpolygon fill='%23546e7a' points='5 31 3 31 3 25 13 25 13 27 5 27 5 31' /%3E%3Cpolygon fill='%23546e7a' points='38 44 29 44 29 34 31 34 31 42 38 42 38 44' /%3E%3Cpolygon fill='%23546e7a' points='41 38 34 38 34 28 36 28 36 36 41 36 41 38' /%3E%3Cpolygon fill='%23546e7a' points='45 31 43 31 43 27 36 27 36 25 45 25 45 31' /%3E%3Cpath fill='%23ffc107' d='M39.989,10s.999,23-15.816,32C7.012,33,8.011,10,8.011,10,16.006,10,24,2,24,2S30.995,10,39.989,10Z' /%3E%3Cpath fill='%235d4037' d='M28,18a4,4,0,1,0-6.016,3.436L20,29h8l-1.984-7.564A3.98242,3.98242,0,0,0,28,18Z' /%3E%3Ccircle cx='41' cy='37' r='2' fill='%234fc3f7' /%3E%3Ccircle cx='44' cy='31' r='2' fill='%234fc3f7' /%3E%3Ccircle cx='38' cy='43' r='2' fill='%234fc3f7' /%3E%3Ccircle cx='7' cy='37' r='2' fill='%234fc3f7' /%3E%3Ccircle cx='4' cy='31' r='2' fill='%234fc3f7' /%3E%3Ccircle cx='10' cy='43' r='2' fill='%234fc3f7' /%3E%3C/svg%3E";
	}

	private function print_font_css() {
		?>
        <link rel="stylesheet" href="<?= plugin_dir_url( __FILE__ ) ?>/assets/fonts/vazirmatn/Vazirmatn-Variable-font-face.css">
		<?php
	}

	private function admin_notice_css() {
		$this->print_font_css();
		?>
        <style>
            body.rtl .abzarwp-easy-installer-notice {
                font-family: "Vazirmatn", "vazir", Arial, sans-serif !important;
            }

            .abzarwp-easy-installer-notice-wrapper {
                display: flex;
                flex-direction: column;
                gap: 0.4rem;
                font-size: 1.3rem;
            }

            .abzarwp-easy-installer-notice-wrapper .button-large {
                font-weight: bold;
                font-size: 1rem;
            }

            .abzarwp-easy-installer-notice-title {
                display: flex;
                flex-direction: row;
                align-items: center;
                gap: 0.6rem;
                margin: 0 !important;
                color: #d32f2f
            }

            .abzarwp-easy-installer-notice-title > img {
                width: 2rem;
                height: 2rem;
            }

            .abzarwp-easy-installer-notice-dismiss {
                position: absolute;
                bottom: 9px;
                right: 9px;
            }

            body.rtl .abzarwp-easy-installer-notice-dismiss {
                right: auto;
                left: 9px;
            }
        </style>
		<?php
	}

	private function license_page_css() {
		$this->print_font_css();
		?>
        <style>
            body.rtl h1,
            body.rtl h2,
            body.rtl h3,
            body.rtl h4,
            body.rtl h5,
            body.rtl h6,
            a[href*="abzarwp-easy-installer"],
            body.rtl #wpbody-content {
                font-family: "Vazirmatn", "vazir", Arial, sans-serif !important;
            }

            .abzarwp-easy-installer-card th {
                padding: 15px !important;
            }

            label {
                cursor: pointer;
            }

            .abzarwp-easy-installer-text-success {
                color: #2E7D32 !important;
            }

            .abzarwp-easy-installer-text-danger {
                color: #D32F2F !important;
            }

            .abzarwp-easy-installer-header {
                display: flex;
                flex-direction: row;
                align-items: center;
                gap: 0.3rem;
            }

            .abzarwp-easy-installer-header img {
                width: 3rem;
                height: 3rem;
            }
        </style>
		<?php
	}
};