<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

class Oxy_Toolbox_YoastIntegration {

	static $prefix;
	static $mod = 'yoast_integration_';
	static $title = 'Yoast Integration';
	static $description = "Includes WordPress content in Yoast's SEO analsysis when using Oxygen.";
	static $link = 'https://oxyplugins.com/doc/yoast-integration/';
	
	static function init( $prefix ) {
		self::$prefix = $prefix;
		$oxy_toolbox_mod = new Oxy_Toolbox_Mod( $prefix, self::$mod, self::$title, self::$description, self::$link );

		// this will block the rest of the mod to load, if it is not checked.
		if ( 0 === intval( get_option( self::$prefix . self::$mod, 0 ) ) || OxyToolboxLicense::is_activated_license() !== true) {
			return;
		}

		// check if Yoast Seo is active.
		include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
		if ( ! is_plugin_active( 'wordpress-seo/wp-seo.php' ) && ! is_plugin_active( 'wordpress-seo-premium/wp-seo-premium.php' ) ) {
			return;
		}

		remove_action( 'admin_enqueue_scripts', 'oxygen_vsb_yoast_compatibility', 99 );

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'mod_admin_scripts' ), 99 );
	}

	static function mod_admin_scripts() {

		global $pagenow;
		global $post;
	
		// save global $post to restore later.
		$saved_post = $post;
	
		// exclude templates.
		if ( is_object( $post ) && $post->post_type == 'ct_template' ) {
			return;
		}
	
		if ( 'post.php' == $pagenow && ! is_null( $post ) ) {
			wp_register_script( self::$prefix . self::$mod . 'script', plugins_url( 'js/script.js', __FILE__ ), [ 'jquery' ], '', true );
			
			wp_enqueue_script( self::$prefix . self::$mod . 'script' );

			wp_localize_script( self::$prefix . self::$mod . 'script', self::$prefix . self::$mod . 'ysco_data', [
				'oxygen_markup' => do_shortcode( get_post_meta( $post->ID, 'ct_builder_shortcodes', true ) )
			]);
		}
	
		// restore original global post.
		$post = $saved_post;
	}
	
}

Oxy_Toolbox_YoastIntegration::init( self::PREFIX );