<?php

namespace TotalThemeCore\Shortcodes;

defined( 'ABSPATH' ) || exit;

final class Shortcode_Cf_Value {

	public function __construct() {
		if ( ! shortcode_exists( 'cf_value' ) ) {
			add_shortcode( 'cf_value', [ self::class, 'output' ] );
		}
	}

	public static function output( $atts, $content = '' ): string {
		$atts = shortcode_atts( [
			'name'     => '',
			'field'    => '',
			'fallback' => '',
		], $atts );
		$field = $atts['name'] ?: $atts['field'];
		if ( ! $field ) {
			return '';
		}
		if ( function_exists( 'vcex_get_meta_value' ) ) {
			$value = vcex_get_meta_value( $field );
		} else {
			$post_id = get_the_ID();
			if ( ! $post_id ) {
				return '';
			}
			$value = get_post_meta( $post_id, $field, true );
		}
		if ( '' === $value ) {
			$value = $atts['fallback'];
		}
		return '' !== $value ? wp_kses_post( $value ) : '';
	}

}
