<?php
/**
 * Options Page Builder — shortcode integration.
 *
 * Usage: [wpps_opb page="my-page" field="field_id" format="display" default=""]
 * Alias: [wp_powersuite_opb page="my-page" field="field_id"]
 *
 * @package OptionsPageBuilder
 */

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

/**
 * @param array<string, string>|string $atts
 */
function wpps_opb_shortcode_callback( $atts ): string {
	$atts = shortcode_atts(
		[
			'page'    => '',
			'field'   => '',
			'format'  => 'display',
			'default' => '',
		],
		is_array( $atts ) ? $atts : [],
		'wpps_opb'
	);

	$page_slug = sanitize_key( (string) $atts['page'] );
	$field_id  = sanitize_key( (string) $atts['field'] );
	if ( $page_slug === '' || $field_id === '' ) {
		return '';
	}

	if ( ! wpps_opb_page_exists( $page_slug ) ) {
		return '';
	}

	return wpps_opb_render_field_output(
		$page_slug,
		$field_id,
		[
			'format'  => sanitize_key( (string) $atts['format'] ),
			'default' => (string) $atts['default'],
		]
	);
}

add_action( 'init', static function (): void {
	add_shortcode( 'wpps_opb', 'wpps_opb_shortcode_callback' );
	add_shortcode( 'wp_powersuite_opb', 'wpps_opb_shortcode_callback' );
}, 20 );
