<?php

namespace EasyContentManager\Shortcode;

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

class EcmFields {


	public function __construct() {
		add_shortcode( 'ecm_field', [ $this, 'render_ecm_field' ] );
	}

	public function render_ecm_field( $atts ) {
		$atts = shortcode_atts([
			'key' => '',
			'post_id' => '',
			'format' => true,
			'label' => false,
		], $atts, 'ecm_field');

		if ( empty( $atts['key'] ) ) {
			return '';
		}

		$post_id = $atts['post_id'] ?? get_the_ID();
		$value = ecm_get_field( $atts['key'], $post_id, (bool) $atts['format'] );
		if ( empty( $value ) ) {
			return '';
		}

		$field_obj = ecm_get_field_object( $atts['key'], $post_id );
		$field_type = $field_obj['field_type'] ?? 'text';

		$template = locate_template( "ecm/{$field_type}-field.php" );
		if ( ! $template ) {
			$template = EASY_CONTENT_MANAGER_ROOT_DIR_PATH . "templates/{$field_type}-field.php";
		}

		$template = apply_filters( 'ecm_shortcode_field_template_path', $template, $field_type, $field_obj, $post_id );

		ob_start();
		if ( file_exists( $template ) ) {
			$field       = $field_obj;
			$value       = $field['value'];
			$with_label  = filter_var( $atts['label'], FILTER_VALIDATE_BOOLEAN );
			include $template;
		} else {
			echo esc_html( is_array( $value ) ? implode( ', ', $value ) : $value );
		}
		return ob_get_clean();
	}
}
