<?php
/**
 * ClaimReview schema + editor meta for fact-check / debunk articles.
 *
 * @package Newsroom_AI_Assistant
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'newsai_claim_review_is_enabled' ) ) {
	/**
	 * @param int $post_id Post ID.
	 */
	function newsai_claim_review_is_enabled( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 ) {
			return false;
		}
		return get_post_meta( $post_id, '_newsai_claim_review_enabled', true ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_save_claim_review_meta' ) ) {
	/**
	 * Persist ClaimReview fields from the editor sidebar.
	 *
	 * @param int $post_id Post ID.
	 */
	function newsai_save_claim_review_meta( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 || defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
		if ( ! isset( $_POST['newsai_sidebar_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newsai_sidebar_nonce'] ) ), 'newsai_sidebar_save' ) ) {
			return;
		}

		$enabled = isset( $_POST['newsai_claim_review_enabled'] ) && sanitize_text_field( wp_unslash( (string) $_POST['newsai_claim_review_enabled'] ) ) === 'yes';
		if ( ! $enabled ) {
			delete_post_meta( $post_id, '_newsai_claim_review_enabled' );
			delete_post_meta( $post_id, '_newsai_claim_text' );
			delete_post_meta( $post_id, '_newsai_claim_rating' );
			delete_post_meta( $post_id, '_newsai_claim_source_url' );
			return;
		}

		update_post_meta( $post_id, '_newsai_claim_review_enabled', 'yes' );

		$claim = isset( $_POST['newsai_claim_text'] ) ? sanitize_textarea_field( wp_unslash( (string) $_POST['newsai_claim_text'] ) ) : '';
		if ( $claim !== '' ) {
			update_post_meta( $post_id, '_newsai_claim_text', $claim );
		} else {
			delete_post_meta( $post_id, '_newsai_claim_text' );
		}

		$allowed_ratings = [ 'False', 'True', 'Misleading' ];
		$rating          = isset( $_POST['newsai_claim_rating'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['newsai_claim_rating'] ) ) : 'False';
		if ( ! in_array( $rating, $allowed_ratings, true ) ) {
			$rating = 'False';
		}
		update_post_meta( $post_id, '_newsai_claim_rating', $rating );

		$source = isset( $_POST['newsai_claim_source_url'] ) ? esc_url_raw( wp_unslash( (string) $_POST['newsai_claim_source_url'] ) ) : '';
		if ( $source !== '' ) {
			update_post_meta( $post_id, '_newsai_claim_source_url', $source );
		} else {
			delete_post_meta( $post_id, '_newsai_claim_source_url' );
		}
	}
}
add_action( 'save_post', 'newsai_save_claim_review_meta', 15 );

if ( ! function_exists( 'nros_schema_build_claim_review_node' ) ) {
	/**
	 * Build ClaimReview node linked to the article graph.
	 *
	 * @param int    $post_id      Post ID.
	 * @param string $article_id   Article @id URL fragment.
	 * @param string $publisher_id Organization @id.
	 * @return array<string,mixed>|null
	 */
	function nros_schema_build_claim_review_node( $post_id, $article_id, $publisher_id ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 || ! newsai_claim_review_is_enabled( $post_id ) ) {
			return null;
		}

		$claim_text = trim( (string) get_post_meta( $post_id, '_newsai_claim_text', true ) );
		if ( $claim_text === '' ) {
			return null;
		}

		$rating_label = (string) get_post_meta( $post_id, '_newsai_claim_rating', true );
		if ( $rating_label === '' ) {
			$rating_label = 'False';
		}

		$permalink = trailingslashit( get_permalink( $post_id ) );
		$node      = [
			'@type'            => 'ClaimReview',
			'@id'              => $permalink . '#claimreview',
			'url'              => $permalink,
			'datePublished'    => function_exists( 'nros_schema_post_datetime_iso' ) ? nros_schema_post_datetime_iso( $post_id, 'date' ) : get_the_date( 'c', $post_id ),
			'claimReviewed'    => [
				'@type' => 'Claim',
				'text'  => $claim_text,
			],
			'reviewRating'     => [
				'@type'         => 'Rating',
				'alternateName' => $rating_label,
			],
			'itemReviewed'     => [
				'@id' => $article_id,
			],
			'author'           => [
				'@id' => $publisher_id,
			],
		];

		$source = (string) get_post_meta( $post_id, '_newsai_claim_source_url', true );
		if ( $source !== '' ) {
			$node['appearance'] = [
				'@type' => 'CreativeWork',
				'url'   => esc_url_raw( $source ),
			];
		}

		return (array) apply_filters( 'nros_schema_claim_review_node', $node, $post_id );
	}
}
