<?php // phpcs:ignore

namespace SEOPress\Tags\Custom;

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

use SEOPress\Models\AbstractCustomTagValue;
use SEOPress\Models\GetTagValue;

/**
 * Custom Post Meta
 */
class CustomPostMeta extends AbstractCustomTagValue implements GetTagValue {
	const CUSTOM_FORMAT = '_cf_';
	const NAME          = '_cf_your_custom_field_name';

	/**
	 * Get description
	 *
	 * @return string
	 */
	public static function getDescription() {
		return __( 'Custom fields (replace your_custom_field_name by the name of your custom field)', 'wp-seopress' );
	}

	/**
	 * Get value
	 *
	 * @param array $args context, tag.
	 * @return string
	 */
	public function getValue( $args = null ) {
		$context = isset( $args[0] ) ? $args[0] : null;
		$tag     = isset( $args[1] ) ? $args[1] : null;
		$value   = '';
		if ( null === $tag || ! $context ) {
			return $value;
		}

		// Support both post and term contexts
		if ( ! $context['post'] && ! $context['term_id'] ) {
			return $value;
		}
		$regex = $this->buildRegex( self::CUSTOM_FORMAT );

		preg_match( $regex, $tag, $matches );

		if ( empty( $matches ) || ! array_key_exists( 'field', $matches ) ) {
			return $value;
		}

		$field = $matches['field'];

		$length = 50;
		$length = apply_filters( 'seopress_excerpt_length', $length );

		// Get meta value based on context type
		if ( $context['post'] ) {
			$raw_value = get_post_meta( $context['post']->ID, $field, true );
		} elseif ( $context['term_id'] ) {
			$raw_value = get_term_meta( $context['term_id'], $field, true );
		} else {
			$raw_value = '';
		}

		$value = wp_trim_words( esc_attr( stripslashes_deep( wp_filter_nohtml_kses( wp_strip_all_tags( strip_shortcodes( $raw_value, true ) ) ) ) ), $length );

		return apply_filters( 'seopress_get_tag_' . $tag . '_value', $value, $context );
	}
}
