<?php
/**
 * Shortcodes for displaying ingested records.
 *
 * @package DataStream
 */

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

/**
 * Class DataStream_Shortcodes
 */
class DataStream_Shortcodes {

	/**
	 * Register shortcodes.
	 */
	public static function register() {
		add_shortcode( 'datastream_list', array( __CLASS__, 'render_list' ) );
		add_shortcode( 'datastream_field', array( __CLASS__, 'render_field' ) );
	}

	/**
	 * [datastream_list stream="products" limit="10" template="table" fields="name,price"]
	 *
	 * @param array<string, string>|string $atts Shortcode attributes.
	 * @return string
	 */
	public static function render_list( $atts ) {
		$atts = shortcode_atts(
			array(
				'stream'       => '',
				'stream_type'  => '',
				'limit'        => '10',
				'template'     => 'list',
				'fields'       => '',
				'empty'        => __( 'No records found.', 'datastream-api-sync' ),
				'page_size'    => '0',
				'orderby'      => '',
				'order'        => 'desc',
				'searchable'   => '',
				'style'        => '',
				'image_aspect' => '',
				'id'           => '',
			),
			$atts,
			'datastream_list'
		);

		return DataStream_Renderer::render_list(
			array(
				'stream'       => '' !== $atts['stream'] ? $atts['stream'] : $atts['stream_type'],
				'limit'        => absint( $atts['limit'] ),
				'template'     => $atts['template'],
				'fields'       => $atts['fields'],
				'empty'        => $atts['empty'],
				'page_size'    => absint( $atts['page_size'] ),
				'orderby'      => $atts['orderby'],
				'order'        => $atts['order'],
				'searchable'   => in_array( strtolower( (string) $atts['searchable'] ), array( '1', 'true', 'yes' ), true ),
				'style'        => $atts['style'],
				'image_aspect' => $atts['image_aspect'],
				'list_id'      => $atts['id'],
			)
		);
	}

	/**
	 * [datastream_field id="123" field="title" default="—"]
	 *
	 * @param array<string, string>|string $atts Shortcode attributes.
	 * @return string
	 */
	public static function render_field( $atts ) {
		$atts = shortcode_atts(
			array(
				'id'      => '',
				'field'   => '',
				'default' => '',
			),
			$atts,
			'datastream_field'
		);

		if ( '' === $atts['id'] || '' === $atts['field'] ) {
			return '';
		}

		return DataStream_Renderer::render_field( $atts['id'], $atts['field'], $atts['default'] );
	}
}
