<?php

namespace AAWP;

/**
 * The Product Schema Class.
 *
 * @since 4.2.0
 */
class ProductSchema {

	/**
	 * Initialize
	 *
	 * @since 4.2.0
	 */
	public function init() {

		$product_schema = ! empty( aawp_get_option( 'product_schema', 'output' ) );

        if ( $product_schema ) {
            add_action( 'aawp_after_template', array( $this, 'build' ) );
        }

		add_action( 'aawp_settings_output_register', array( $this, 'settings' ) );
	}

	/**
	 * Add Settings for Product Schema.
	 *
	 * @since 4.2.0
	 */
	public function settings() {

		/**
		 * Product Schema Section.
		 *
		 * @since 4.2.0.
		 */
		add_settings_field(
			'aawp_product_schema',
			esc_html__( 'Product Schema', 'aawp' ),
			array( $this, 'settings_product_schema_render' ),
			'aawp_output',
			'aawp_output_section',
			array( 'label_for' => 'aawp_product_schema' )
		);
	}

	/**
	 * Render Product Schema Markup Section.
	 *
	 * @since 4.2.0
	 */
	public function settings_product_schema_render() {

		$product_schema = ! empty( aawp_get_option( 'product_schema', 'output' ) ) ;

		?>
			<p>
				<input type="checkbox" id="aawp_product_schema" name="aawp_output[product_schema]" value="1" <?php echo $product_schema === true ? 'checked' : ''; ?> >
				<label for="aawp_product_schema"><?php esc_html_e( 'Enable Product Schema Markup', 'aawp' ); ?></label>
			</p>
			<p>
				<small><?php esc_html_e( 'Automatically generate and include structured data (schema markup) for products.', 'aawp' ); ?></small>
			</p>
		<?php
	}

	/**
	 * Build the product schema.
	 *
	 * @param array $args The Product Arguments.
	 *
	 * @since 4.2.0
	 */
	public function build( $args ) { //phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		if ( empty( $args['items'] ) ) { // Check for comparison table because items are built differently.

			global $aawp_table;

			if ( ! empty( $aawp_table ) ) {
				$products = $aawp_table['items'];
			}
		}

		if ( ! isset( $products ) ) {
			$products = $args['items'];
		}

		if ( empty( $products ) ) {
			return;
		}

		$graph = [];

		foreach( $products as $product ) {

			$product = new \AAWP_Product( $product );

			$schema = array(
				'@type'           => 'Product',
				'name'            => $product->get_title(),
				'image'           => $product->get_image(),
				'description'     => $product->get_description(),
				'sku'             => $product->get_asin(),
				'brand'           => array(
					'@type' => 'Brand',
					'name'  => ! empty( $product->get_attributes()['basic_info']['brand'] ) ? $product->get_attributes()['basic_info']['brand'] : '',
				),
				'offers'          => array(
					'@type'         => 'Offer',
					'url'           => aawp_replace_url_tracking_id_placeholder( $product->get_url(), '', false ),
					'priceCurrency' => $product->get_currency(),
					'price'         => $product->get_price(),
					'availability'  => ! empty( $product->get_availability() ) ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
					'itemCondition' => 'https://schema.org/NewCondition',
					'seller'        => array(
						'@type' => 'Organization',
						'name'  => ! empty( $product->get_attributes()['basic_info']['manufacturer'] ) ? $product->get_attributes()['basic_info']['manufacturer'] : '',
					),
				),
				'aggregateRating' => ! empty( $product->get_rating() ) && ! empty( $product->get_reviews() ) ? array(
					'@type'       => 'AggregateRating',
					'ratingValue' => $product->get_rating(),
					'reviewCount' => $product->get_reviews(),
				) : null,
			);

			// Filter out null or empty values from the schema.
			$schema = array_filter(
				$schema,
				function ( $value ) {
					return ! empty( $value ) || is_array( $value );
				}
			);

			$graph[] = $schema;
		}

		$aawp_schema = [
			'@context' => "https://schema.org/",
			'@graph'   => $graph
		];

		echo '<script type="application/ld+json">' . wp_json_encode( $aawp_schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ) . '</script>';
	}
}
