<?php
/**
 * Yoast SEO integration: inject UGC review content into content analysis (product edit screen).
 *
 * So that review text contributes to focus keyphrase and word count in the editor.
 *
 * @package Ugcify\SEO
 */

namespace Ugcify\SEO;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class YoastIntegration
 */
class YoastIntegration {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_yoast_ugcify_script' ), 20 );
	}

	/**
	 * Enqueue the Yoast content-modification script on product edit screen when Yoast is active.
	 */
	public function enqueue_yoast_ugcify_script( $hook ) {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || $screen->post_type !== 'product' || $screen->base !== 'post' ) {
			return;
		}

		if ( ! defined( 'WPSEO_VERSION' ) && ! class_exists( 'WPSEO_Options', false ) ) {
			return;
		}

		$product_id = isset( $_GET['post'] ) ? (int) $_GET['post'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading post ID from standard admin screen URL.
		if ( $product_id < 1 ) {
			return;
		}

		$reviews_text = $this->get_reviews_plain_text_for_product( $product_id );

		$script_path = 'src/frontend/js/yoast-ugcify-content.js';
		$script_url  = UGCIFY_URL . $script_path;
		$script_ver  = file_exists( UGCIFY_PATH . $script_path ) ? filemtime( UGCIFY_PATH . $script_path ) : UGCIFY_VERSION;

		wp_enqueue_script(
			'ugcify-yoast-integration',
			$script_url,
			array( 'jquery' ),
			$script_ver,
			true
		);

		wp_localize_script(
			'ugcify-yoast-integration',
			'ugcifyForYoast',
			array(
				'content' => $reviews_text,
			)
		);
	}

	/**
	 * Get approved reviews for a product as a single plain-text string for Yoast analysis.
	 *
	 * @param int $product_id Product ID.
	 * @return string
	 */
	private function get_reviews_plain_text_for_product( $product_id ) {
		$repository = new \Ugcify\Database\ReviewRepository();
		$result = $repository->get_paginated( array(
			'product_id' => $product_id,
			'status'     => 'approved',
			'per_page'   => 100,
			'page'       => 1,
			'order_by'   => 'id',
			'order'      => 'DESC',
		) );

		if ( empty( $result['items'] ) ) {
			return '';
		}

		$parts = array();
		foreach ( $result['items'] as $review ) {
			$content = wp_strip_all_tags( $review->content );
			if ( $content !== '' ) {
				$parts[] = $content;
			}
		}

		return implode( "\n\n", $parts );
	}
}
