<?php
/**
 * Custom WPBakery param types.
 *
 * Registers the "cafw_layout" param: a visual radio group where each option
 * is a small wireframe thumbnail (an inline SVG supplied by the element), like
 * the skin pickers in modern builders. The selected value is stored in a
 * hidden input that WPBakery reads as usual (.wpb_vc_param_value).
 *
 * @package CraftAddonsForWPBakery
 */

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

/**
 * Class CAFW_Params
 */
class CAFW_Params {

	/**
	 * Register the custom param types with WPBakery.
	 *
	 * Must run inside vc_before_init (or later), once vc_add_shortcode_param
	 * exists. Safe to call multiple times.
	 *
	 * @return void
	 */
	public static function register() {
		if ( ! function_exists( 'vc_add_shortcode_param' ) ) {
			return;
		}
		vc_add_shortcode_param( 'cafw_layout', array( __CLASS__, 'layout_field' ) );
	}

	/**
	 * Render the layout picker form field.
	 *
	 * Expects the param definition to carry an "options" map:
	 * value => array( 'label' => string, 'thumb' => inline SVG markup ).
	 * An optional "resets" list names sibling params (dropdowns) that snap
	 * back to their first option whenever a layout is picked, so the element
	 * always lands in the arrangement the thumbnail shows.
	 *
	 * @param array  $settings Param definition from vc_map().
	 * @param string $value    Current value.
	 * @return string
	 */
	public static function layout_field( $settings, $value ) {
		$options = isset( $settings['options'] ) && is_array( $settings['options'] ) ? $settings['options'] : array();
		$name    = isset( $settings['param_name'] ) ? $settings['param_name'] : '';
		$value   = (string) $value;
		if ( '' === $value && isset( $settings['value'] ) ) {
			$value = (string) $settings['value']; // pre-existing content saved before this param existed.
		}
		$resets = isset( $settings['resets'] ) && is_array( $settings['resets'] ) ? implode( ',', $settings['resets'] ) : '';

		$html = '<div class="cafw-layout-picker" data-resets="' . esc_attr( $resets ) . '">';
		foreach ( $options as $key => $option ) {
			$key      = (string) $key;
			$selected = ( $value === $key ) ? ' is-selected' : '';
			$html    .= sprintf(
				'<button type="button" class="cafw-layout-option%1$s" data-value="%2$s" title="%3$s" aria-pressed="%4$s">%5$s<span class="screen-reader-text">%3$s</span></button>',
				$selected,
				esc_attr( $key ),
				esc_attr( $option['label'] ),
				$value === $key ? 'true' : 'false',
				$option['thumb'] // Inline SVG built by the element; static markup, no user input.
			);
		}
		$html .= sprintf(
			'<input type="hidden" name="%1$s" class="wpb_vc_param_value wpb-textinput %1$s %2$s_field" value="%3$s">',
			esc_attr( $name ),
			esc_attr( isset( $settings['type'] ) ? $settings['type'] : 'cafw_layout' ),
			esc_attr( $value )
		);
		$html .= '</div>';

		return $html;
	}
}
