<?php
/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

class FSRS_ADMIN_INIT {

	private static $instance;

	private $notif_size = 0;

	/**
	 * enqueue all admin styles
	 */
	public function enqueue_styles() {
		// include bootstrap only in our plugin setting page
		if ( isset( $_GET["page"] ) && ( strpos( $_GET['page'], 'full-schema-rich-snippet' ) !== false ) ) {
			wp_enqueue_style( 'bootstrap', FSRS_ADMIN_URL . 'css/bootstrap.min.css' );
			wp_enqueue_style( 'full-schema', FSRS_ADMIN_URL . 'css/fsrs-ui.css', false,
				FULL_SCHEMA_RICH_SNIPPET_VERSION );
		}
		wp_enqueue_style( 'fsrs-faq-schema-jquery-ui',
			FSRS_ADMIN_URL . 'css/jquery-ui.css', [], '2.0.0' );
		wp_enqueue_style( 'sweetalert2', FSRS_ADMIN_URL . 'css/sweetalert2.min.css',
			false, FULL_SCHEMA_RICH_SNIPPET_VERSION );
		wp_enqueue_style( 'fsrs-faq-schema-style', FSRS_ADMIN_URL . 'css/fsrs-admin-style.css',
			false, FULL_SCHEMA_RICH_SNIPPET_VERSION );
	}

	/**
	 * enqueue all admin scripts
	 */
	public function enqueue_scripts() {
		wp_enqueue_script( 'sweetalert2', FSRS_ADMIN_URL . 'js/sweetalert2.all.min.js',
			array( 'jquery' ), FULL_SCHEMA_RICH_SNIPPET_VERSION );
		wp_enqueue_script( 'papaparse', FSRS_ADMIN_URL . 'js/papaparse.min.js',
			array( 'jquery' ), FULL_SCHEMA_RICH_SNIPPET_VERSION, true );
		wp_register_script( 'fsrs-main-script', FSRS_ADMIN_URL . 'js/fsrs-admin-main.js', [
			'jquery',
			'papaparse',
			'sweetalert2',
			'jquery-ui-accordion',
		], FULL_SCHEMA_RICH_SNIPPET_VERSION, true );
		wp_localize_script( 'fsrs-main-script', 'fsrs_main_object',
			array(
				'popupTitle'       => __( 'برای پاک کردن این سوال و جواب اطمینان دارید؟', 'full-schema' ),
				'popupDesc'        => __( 'در صورت پاک کردن دیگر نمی‌توانید این آیتم را بازگردانید!', 'full-schema' ),
				'popupConfirm'     => __( 'بله پاک کن!', 'full-schema' ),
				'popupDeny'        => __( 'نه پاک نکن', 'full-schema' ),
				'popupSuccessMess' => __( 'آيتم با موفقیت حذف شد', 'full-schema' ),
			) );
		wp_enqueue_script( 'fsrs-main-script' );
		// include scripts only in our plugin setting page
		if ( isset( $_GET["page"] ) && ( strpos( $_GET['page'], 'full-schema-rich-snippet' ) !== false ) ) {
			wp_enqueue_style( 'wp-color-picker' );
			wp_register_script( 'fsrs_admin_setting', FSRS_ADMIN_URL . 'js/fsrs-admin-settings.js',
				array( 'jquery', 'wp-color-picker', 'sweetalert2' ), FULL_SCHEMA_RICH_SNIPPET_VERSION,
				true );
			$nonce = wp_create_nonce( "fsrs_admin_nonce" );
			wp_localize_script( 'fsrs_admin_setting', 'fsrs_object', array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => $nonce
			) );
			wp_enqueue_script( 'fsrs_admin_setting' );
			wp_enqueue_script( 'font-awesome', FSRS_ADMIN_URL . 'js/all.min.js' );
			wp_enqueue_script( 'bootstrap', FSRS_ADMIN_URL . 'js/bootstrap.min.js' );
		}

	}

	public function sample_admin_notice__success() {
		$validity = get_option( 'fsrs-pr-license', '' );
		if ( empty( $validity ) ) { ?>
            <div class="notice notice-error">
                <p style="font-size: 16px;">
                    هنوز فول اسکیما را فعال نکردید! لطفا برای استفاده از امکانات افزونه آن را فعال سازی کنید.
                </p>
                <p style="font-size: 16px;">
                    <a href="<?php echo admin_url() . 'admin.php?page=full-schema-rich-snippet' ?>">
                        <button class="button-primary">فعال کردن افزونه</button>
                    </a>
                </p>
            </div>
		<?php }
	}

	/**
	 * Initialize metabox
	 *
	 * @return void
	 */
	public function fsrs_add_custom_box() {
		$sc_types = $post_types = get_post_types( array( 'public' => true ) );
		foreach ( $sc_types as $sc_type ) {
			add_meta_box(
				'fsrs_rating_schema',
				'افزونه فول اسکیما سفینه',
				[ $this, 'fsrs_rating_box_html' ],
				$sc_type
			);
		}
	}

	public function fsrs_rating_box_html( $post ) {
		$vObject = get_post_meta( $post->ID, '_fsrs_schema', true );
		if ( empty( $vObject ) ) {
			$vObject = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post->ID, '' );
		}
		$page_rating_show_option = get_post_meta( $post->ID, '_fsrs_page_star_option', true );
		if ( empty( $page_rating_show_option ) ) {
			$page_rating_show_option = array( 'showOption' => '0' );
		}

		$post_type = get_post_type( get_the_ID() );

		ob_start();
		if ( $post_type !== 'product' ) {
			include_once FSRS_ADMIN_DIR . 'template/fsrs-rating-meta-temp.php';
			include_once FSRS_ADMIN_DIR . 'template/fsrs-faq-meta-temp.php';
		}
		include_once FSRS_ADMIN_DIR . 'template/fsrs-script-meta-temp.php';
		echo ob_get_clean();
	}

	/**
	 * Save meta values
	 *
	 * @param int $post_id Post ID.
	 *
	 * @return void
	 * @access public
	 *
	 */
	public function save( int $post_id ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return;
		}


		$this->fsrs_save_faq( $post_id );
		$this->save_fsrs_schema( $post_id );
		$this->save_fsrs_inject_script( $post_id );
	}

	/**
	 * Save FAQ Options
	 *
	 * @param $post_id
	 */
	private function fsrs_save_faq( $post_id ) {
		if ( ! isset( $_POST['fsrs-faq-schema-nonce'] ) || !
			wp_verify_nonce( sanitize_key( $_POST['fsrs-faq-schema-nonce'] ), 'fsrs-faq-schema' ) ) {
			return;
		}
		update_post_meta( $post_id, '_fsrs_faq_schema',
			! isset( $_POST['fsrs-faq-schema'] ) ? [] : $this->sanitize( $_POST['fsrs-faq-schema'] ) ); // phpcs:ignore
	}

	/**
	 * Save rating Options
	 *
	 * @param $post_id
	 */
	private function save_fsrs_schema( $post_id ) {
		if ( ! isset( $_POST['fsrs-schema-nonce'] ) || !
			wp_verify_nonce( sanitize_key( $_POST['fsrs-schema-nonce'] ), 'fsrs-rating-schema' ) ) {
			return;
		}

		$radioVal          = $_POST["fsrs-schema-radio"] ?? '3';
		$page_show_options = $_POST['fsrs-rating-show-option'] ?? '';
		$desc              = $_POST['fsrs-vo-desc'] ?? '';
		$contentUrl        = $_POST['fsrs-vo-video-url'] ?? '';
		$title             = $_POST['fsrs-vo-title'] ?? '';
		$duration          = $_POST['fsrs-vo-duration'] ?? '';

		$n_content_url = (string) $contentUrl;
		if ( get_post_type() === 'post' ) {
			if ( empty( $title ) ) {
				$title = get_the_title( $post_id );
			}
			$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id, $title );
			if ( $radioVal === '1' ) {
				$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::video_object_options( $post_id, $title, $desc,
					$duration,
					$n_content_url );
			}
			if ( $radioVal === '2' ) {
				$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::audio_object_options( $duration, $title, $desc,
					$n_content_url );
			}
			if ( $radioVal === '3' ) {
				$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id, $title );
			}
			update_post_meta( $post_id, '_fsrs_schema', $new_meta_value );

		} else if ( get_post_type() !== 'post' ) {
			if ( $page_show_options === '1' ) {
				if ( empty( $title ) ) {
					$title = get_the_title( $post_id );
				}
				$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id, $title );
				if ( $radioVal === '1' ) {
					$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::video_object_options( $post_id, $title,
						$desc, $duration,
						$n_content_url );
				}
				if ( $radioVal === '2' ) {
					$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::audio_object_options( $duration, $title, $desc,
						$n_content_url );
				}
				if ( $radioVal === '3' ) {
					$new_meta_value = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id, $title );
				}
				update_post_meta( $post_id, '_fsrs_schema', $new_meta_value );
				update_post_meta( $post_id, '_fsrs_page_star_option', array( 'showOption' => '1' ) );
			} else {
				update_post_meta( $post_id, '_fsrs_page_star_option', array( 'showOption' => '0' ) );
			}
		}
	}

	public function add_setting_link( $links, $file ) {
		if ( $file !== FSRS_PLUGIN_BASENAME ) {
			return $links;
		}
		$settings_link = '<a href="admin.php?page=full-schema-rich-snippet">' . esc_html__( 'تنظیمات',
				'full-schema' ) . '</a>';
		array_unshift( $links, $settings_link );

		return $links;
	}

	/**
	 * Save inject script
	 *
	 * @param $post_id
	 */
	private function save_fsrs_inject_script( $post_id ) {
		if ( ! isset( $_POST['fsrs-script-nonce'] ) || !
			wp_verify_nonce( sanitize_key( $_POST['fsrs-script-nonce'] ), 'fsrs-script' ) ) {
			return;
		}

		$header      = $_POST['fsrs-script-header'] ?? '';
		$footer      = $_POST['fsrs-script-footer'] ?? '';
		$script_data = array(
			'header' => $header,
			'footer' => $footer
		);
		update_post_meta( $post_id, '_fsrs_script', $script_data );
	}

	/**
	 * Sanitize full array
	 *
	 * @param array $faqs Array.
	 *
	 * @return  array
	 * @access public
	 *
	 */
	private function sanitize( array $faqs ): array {
		$new_faqs = [];

		if ( ! empty( $faqs ) && is_array( $faqs ) ) {
			foreach ( $faqs as $faq ) {
				$new_faq = [];

				if ( ! empty( $faq['q'] ) ) {
					$new_faq['q'] = sanitize_text_field( $faq['q'] );
				}
				if ( ! empty( $faq['a'] ) ) {
					$new_faq['a'] = $faq['a'];
					(string) $new_faq;
				}
				if ( ! empty( $new_faq ) ) {
					$new_faqs[] = $new_faq;
				}
			}
		}

		return $new_faqs;
	}

	public function tax_meta() {
		ob_start();
		?>
        <div class="form-field is-tax">
			<?php $this->tax_meta_label(); ?>
			<?php include_once FSRS_ADMIN_DIR . 'template/fsrs-faq-tax-meta-temp.php' ?>
        </div>
		<?php
		echo ob_get_clean();
	}

	public function tax_meta_edit( $term ) {
		ob_start() ?>
        <tr class="form-field store-logo-wrap">
            <th scope="row">
				<?php $this->tax_meta_label(); ?>
            </th>
            <td>
				<?php
				$term_id = $term->term_id;
				$faqs    = $term_id ? get_term_meta( $term_id, '_fsrs_faq_schema', true ) : '';
				include_once FSRS_ADMIN_DIR . 'template/fsrs-faq-tax-meta-temp.php' ?>
            </td>
        </tr>
		<?php
		echo ob_get_clean();
	}

	private function tax_meta_label() {
		?>
        <label class="is-tax-label"><?php esc_html( __( 'اسکیما faq برای پست ها و برگه ها %s',
				'fsrs-faq-schema' ) ) ?></label>
		<?php
	}

	public function save_tax_meta( $term_id ) {
		if ( ! isset( $_POST['fsrs-faq-schema-nonce'] ) || !
			wp_verify_nonce( sanitize_key( $_POST['fsrs-faq-schema-nonce'] ), 'fsrs-faq-schema' ) ) {
			return;
		}

		update_term_meta( $term_id, '_fsrs_faq_schema',
			! isset( $_POST['fsrs-faq-schema'] ) ? [] : $this->sanitize( $_POST['fsrs-faq-schema'] ) );
	}

	public function fsrs_daily_check_promotion_callback() {
		$response = wp_remote_post( 'https://safine.net/api/fsrs/apigetvalue.php', array(
			'method'      => 'POST',
			'timeout'     => 45,
			'redirection' => 5,
			'httpversion' => '1.0',
			'blocking'    => true,
		) );
		if ( ! is_wp_error( $response ) ) {
			$var1 = $response['body'];
			$obj  = json_decode( $var1 );
			update_option( 'fsrs_promo',
				array(
					'content' => str_replace( '\\', '', $obj->{'info'} ),
					'count'   => $obj->{'notif_size'},
					'alert'   => $obj->{'alert'}
				) );
		}
	}

	/**
	 * check license validity once a day
	 */
	public function fsrs_daily_check_validity() {
		$pr_code = get_option( 'license_key', '' );
		$valid   = get_option( 'fsrs_pr_option', '' );
		if ( ! empty( $pr_code ) && ! empty( $valid ) ) {
			$res = FSRS_COMMON::get_instance()->check_license( (string) $pr_code );
			if ( ! $res && $valid['valid'] === '1' ) {
				update_option( 'fsrs_pr_option', array( 'license' => (string) $pr_code, 'valid' => '0' ),
					true );
			}
		}
	}

	public function fsrsMenuPage() {
		$fsrs_promo           = get_option( 'fsrs_promo', array() );
		$notif_option_content = get_option( 'fsrs_notif_option', ' ' );
		$notif_content        = $notif_option_content['notif_content'] ?? '';
		if ( $notif_content !== ( $fsrs_promo['content'] ?? '' ) ) {
			$this->notif_size = $fsrs_promo['count'];
		}
		$menu_title = '<div class="fsrs-main-menu">' . esc_html__( 'فول اسیکما', 'full-schema' ) . '
                       </div>';
		if ( $this->notif_size > 0 ) {
			$menu_title = '<div class="fsrs-main-menu">' . esc_html__( 'فول اسیکما', 'full-schema' ) . '
                        <span class="fsrs-main-notif" style="background: #f16334;
                           font-size: 12px; display: inline-block; width: 20px; height: 20px;
                           text-align: center; font-family: inherit; line-height: 1.5;
                           border-radius: 100px; color: white">' . $this->notif_size . '
                        </span>
                       </div>';
		}
		add_menu_page(
			esc_html__( 'تنظیمات فول اسکیما', 'full-schema' ),
			$menu_title,
			'administrator',
			'full-schema-rich-snippet',
			[ $this, 'fsrs_setup_main_page' ],
			'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAAGz7rX1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDYuMC1jMDAyIDc5LjE2NDQ2MCwgMjAyMC8wNS8xMi0xNjowNDoxNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXB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4Ny+Xr3eZI1BTcvT02eXOb1l/1NqGdqGyU89UuQ3ilMoTE39iLjbqi7gW3BKIR0R4MCOcIEY5rCTR9fESyD/Wq6zi50mxEyHZqFIVOC1szqccsFjwufxIkA2BBHdSidTzLVZ4quLqSJZDODie85brhyTO7DEO4GAhInkhU5DdhYd0nJ9LHVASTCHyaiGhCCsLVxShKK0GiX4ER8oG0tJ9hPYOZdNao5ummY4Jo8TT7W59aPtivnk/7bstJC8hIrQ4ipBEwrviSLglZkwx2xQ5bQRasEg8ivCqLMii9OmdCnPuvwlKECp7uRUyQqVQyVPVGq9/z1cFmnOyuSMS4bjdBvD2CvC8u3Dl4HeO7dsPloAgPhnGh8Ta8z9tgbkiB6eBS+dGHiEXEsGwV5qwCERc/btxLxXY+TULxbIBICJncFzytDpQ9tSEo56F7235cczegKaUGmVsoOrxeDIkG/H39MPRpTPKb9ysMUzIV1+yulozc5ev7LEJrnbkZBcwkiPgmMGzZ4D0lY9tOiuZaAtLrgqwboFFu5qoCi0Rhm59zwukKX1997O5aphMO+zFOVYqUn+P53HRPyBCPJZDZjYIug0UVHD4pckc0QAiXqKTy1he4UdvwrtH4/KxZb61Yq7tebwqs4NBPKZ0IhwcuVR/F3vxMX0Pry1tht1kGQamSJZ6RMyApiwELbGg70PykyR+oWwvkcfv0H0rleYzSgvcfSjO0yppD6gOLKhZ3BgExBD+3xOZnxF8UL8Tc/n0SSRCvHEnaebZMq8lKVg7YJCQvjBAezN8ZYo12DkTuV94cfqQbLLDadv7Zh/7n+QVkruAszv9m4QAAAABJRU5ErkJggg==',
			'73'
		);
	}


	public function fsrs_setup_main_page() {
		TABS::get_instance();
	}

	/**
	 * @return mixed
	 */
	public static function getInstance(): FSRS_ADMIN_INIT {
		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {

			self::$instance = new self;

		}

		return self::$instance;
	}
}