<?php
 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-person.php';
class Vserpb_Review {
	private $product_id;
	private $reviews     = array();
	private $bestRating  = 5;
	private $worstRating = 1;
	private $author;

	// New properties for aggregate info
	private $publisher;
	private $review_aspect;
	private $positive_notes;
	private $negative_notes;
	
	/**
	 * __construct
	 *
	 * @param  mixed $product_id
	 * @return void
	 */
	public function __construct( $product_id ) {
		$this->product_id = $product_id;
	    $this->publisher = get_bloginfo( 'name' );
		$this->vserpb_setReviews();       // Load reviews
	}
	
	/**
	 * vserpb_set_aggregate_info
	 *
	 * @return void
	 */

	
	/**
	 * vserpb_setReviews
	 *
	 * @return void
	 */
	private function vserpb_setReviews() {
		

		$args = array(
			'post_id' => $this->product_id,
			'status'  => 'approve',
			'type'    => 'review',
			'orderby' => 'meta_value_num',
			'order'   => 'DESC',
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
			'meta_query' => array(
				array(
					'key'     => 'rating',
					'compare' => 'EXISTS',
				),
			),
		);
		$comments = get_comments( $args );


		if ( ! empty( $comments ) ) {
			foreach ( $comments as $comment ) {
				$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
				$review_url = get_comment_link( $comment->comment_ID );
				if ( empty( $review_url ) ) {
					$review_url = get_permalink( $product_id ) . '#reviews';
				}
				$review_schema = array(
					'@type'         => 'Review',
					'reviewRating'  => array(
						'@type'       => 'Rating',
						'ratingValue' => $rating ?: 0,
						'bestRating'  => $this->bestRating,
						'worstRating' => $this->worstRating,
					),
					'author'        => ( new Vserpb_Person( $comment->comment_author ) )->vserpb_getSchema(),
					'reviewBody'    => $comment->comment_content,
					'datePublished' => $comment->comment_date,
					 'url'           => esc_url( $review_url ),
					
				);

				// Add additional fields if available
				if ( ! empty( $this->publisher ) ) {
					$review_schema['publisher'] = array(
						'@type' => 'Organization',
						'name'  => $this->publisher,
					);
				}
				$this->reviews[] = $review_schema;
			}
		}
	}
	
	/**
	 * vserpb_getSchema
	 *
	 * @return void
	 */
	public function vserpb_getSchema() {
		return $this->reviews;
	}
	
	/**
	 * vserpb_getSchemaByProperties
	 *
	 * @param  mixed $properties
	 * @return void
	 */
	public function vserpb_getSchemaByProperties( ...$properties ) {
		$schema = array(
			'@type' => 'Review',
		);

		foreach ( $properties as $property ) {
			if ( ! is_string( $property ) ) {
				continue;
			}

			switch ( $property ) {
				case 'ratingValue':
					$schema['ratingValue'] = $this->average_rating;
					break;
				case 'reviewCount':
					$schema['reviewCount'] = $this->review_count ?? null;
					break;
			}
		}

		return $schema;
	}
}
