<?php
/**
 * Custom Fields — shortcode integration.
 *
 * Usage: [wpps_cf group="book_details" field="subtitle" post_id="" format="display" default=""]
 * Alias: [wp_powersuite_cf group="book_details" field="subtitle"]
 * Meta:  [wpps_cf meta="book_details_subtitle" post_id="123"]
 *
 * @package CustomFields
 */

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

/**
 * @param array<string, string>|string $atts
 */
function wpps_cf_shortcode_callback( $atts ): string {
	$atts = shortcode_atts(
		[
			'group'   => '',
			'field'   => '',
			'meta'    => '',
			'post_id' => '',
			'format'  => 'display',
			'default' => '',
		],
		is_array( $atts ) ? $atts : [],
		'wpps_cf'
	);

	$post_id = $atts['post_id'] !== '' ? absint( $atts['post_id'] ) : null;
	$args    = [
		'format'  => sanitize_key( (string) $atts['format'] ),
		'default' => (string) $atts['default'],
	];

	$meta = sanitize_key( (string) $atts['meta'] );
	if ( $meta !== '' ) {
		return \CustomFields\FieldOutput::renderByMetaKey( $meta, $post_id, $args );
	}

	$group_key  = sanitize_key( (string) $atts['group'] );
	$field_name = sanitize_key( (string) $atts['field'] );
	if ( $group_key === '' || $field_name === '' ) {
		return '';
	}

	return \CustomFields\FieldOutput::render( $group_key, $field_name, $post_id, $args );
}

add_action(
	'init',
	static function (): void {
		add_shortcode( 'wpps_cf', 'wpps_cf_shortcode_callback' );
		add_shortcode( 'wp_powersuite_cf', 'wpps_cf_shortcode_callback' );
	},
	20
);
