<?php
/**
 * AI Visibility - Schema Injection
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\AiVisibility;

/**
 * Handles schema injection via API
 */
class Schema {

	/**
	 * Get schema status for API
	 *
	 * @return array
	 */
	public static function get_status() {
		// Check if any posts have custom schema
		$args = array(
			'post_type'      => array( 'post', 'page' ),
			'post_status'    => 'publish',
			'posts_per_page' => 1,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			'meta_query'     => array(
				array(
					'key'     => '_seovault_schema_json',
					'compare' => 'EXISTS',
				),
			),
		);

		$posts             = get_posts( $args );
		$has_custom_schema = count( $posts ) > 0;

		return array(
			'has_custom_schema' => $has_custom_schema,
			'auto_generation'   => true,
		);
	}

	/**
	 * Preview schema
	 *
	 * @param string $schema_json Schema JSON
	 * @return array
	 */
	public static function preview( $schema_json ) {
		$sanitized = \SEOvaultSEO\Utils\Sanitizer::sanitize_schema_json( $schema_json );

		if ( empty( $sanitized ) ) {
			return array(
				'success' => false,
				'message' => 'Invalid JSON schema',
			);
		}

		$decoded = json_decode( $sanitized, true );

		return array(
			'success'   => true,
			'preview'   => $decoded,
			'formatted' => wp_json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ),
		);
	}

	/**
	 * Inject schema into post
	 *
	 * @param int    $post_id Post ID
	 * @param string $schema_json Schema JSON
	 * @return array
	 */
	public static function inject( $post_id, $schema_json ) {
		$post = get_post( $post_id );

		if ( ! $post ) {
			return array(
				'success' => false,
				'message' => 'Post not found',
			);
		}

		$sanitized = \SEOvaultSEO\Utils\Sanitizer::sanitize_schema_json( $schema_json );

		if ( empty( $sanitized ) ) {
			return array(
				'success' => false,
				'message' => 'Invalid JSON schema',
			);
		}

		// API inject defaults to Add mode; callers needing Replace must confirm separately.
		\SEOvaultSEO\Schema\SchemaCustomJson::save( $post_id, $sanitized, \SEOvaultSEO\Schema\SchemaCustomJson::MODE_ADD, false );

		return array(
			'success' => true,
			'message' => 'Schema injected successfully',
		);
	}

	/**
	 * Detect schema types on a post
	 *
	 * @param int $post_id Post ID
	 * @return array
	 */
	public static function detect_schema_types( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post ) {
			return array(
				'success' => false,
				'message' => 'Post not found',
			);
		}

		$types = array();

		// Check for custom schema
		$custom_schema = \SEOvaultSEO\Core\PostMeta::get_schema_json( $post_id );
		if ( ! empty( $custom_schema ) ) {
			$decoded = json_decode( $custom_schema, true );
			if ( is_array( $decoded ) ) {
				if ( isset( $decoded['@type'] ) ) {
					$types[] = $decoded['@type'];
				}
				if ( isset( $decoded['@graph'] ) && is_array( $decoded['@graph'] ) ) {
					foreach ( $decoded['@graph'] as $item ) {
						if ( isset( $item['@type'] ) ) {
							$types[] = $item['@type'];
						}
					}
				}
			}
		}

		// Auto-detect based on post type
		if ( 'post' === $post->post_type ) {
			$types[] = 'Article';
		} elseif ( 'page' === $post->post_type ) {
			$types[] = 'WebPage';
		}

		return array(
			'success' => true,
			'types'   => array_unique( $types ),
		);
	}
}
