<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-person.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-thing.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-comment.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-place.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-inlanguagespecification.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-organization.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-publication.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-review.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-thumbnailspecification.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-translatorspecification.php';
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-associatedmediaobject.php';

class Vserpb_Article_Schema {

	/**
	 * Generate structured schema for a WordPress article.
	 *
	 * @param int $post_id WordPress Post ID.
	 * @return array|void JSON-LD Schema Markup or void if not a single post.
	 */
	public static function vserpb_generate_schema( $post_id ) {
		if ( ! is_single() ) {
			return;
		}

		$post = get_post( $post_id );

		if ( ! $post || get_post_type( $post_id ) !== 'post' ) {
			return;
		}

			// Fetching essential article details
			$title          = sanitize_text_field( get_the_title( $post_id ) );
			$description    = wp_strip_all_tags( do_shortcode( get_the_excerpt( $post_id ) ) );		
			$author_id      = $post->post_author;
			$author_name    = get_the_author_meta( 'display_name', $author_id );
			$published_date = get_the_date( 'c', $post_id );
			$modified_date  = get_the_modified_date( 'c', $post_id );
			$post_url       = get_permalink( $post_id );
			$author_url  = get_author_posts_url( $author_id );

			// Fetching additional properties
			$is_accessible_for_free = get_post_meta( $post_id, '_is_accessible_for_free', true ) ? true : false;
			$word_count             = str_word_count( wp_strip_all_tags( $post->post_content ) );

				$schema = array(
					'@context'            => 'https://schema.org/',
					'@type'               => 'Article',
					'headline'            => $title,
					'description'         => $description,
					'author'              => array(
						'@type' => 'Person',
						'name'  => $author_name,
					),
					'dateCreated'         => $published_date,
					'datePublished'       => $published_date,
					'dateModified'        => $modified_date,
					'mainEntityOfPage'    => array(
						'@type' => 'WebPage',
						'@id'   => $post_url,
					),
					'isAccessibleForFree' => $is_accessible_for_free,
					'wordCount'           => $word_count,
				);

				// backstory Property Start

					$schema['about'] = ( new Vserpb_Thing( $post_id, 'Article' ) )->vserpb_getSchema( 'Article' );
				// about propetry end

				// abstract Property Start
					$abstract_text = get_the_excerpt($post_id);
					// Assuming 'abstract' is a custom field
				if ( ! empty( $abstract_text ) ) {
					$schema['abstract'] = sanitize_text_field( $abstract_text );
				}
				// abstract Property End

				

		$Personspecfaq = new Vserpb_Person( $author_name, $author_url );
		$Person        = $Personspecfaq->vserpb_getSchema();

				if ( ! empty( $Person ) ) {
					$schema['accountablePerson'] = $Person;
				}

				// copyrightHolder Property Start
					$copyright_name = get_option( 'blogname' );
					$copyright_url  = home_url();
				if ( ! empty( $copyright_name ) && ! empty( $copyright_url ) ) {
					$schema['copyrightHolder'] = ( new Vserpb_Organization( $copyright_name, $copyright_url ) )->vserpb_getSchema();
				}

				// copyrightHolder Property END

				// contentLocation Property start

				$content_location = ( new Vserpb_Place( $post_id, 'Article' ) )->vserpb_getSchema( 'Article' );

				if ( ! empty( $content_location ) && is_array( $content_location ) ) {
					$schema['contentLocation'] = $content_location;
				}

				// contentLocation Property end

				// articleBody Property Start
			$article_body = get_post_field( 'post_content', $post_id );
               $article_body = wp_strip_all_tags( $article_body, true );
               $schema['articleBody'] = $article_body;

				// articleBody Property End

				
				// articleSection Propety Start
					$articleSection           = get_the_excerpt( $post_id );
					$schema['articleSection'] = $articleSection;
				// articleSection Propety End

				
				// wordcount Property Start
					$word_count           = get_post_meta( $post_id, 'word_count', true );
					$schema['word_count'] = $word_count;
				// wordcount Property End

				// genre propetry start
					$tags = wp_get_post_tags( $post_id, array( 'fields' => 'names' ) );
					if ( ! empty( $tags ) ) {
						$schema['genre'] = count( $tags ) === 1 ? $tags[0] : $tags;
					}
				// genre Property End
			

				// keywords Property start
					$article_keywords   = new Vserpb_keyword( $post_id, 'post_tag' );
						$schema['keywords'] = $article_keywords->vserpb_getSchema();
				// keywords Property end

				// maintainer Property start
					$Organization       = new Vserpb_Organization( $copyright_name, $copyright_url );
					$Organizationschema = $Organization->vserpb_getSchema();

					if ( ! empty( $Organizationschema ) ) {
						$schema['maintainer'] = $Organizationschema;
					}
				// maintainer Property end

				// publication Property Start
					$publication_spec = new Vserpb_PublicationSpecification( $post_id );
					$publication      = $publication_spec->vserpb_getSchema();

					if ( ! empty( $publication ) ) {
						$schema['publication'] = $publication;
					}
				// publication property end


				// thumbnail Property start
					$thumbnail_spec = new Vserpb_ThumbnailSpecification( $post_id );
					$thumbnail      = $thumbnail_spec->vserpb_getSchema();

					if ( ! empty( $thumbnail ) ) {
						$schema['thumbnail'] = $thumbnail;
					}
				// thumbnail Property end

				// thumbnailUrl Property start
					$thumbnail_url = get_the_post_thumbnail_url( $post_id, 'full' );

					if ( ! empty( $thumbnail_url ) ) {
						$schema['thumbnailUrl'] = $thumbnail_url;
					}
				// thumbnailUrl Property end

				// text Property start
					  $text_content = wp_strip_all_tags(
                        get_post_field( 'post_content', $post_id ),
                        true
                    );

					if ( ! empty( $text_content ) ) {
						$schema['text'] = $text_content;
					}

					// contributor Property start
					$contributor_spec = new Vserpb_Organization( $copyright_name, $copyright_url );
					$contributor      = $contributor_spec->vserpb_getSchema();
					if ( ! empty( $contributor ) ) {
						$schema['contributor'] = $contributor;
					}
					// contributor Property end

						// identifier Property start
							$post_slug  = $post->post_name;
							$post_title = get_the_title( $post_id );
							$site_name  = get_bloginfo( 'name' );

							// Build the identifier with all supported types
							$identifier_property_value = array(
								'@type'      => 'PropertyValue',
								'propertyID' => 'slug', // You can also use 'post_id', 'url', etc.
								'value'      => $post_slug,
							);

							// Optional: Just in case you want to include all types together
							$schema['identifier'] = array(
								$identifier_property_value, // PropertyValue type
								
							);
							// identifier Property end


						$attachment_ids = get_posts( array(
							'post_parent'    => $post_id,
							'post_type'      => 'attachment',
							'post_status'    => 'inherit',
							'posts_per_page' => -1,
							'fields'         => 'ids',
						) );

					if ( ! empty( $attachment_ids ) ) {

						$associated_media = array();

						foreach ( $attachment_ids as $attachment_id ) {

							$media = new Vserpb_AssociatedMediaObject( $attachment_id );
							$media_schema = $media->vserpb_getSchema();

							if ( ! empty( $media_schema ) ) {
								$associated_media[] = $media_schema;
							}
						}

						if ( ! empty( $associated_media ) ) {
							$schema['associatedMedia'] = $associated_media;
						}
					}



					// image Property start
						$logo   = new Vserpb_ImageObject( $post_id );
						$Logoschema = $logo->vserpb_getSchema();
						if ( ! empty( $Logoschema ) ) {
							$schema['image'] = $Logoschema;
						}

					// image Property end


			// potentialAction Property start
				if ( 'publish' === get_post_status( $post_id ) && ! post_password_required( $post_id ) ) {
				$action = array(
					'@type'  => 'ReadAction',
					'name'   => ! empty( $title )
						? $title 
						: esc_html__( 'Read Article', 'voidek-serp-schema-builder' ),
					'target'      => esc_url( get_permalink( $post_id ) ),
					'description' => $description ,
				);
				// Build agent (Person)
				$Personspec = new Vserpb_Person( $author_name, $author_url );
				$Person     = $Personspec->vserpb_getSchema();
				if ( ! empty( $Person ) ) {
					$action['agent'] = $Person; 
				}
				$schema['potentialAction'] = array( $action );
			}
			// potentialAction Property end


					// name Property start
					if ( ! empty( $post_title ) ) {
							$schema['name'] = $post_title;
					}
	
				
					$creator = array(
						'@type' => 'Person',
						'name'  => $author_name,
						'url'   => $author_url,
					);

						$schema['creator'] = $creator;
					// creator Property end
					// editor Property start
					$Personspec = new Vserpb_Person( $author_name, $author_url );
					$Person     = $Personspec->vserpb_getSchema();

					if ( ! empty( $Person ) ) {
						$schema['editor'] = $Person;
					}


			$schema = apply_filters( 'vserpb_extend_article_schema', $schema, $post_id );

			return $schema;
	}
}
// Upcoming session target
// ->Distinguish the paid and free property and label there respective status
// ->understanding how to implement the freeium plugin model
// ->Implementing the Article schema pending properties further
// ->
