<?php
/**
 * Share meta tag injector.
 *
 * @package Ugcify\Frontend
 */

namespace Ugcify\Frontend;

use Ugcify\Database\ReviewRepository;

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

/**
 * Class ShareMetaInjector
 */
class ShareMetaInjector {
	/**
	 * Repository.
	 *
	 * @var ReviewRepository
	 */
	private $review_repository;

	/**
	 * Constructor.
	 *
	 * @param ReviewRepository|null $review_repository Repository.
	 */
	public function __construct( $review_repository = null ) {
		$this->review_repository = $review_repository instanceof ReviewRepository ? $review_repository : new ReviewRepository();
	}

	/**
	 * Print OG meta tags for share landing.
	 *
	 * @return void
	 */
	public function inject() {
		if ( empty( $_GET['ugc_share'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only URL param.
			return;
		}

		$token = sanitize_key( wp_unslash( (string) $_GET['ugc_share'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( '' === $token ) {
			return;
		}

		$meta = $this->review_repository->find_by_share_token( $token );
		if ( ! is_array( $meta ) ) {
			return;
		}

		$review_id = absint( $meta['review_id'] ?? 0 );
		$review    = $this->review_repository->find( $review_id );
		if ( ! $review ) {
			return;
		}

		$review_data = $review->to_array();
		$product_id  = absint( $review_data['product_id'] ?? 0 );
		if ( $product_id < 1 ) {
			return;
		}

		$title       = get_the_title( $product_id );
		$permalink   = get_permalink( $product_id );
		$description = wp_strip_all_tags( (string) ( $review_data['content'] ?? '' ) );
		$description = wp_trim_words( $description, 24, '...' );
		$image       = get_the_post_thumbnail_url( $product_id, 'full' );

		if ( ! $permalink ) {
			return;
		}

		echo "\n";
		echo '<meta property="og:type" content="product" />' . "\n";
		echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
		echo '<meta property="og:description" content="' . esc_attr( $description ) . '" />' . "\n";
		echo '<meta property="og:url" content="' . esc_url( $permalink ) . '" />' . "\n";
		echo '<meta name="twitter:card" content="summary_large_image" />' . "\n";
		echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '" />' . "\n";
		echo '<meta name="twitter:description" content="' . esc_attr( $description ) . '" />' . "\n";
		if ( $image ) {
			echo '<meta property="og:image" content="' . esc_url( $image ) . '" />' . "\n";
			echo '<meta name="twitter:image" content="' . esc_url( $image ) . '" />' . "\n";
		}
	}
}
