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

if ( ! class_exists( 'SftcyWordaiMetabox') ) {
class SftcyWordaiMetabox {
	private static $initiated = false;
	
	public function __construct() {
		if ( ! self::$initiated ) {
			self::initiate_hooks();
		}
	}	

	/**
	 * Hook	
	 */
	private static function initiate_hooks() {
		 // Enqueue scripts
		add_action('admin_enqueue_scripts', array( __CLASS__, 'admin_metabox_required_scripts') );		

		add_action( 'add_meta_boxes', array( __CLASS__, 'wordai_add_metaboxes' ) );
		add_action( 'add_meta_boxes', array( __CLASS__, 'wordai_add_seo_fields_metaboxes' ) );

		add_action( 'save_post', array( __CLASS__, 'wordai_save_seo_fields' ) );

		// Front-end meta output ( Basic & Social Meta )
		add_action( 'wp_head', array( __CLASS__, 'wordai_seo_meta_data_display' ), 5 );

		// Title filter (unchanged)
		add_filter( 'pre_get_document_title', array( __CLASS__, 'wordai_seo_title_tag_value_add' ) );

		// Editor notice
		add_action( 'edit_form_after_title', array( __CLASS__, 'wordai_seo_admin_notice_in_editor' ) );

		// ✅ AJAX (moved under this class for organization)
		add_action( 'wp_ajax_sc_wordai_check_seo_social_meta_tags', array( __CLASS__, 'sc_wordai_check_seo_social_meta_tags' ) );
		add_action( 'wp_ajax_sc_wordai_add_remove_seo_social_meta_tags', array( __CLASS__, 'sc_wordai_add_remove_seo_social_meta_tags' ) );

		self::$initiated = true;
	}


	/**
	 * Add metabox for - post , page, product
	 * WordAI Button
	 */	
	public static function wordai_add_metaboxes() {
		add_meta_box(
					'sftcy_wordai_metabox',
					__('AI Content Generator', 'wordai-pro'),                // Metabox Title
					array( __CLASS__, 'scwordai_metabox_html_callback'),     // Callback function
					array('post', 'page', 'product'),                        // Post types
					'side', 
					'high' 
				);				
	}	

	/**
	 * Add metabox for - post , page, product
	 * WordAI SEO input fields
	 */	
	public static function wordai_add_seo_fields_metaboxes() {
		add_meta_box(
					'sftcy_wordai_seo_metabox',
					__('WordAI SEO Fields', 'wordai-pro'),                				// Metabox Title
					array( __CLASS__, 'scwordai_seo_fields_metabox_html_callback'),     // Callback function
					array('post', 'page', 'product'),                        			// Post types
					'side', 
					'high' 
				);		
		
	}	

	/**
	 * Callback method
	 * Add WordAI button html contents
	 *
	 * @return void
	 */
	public static function scwordai_metabox_html_callback() {		
		include_once SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/metabox-popup.php';
	}

	/**
	 * Callback method
	 * Add WordAI SEO fields html contents
	 *
	 * @return void
	 */
	public static function scwordai_seo_fields_metabox_html_callback() {		
		include_once SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/metabox-seo-fields.php';
	}



	/** Admin Enqueue Scripts */
	public static function admin_metabox_required_scripts() {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || 'post' !== $screen->base || ! in_array( $screen->post_type, array( 'post', 'page', 'product' ), true ) ) {
			return;
		}

		wp_enqueue_script('sftcy-wordai-seo-metabox-script', plugins_url( '../admin/js/sc-wordai-seo-metabox.js', __FILE__ ) , array('jquery', 'jquery-ui-dialog', 'jquery-ui-core' ), SFTCY_WORDAI_VERSION, true);

		// Nonce
		$nonce = wp_create_nonce( 'scwordai_wpnonce' );
		$data  = array(
				'adminajax_url'              => admin_url('admin-ajax.php'),
				'base_url' 					 => home_url('/'),  // Proper WP base URL with trailing slash
				// 'base_url' 				 => home_url(),  // Proper WP base URL with trailing slash
				'nonce'                      => $nonce, 
			);

		// Localize script
		wp_localize_script( 'sftcy-wordai-seo-metabox-script', 'sftcy_wordai_seo_metabox_script_obj', $data );

		// Provide AJAX nonce if you prefer (or rely on hidden field)
		// wp_localize_script( 'sc-wordai-seo-metabox', 'sftcy_wordai_admin_metabox_script_obj', array(
		// 	'scwordai_wpnonce' => wp_create_nonce( 'scwordai_wpnonce' ),
		// ) );

	}

	/* ---------------------------------------------
	* Helpers for "Enable SEO Social Meta Tags" IDs
	* --------------------------------------------- */
	private static function get_social_allowed_ids() {
		$option_key  = 'wordai_add_social_media_meta_tags_post_ids';
		$allowed_ids = get_option( $option_key, array() );
		return is_array( $allowed_ids ) ? array_values( array_unique( array_map( 'intval', $allowed_ids ) ) ) : array();
	}
	private static function add_social_allowed_id( $post_id ) {
		$option_key  = 'wordai_add_social_media_meta_tags_post_ids';
		$allowed     = self::get_social_allowed_ids();
		if ( ! in_array( (int) $post_id, $allowed, true ) ) {
			$allowed[] = (int) $post_id;
			update_option( $option_key, $allowed, false );
		}
	}
	private static function remove_social_allowed_id( $post_id ) {
		$option_key  = 'wordai_add_social_media_meta_tags_post_ids';
		$allowed     = self::get_social_allowed_ids();
		$allowed     = array_diff( $allowed, array( (int) $post_id ) );
		update_option( $option_key, array_values( $allowed ), false );
	}



	/**
	 * Securely save all WordAI SEO meta fields.
	 *
	 * Hooked via: add_action( 'save_post', [ __CLASS__, 'wordai_save_seo_fields' ] );
	 *
	 * Adds automatic fallback for Canonical URL, SEO Title, and Meta Description.
	 *
	 * @param int $post_id Current post ID.
	 * @return void
	 */
	public static function wordai_save_seo_fields( $post_id ) {

		// 🔒 1. Bail early on autosave, revisions, or insufficient permissions
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// 🔒 2. Nonce verification
		if (
			! isset( $_POST['wordai_save_seo_fields_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( $_POST['wordai_save_seo_fields_nonce'] ), 'wordai_save_seo_fields_nonce_action' )
		) {
			return;
		}

		// ✅ 3. Collect and sanitize fields
		$fields = array(
			'_wordai_seo_title'            => isset( $_POST['wordaiseotitle'] )            ? sanitize_text_field( $_POST['wordaiseotitle'] ) : '',
			'_wordai_seo_meta_description' => isset( $_POST['wordaiseometadescription'] )  ? sanitize_textarea_field( $_POST['wordaiseometadescription'] ) : '',
			'_wordai_seo_focus_keyword'    => isset( $_POST['wordaiseofocuskeyword'] )     ? sanitize_text_field( $_POST['wordaiseofocuskeyword'] ) : '',
			'_wordai_seo_canonical_url'    => isset( $_POST['wordaiscanonicalurl'] )       ? esc_url_raw( $_POST['wordaiscanonicalurl'] ) : '',
			'_wordai_seo_robots_meta'      => isset( $_POST['wordairobotsmeta'] )          ? sanitize_text_field( $_POST['wordairobotsmeta'] ) : '',
			'_wordai_seo_schema_type'      => isset( $_POST['wordaischema'] )              ? sanitize_text_field( $_POST['wordaischema'] ) : '',
		);

		// ✅ 4. Auto-fallback: Canonical URL
		if ( empty( $fields['_wordai_seo_canonical_url'] ) ) {
			$fields['_wordai_seo_canonical_url'] = esc_url_raw( get_permalink( $post_id ) );
		}

		// ✅ 5. Auto-fallbacks: Title & Description
		$post_obj      = get_post( $post_id );
		$post_title    = isset( $post_obj->post_title )   ? sanitize_text_field( $post_obj->post_title ) : '';
		$post_excerpt  = isset( $post_obj->post_excerpt ) ? sanitize_textarea_field( $post_obj->post_excerpt ) : '';

		if ( empty( $fields['_wordai_seo_title'] ) && ! empty( $post_title ) ) {
			$fields['_wordai_seo_title'] = $post_title;
		}

		if ( empty( $fields['_wordai_seo_meta_description'] ) ) {
			if ( ! empty( $post_excerpt ) ) {
				$fields['_wordai_seo_meta_description'] = $post_excerpt;
			} else {
				$content = isset( $post_obj->post_content ) ? wp_strip_all_tags( $post_obj->post_content ) : '';
				$fields['_wordai_seo_meta_description'] = mb_substr( trim( $content ), 0, 155 );
			}
		}

		$existing_document = SftcyWordaiSeoIntegrationManager::read( $post_id );
		$had_existing_title = ! is_wp_error( $existing_document ) && ! empty( $existing_document['title'] );

		// Save through the selected SEO owner so external plugins remain authoritative.
		$write_result = SftcyWordaiSeoIntegrationManager::write(
			$post_id,
			array(
				'title'         => $fields['_wordai_seo_title'],
				'description'   => $fields['_wordai_seo_meta_description'],
				'focus_keyword' => $fields['_wordai_seo_focus_keyword'],
				'canonical'     => $fields['_wordai_seo_canonical_url'],
				'robots'        => $fields['_wordai_seo_robots_meta'],
				'schema_type'   => $fields['_wordai_seo_schema_type'],
			)
		);
		if ( is_wp_error( $write_result ) ) {
			set_transient( 'sftcy_wordai_seo_save_error_' . get_current_user_id(), $write_result->get_error_message(), MINUTE_IN_SECONDS );
		}


		/**
		 * ✅ 7. Default behavior for new posts:
		 * Add post ID only the first time it is saved, not on every save.
		 * Do NOT auto-add if user has already unchecked the setting.
		 */
		$allowed_ids = self::get_social_allowed_ids();

		// Detect brand new post (auto-draft or first publish)
		$post_status = get_post_status( $post_id );
		$is_new_post = in_array( $post_status, array( 'auto-draft', 'draft', 'pending' ), true ) && ! $had_existing_title;

		if ( $is_new_post && ! in_array( (int) $post_id, $allowed_ids, true ) ) {
			self::add_social_allowed_id( (int) $post_id );
		}

	}


	/**
	 * Add SEO & (conditionally) Social Meta Data to <head>
	 * - Basic SEO tags always (if available)
	 * - Social (OG/Twitter/LinkedIn) only when post is in the allowed list
	 */
	// public static function wordai_seo_meta_data_display() {
	// 	$post_id = get_queried_object_id();
	// 	if ( ! $post_id ) {
	// 		return;
	// 	}

	// 	// Gather SEO fields (may be empty)
	// 	$seo_title            = get_post_meta( $post_id, '_wordai_seo_title', true );
	// 	$seo_meta_description = get_post_meta( $post_id, '_wordai_seo_meta_description', true );
	// 	$focus_keyword        = get_post_meta( $post_id, '_wordai_seo_focus_keyword', true );
	// 	$canonical_url        = get_post_meta( $post_id, '_wordai_seo_canonical_url', true );
	// 	$robots_meta          = get_post_meta( $post_id, '_wordai_seo_robots_meta', true );
	// 	$schema_type          = get_post_meta( $post_id, '_wordai_seo_schema_type', true );

	// 	// Context
	// 	$permalink        = get_permalink( $post_id );
	// 	$title            = $seo_title ? $seo_title : get_the_title( $post_id );
	// 	$locale           = get_locale();
	// 	$site_name        = get_bloginfo( 'name' );
	// 	$featured_img_url = get_the_post_thumbnail_url( $post_id, 'full' );
	// 	$featured_alt     = get_post_meta( get_post_thumbnail_id( $post_id ), '_wp_attachment_image_alt', true );

	// 	// Extra (optional) — if you add settings for these in plugin options:
	// 	$twitter_site   = trim( (string) get_option( 'wordai_twitter_site', '' ) );   // e.g. @yourbrand
	// 	$twitter_creator= trim( (string) get_option( 'wordai_twitter_creator', '' ) );// e.g. @creator

	// 	$is_social_allowed = in_array( (int) $post_id, self::get_social_allowed_ids(), true );

	// 	// Start Comments
	// 	if ( $is_social_allowed ) {
	// 		echo "\n<!-- Start Both SEO & Social Meta Tags Fields -->\n";
	// 	} else {
	// 		echo "\n<!-- Start Basic SEO Meta Fields -->\n";
	// 	}
	// 	echo "<!-- Generated by WordAI Pro | Post ID: " . esc_html( $post_id ) . " -->\n";

	// 	/* --------------------------
	// 	* Basic SEO Meta (always)
	// 	* -------------------------- */
	// 	if ( ! empty( $seo_meta_description ) ) {
	// 		echo '<meta name="description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
	// 	}
	// 	if ( ! empty( $focus_keyword ) ) {
	// 		echo '<meta name="keywords" content="' . esc_attr( $focus_keyword ) . '">' . "\n";
	// 	}
	// 	if ( ! empty( $robots_meta ) ) {
	// 		echo '<meta name="robots" content="' . esc_attr( $robots_meta ) . '">' . "\n";
	// 	}
	// 	if ( ! empty( $canonical_url ) ) {
	// 		echo '<link rel="canonical" href="' . esc_url( $canonical_url ) . '">' . "\n";
	// 	}

	// 	/* --------------------------------------------------------
	// 	* Social Meta (Open Graph / Twitter / LinkedIn) — optional
	// 	* Only when enabled for this Post ID
	// 	* -------------------------------------------------------- */
	// 	if ( $is_social_allowed ) {
	// 		// Open Graph (works for Facebook, LinkedIn, WhatsApp, etc.)
	// 		echo '<meta property="og:title" content="' . esc_attr( $title ) . '">' . "\n";
	// 		if ( ! empty( $seo_meta_description ) ) {
	// 			echo '<meta property="og:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
	// 		}
	// 		echo '<meta property="og:type" content="article">' . "\n";
	// 		echo '<meta property="og:url" content="' . esc_url( $permalink ) . '">' . "\n";
	// 		echo '<meta property="og:site_name" content="' . esc_attr( $site_name ) . '">' . "\n";
	// 		echo '<meta property="og:locale" content="' . esc_attr( $locale ) . '">' . "\n";

	// 		if ( $featured_img_url ) {
	// 			echo '<meta property="og:image" content="' . esc_url( $featured_img_url ) . '">' . "\n";
	// 			if ( ! empty( $featured_alt ) ) {
	// 				echo '<meta property="og:image:alt" content="' . esc_attr( $featured_alt ) . '">' . "\n";
	// 			}
	// 		}

	// 		// Extra OG article hints (popular on Facebook/LinkedIn, Pinterest)
	// 		$published_time = get_the_date( DATE_W3C, $post_id );
	// 		$modified_time  = get_the_modified_date( DATE_W3C, $post_id );
	// 		echo '<meta property="article:published_time" content="' . esc_attr( $published_time ) . '">' . "\n";
	// 		echo '<meta property="article:modified_time" content="' . esc_attr( $modified_time ) . '">' . "\n";

	// 		// Twitter / X
	// 		echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
	// 		echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '">' . "\n";
	// 		if ( ! empty( $seo_meta_description ) ) {
	// 			echo '<meta name="twitter:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
	// 		}
	// 		if ( $featured_img_url ) {
	// 			echo '<meta name="twitter:image" content="' . esc_url( $featured_img_url ) . '">' . "\n";
	// 		}
	// 		if ( ! empty( $twitter_site ) ) {
	// 			echo '<meta name="twitter:site" content="' . esc_attr( $twitter_site ) . '">' . "\n";
	// 		}
	// 		if ( ! empty( $twitter_creator ) ) {
	// 			echo '<meta name="twitter:creator" content="' . esc_attr( $twitter_creator ) . '">' . "\n";
	// 		}

	// 		// (Note: Pinterest, Reddit, Telegram, iMessage mostly reuse OG/Twitter)
	// 	}

	// 	/* --------------------------
	// 	* JSON-LD Schema (optional)
	// 	* -------------------------- */
	// 	if ( ! empty( $schema_type ) ) {
	// 		$schema_data = array(
	// 			"@context"  => "https://schema.org",
	// 			"@type"     => $schema_type,
	// 			"headline"  => $title,
	// 			"description" => $seo_meta_description ?: '',
	// 			"mainEntityOfPage" => array(
	// 				"@type" => "WebPage",
	// 				"@id"   => $permalink
	// 			),
	// 			"url"        => $permalink,
	// 			"inLanguage" => $locale,
	// 			"publisher"  => array(
	// 				"@type" => "Organization",
	// 				"name"  => $site_name,
	// 				"logo"  => array(
	// 					"@type" => "ImageObject",
	// 					"url"   => get_site_icon_url()
	// 				),
	// 			),
	// 		);
	// 		if ( $featured_img_url ) {
	// 			$schema_data["image"] = array(
	// 				"@type" => "ImageObject",
	// 				"url"   => $featured_img_url,
	// 				"caption" => $featured_alt ?: $title,
	// 			);
	// 		}
	// 		echo '<script type="application/ld+json">' .
	// 			wp_json_encode( $schema_data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ) .
	// 			'</script>' . "\n";
	// 	}

	// 	// End Closing Comments
	// 	if ( $is_social_allowed ) {
	// 		echo "<!-- End Both SEO & Social Meta Tags Fields -->\n\n";
	// 	} else {
	// 		echo "<!-- End Basic SEO Meta Fields -->\n\n";
	// 	}

	// }

	/**
	 * Add SEO & (conditionally) Social Meta Data to <head>
	 * ----------------------------------------------------
	 * - Basic SEO tags always (if available)
	 * - Social (OG/Twitter/LinkedIn/Pinterest) only when enabled for this Post ID
	 */
	public static function wordai_seo_meta_data_display() {
		if ( ! SftcyWordaiSeoIntegrationManager::should_wordai_output() ) {
			return;
		}

		$post_id = get_queried_object_id();
		if ( ! $post_id ) {
			return;
		}

		// Gather SEO fields (may be empty)
		$seo_title            = get_post_meta( $post_id, '_wordai_seo_title', true );
		$seo_meta_description = get_post_meta( $post_id, '_wordai_seo_meta_description', true );
		$focus_keyword        = get_post_meta( $post_id, '_wordai_seo_focus_keyword', true );
		$canonical_url        = get_post_meta( $post_id, '_wordai_seo_canonical_url', true );
		$robots_meta          = get_post_meta( $post_id, '_wordai_seo_robots_meta', true );
		$schema_type          = get_post_meta( $post_id, '_wordai_seo_schema_type', true );

		// Context and derived info
		$permalink        = get_permalink( $post_id );
		$title            = $seo_title ? $seo_title : get_the_title( $post_id );
		$locale           = get_locale();
		$site_name        = get_bloginfo( 'name' );
		$featured_img_url = get_the_post_thumbnail_url( $post_id, 'full' );
		$featured_alt     = get_post_meta( get_post_thumbnail_id( $post_id ), '_wp_attachment_image_alt', true );

		// Optional global settings

		// ✅ Pull from unified WordAI Content Settings Option
		$settings_data = maybe_unserialize( get_option( 'sftcy-wordai-content-settings-data', [] ) );
		$twitter_site   = $settings_data['sc-wordai-twitter-site'] ?? '@yourbrand';
		$twitter_creator= $settings_data['sc-wordai-twitter-creator'] ?? '@creatorname';
		$pinterest_verification = $settings_data['sc-wordai-pinterest-verification'] ?? '';
		$pinterest_richpins      = ! empty( $settings_data['sc-wordai-enable-pinterest-richpins'] );
		$pinterest_domain = esc_url( home_url() ); // domain hint for Pinterest rich pins


		// Check if social meta tags are allowed
		$is_social_allowed = in_array( (int) $post_id, self::get_social_allowed_ids(), true );

		// ---------------------------
		//  Comment Headers
		// ---------------------------
		if ( $is_social_allowed ) {
			echo "\n<!-- Start Both SEO & Social Meta Tags Fields -->\n";
		} else {
			echo "\n<!-- Start Basic SEO Meta Fields -->\n";
		}
		echo "<!-- Generated by WordAI | Post ID: " . esc_html( $post_id ) . " -->\n";

		/* ==============================================
		* BASIC SEO META TAGS (always printed)
		* ============================================== */
		if ( ! empty( $seo_meta_description ) ) {
			echo '<meta name="description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
		}
		// Canonical and robots are supplied through WordPress core filters. Focus
		// keywords are analysis inputs and must not be printed as meta keywords.

		/* ==============================================
		* SOCIAL META TAGS (only when enabled)
		* ============================================== */
		if ( $is_social_allowed ) {
			// --- Open Graph (Facebook, LinkedIn, etc.)
			echo '<meta property="og:title" content="' . esc_attr( $title ) . '">' . "\n";
			if ( ! empty( $seo_meta_description ) ) {
				echo '<meta property="og:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
			}
			echo '<meta property="og:type" content="article">' . "\n";
			echo '<meta property="og:url" content="' . esc_url( $permalink ) . '">' . "\n";
			echo '<meta property="og:site_name" content="' . esc_attr( $site_name ) . '">' . "\n";
			echo '<meta property="og:locale" content="' . esc_attr( $locale ) . '">' . "\n";
			if ( $featured_img_url ) {
				echo '<meta property="og:image" content="' . esc_url( $featured_img_url ) . '">' . "\n";
				if ( ! empty( $featured_alt ) ) {
					echo '<meta property="og:image:alt" content="' . esc_attr( $featured_alt ) . '">' . "\n";
				}
			}

			// --- LinkedIn (reuses OG but adds clarity tags)
			echo '<meta property="linkedin:title" content="' . esc_attr( $title ) . '">' . "\n";
			if ( ! empty( $seo_meta_description ) ) {
				echo '<meta property="linkedin:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
			}
			if ( $featured_img_url ) {
				echo '<meta property="linkedin:image" content="' . esc_url( $featured_img_url ) . '">' . "\n";
			}

			// --- Pinterest (uses OG but adds domain verification & description)			
			if ( $pinterest_richpins ) {
				echo '<meta name="pinterest-rich-pin" content="true">' . "\n";
			}
			if ( ! empty( $pinterest_verification ) ) {
				echo '<meta name="p:domain_verify" content="' . esc_attr( $pinterest_verification ) . '">' . "\n";
			}
			
			if ( $seo_meta_description ) {
				echo '<meta name="pinterest:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
			}
			
			

			// --- Twitter
			echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
			echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '">' . "\n";
			if ( ! empty( $seo_meta_description ) ) {
				echo '<meta name="twitter:description" content="' . esc_attr( $seo_meta_description ) . '">' . "\n";
			}
			if ( $featured_img_url ) {
				echo '<meta name="twitter:image" content="' . esc_url( $featured_img_url ) . '">' . "\n";
			}
			if ( ! empty( $twitter_site ) ) {
				echo '<meta name="twitter:site" content="' . esc_attr( $twitter_site ) . '">' . "\n";
			}
			if ( ! empty( $twitter_creator ) ) {
				echo '<meta name="twitter:creator" content="' . esc_attr( $twitter_creator ) . '">' . "\n";
			}

			// --- OG Article time fields
			$published_time = get_the_date( DATE_W3C, $post_id );
			$modified_time  = get_the_modified_date( DATE_W3C, $post_id );
			echo '<meta property="article:published_time" content="' . esc_attr( $published_time ) . '">' . "\n";
			echo '<meta property="article:modified_time" content="' . esc_attr( $modified_time ) . '">' . "\n";
		}

		/* ==============================================
		* JSON-LD Schema (always, optional)
		* ============================================== */
		if ( ! empty( $schema_type ) ) {
			$schema_data = array(
				"@context"  => "https://schema.org",
				"@type"     => $schema_type,
				"headline"  => $title,
				"description" => $seo_meta_description ?: '',
				"mainEntityOfPage" => array(
					"@type" => "WebPage",
					"@id"   => $permalink
				),
				"url"        => $permalink,
				"inLanguage" => $locale,
				"publisher"  => array(
					"@type" => "Organization",
					"name"  => $site_name,
					"logo"  => array(
						"@type" => "ImageObject",
						"url"   => get_site_icon_url()
					),
				),
			);
			if ( $featured_img_url ) {
				$schema_data["image"] = array(
					"@type" => "ImageObject",
					"url"   => $featured_img_url,
					"caption" => $featured_alt ?: $title,
				);
			}
			echo '<script type="application/ld+json">' .
				wp_json_encode( $schema_data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ) .
				'</script>' . "\n";
		}

		// ---------------------------
		//  Comment Footer
		// ---------------------------
		if ( $is_social_allowed ) {
			echo "<!-- End Both SEO & Social Meta Tags Fields -->\n\n";
		} else {
			echo "<!-- End Basic SEO Meta Fields -->\n\n";
		}
	}



	/**
	 * AJAX: Check if current post is allowed for SEO Social Meta Tags
	 */
	public static function sc_wordai_check_seo_social_meta_tags() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
		if ( empty( $post_id ) || $post_id <= 0 ) {
			wp_send_json( array(
				'status'  => 'fail',
				'message' => __( 'Invalid post ID received.', 'wordai-pro' ),
				'allowed' => false,
			) );
		}

		$is_allowed = in_array( $post_id, self::get_social_allowed_ids(), true );

		wp_send_json( array(
			'status'  => 'success',
			'allowed' => $is_allowed,
			'message' => $is_allowed
				? sprintf( __( 'Post ID %d is already allowed for SEO social meta tags.', 'wordai-pro' ), $post_id )
				: sprintf( __( 'Post ID %d not yet allowed.', 'wordai-pro' ), $post_id ),
		) );
	}

	/**
	 * AJAX: Add or Remove post ID in SEO Social Meta Tags option list
	 */
	public static function sc_wordai_add_remove_seo_social_meta_tags() {

		// prevents any non-author role triggering via console
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( __( 'Insufficient permissions.', 'wordai-pro' ) );
		}


		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$post_id   = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
		$operation = isset( $_POST['operation'] ) ? sanitize_text_field( $_POST['operation'] ) : '';

		if ( empty( $post_id ) || $post_id <= 0 || ! in_array( $operation, array( 'add', 'remove' ), true ) ) {
			wp_send_json( array(
				'status'  => 'fail',
				'message' => __( 'Invalid post ID or operation.', 'wordai-pro' ),
			) );
		}

		if ( 'add' === $operation ) {
			self::add_social_allowed_id( $post_id );
			wp_send_json( array(
				'status'  => 'success',
				'message' => sprintf( __( 'Post ID %d successfully added to list.', 'wordai-pro' ), $post_id ),
				'post_id' => $post_id,
			) );
		}

		if ( 'remove' === $operation ) {
			self::remove_social_allowed_id( $post_id );
			wp_send_json( array(
				'status'  => 'success',
				'message' => sprintf( __( 'Post ID %d removed successfully from list.', 'wordai-pro' ), $post_id ),
				'post_id' => $post_id,
			) );
		}
	}



		/**
		 * Display SEO Meta Tags Status Notice inside Post Editor
		 * Works with both Classic and Block Editor
		 */
		public static function wordai_seo_admin_notice_in_editor() {

			$screen = get_current_screen();

			// Only run in post/page/product edit screens
			if ( ! $screen || ! in_array( $screen->id, array( 'post', 'page', 'product' ), true ) ) {
				return;
			}

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

			$post_id       = absint( $post->ID );
			$allowed_posts = get_option( 'wordai_add_social_media_meta_tags_post_ids', array() );
			$is_allowed    = in_array( $post_id, $allowed_posts, true );

			$message = $is_allowed
				? '<span class="dashicons dashicons-yes-alt"></span> <strong>' . esc_html__( 'WordAI SEO Meta Tags are active for this post.', 'wordai-pro' ) . '</strong>'
				: '<span class="dashicons dashicons-lightbulb"></span> ' . esc_html__( 'WordAI SEO Meta Tags are currently disabled for this post. You can enable them in the WordAI SEO box below.', 'wordai-pro' );

			$class = $is_allowed ? 'notice-success' : 'notice-info';
			$notice_html = '<div class="notice ' . esc_attr( $class ) . ' is-dismissible wordai-seo-status-notice"><p>' . $message . '</p></div>';

			// Classic editor display (below title)
			if ( use_block_editor_for_post_type( $post->post_type ) === false ) {
				echo $notice_html;
			}
			else {
				// For block editor — inject notice dynamically via JS
				add_action( 'admin_print_footer_scripts', function () use ( $notice_html ) {
					?>
					<script>
						document.addEventListener('DOMContentLoaded', function() {
							if (!document.querySelector('.wordai-seo-status-notice')) {
								const notice = document.createElement('div');
								notice.innerHTML = <?php echo wp_json_encode( $notice_html ); ?>;
								const editorTopBar = document.querySelector('.edit-post-header');
								if (editorTopBar) {
									editorTopBar.insertAdjacentHTML('afterend', notice.innerHTML);
								} else {
									// fallback to main wrapper
									document.body.insertAdjacentHTML('afterbegin', notice.innerHTML);
								}
							}
						});
					</script>
					<?php
				});
			}
		}

	/**
	 * Callback function of hook 'pre_get_document_title'
	 * Add SEO Title with Post if available
	 * @param string $title
	 * @return $title
	 */
	public static function wordai_seo_title_tag_value_add( $title ) {
		if ( ! SftcyWordaiSeoIntegrationManager::should_wordai_output() ) {
			return $title;
		}

		$post_id = get_queried_object_id();

		if ( ! $post_id ) {
			return $title;
		}

		$seo_title = get_post_meta( $post_id, '_wordai_seo_title', true );

		return ! empty( $seo_title ) ? $seo_title : $title;
	}


} // End class
}
