<?php
namespace SabaiApps\Directories\Component\Entity\DisplayElement;

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Display\Model\Display;

trait WithFieldTrait {

	public function displayElementSettingsForm( Bundle $bundle, array $settings, Display $display, array $parents = array(), $tab = null, $isEdit = false, array $submitValues = array() ) {
		return parent::displayElementSettingsForm( $bundle, $settings, $display, $parents, $tab, $isEdit, $submitValues )
			+ $this->_application->Display_ElementLabelSettingsForm( $settings, $parents, false, 5 )
			+ array(
				'label_as_heading' => array(
					'#title'         => __( 'Show label as heading', 'directories-pro' ),
					'#type'          => 'checkbox',
					'#default_value' => ! empty( $settings['label_as_heading'] ),
					'#horizontal'    => true,
					'#states'        => array(
						'invisible' => array(
							sprintf( 'select[name="%s[label]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 'none' ),
						),
					),
					'#weight'        => 10,
				),
			);
	}

	public function displayElementRender( Bundle $bundle, array $element, $var, ?array $context = null ) {
		if ( ! $rendered = parent::displayElementRender( $bundle, $element, $var, $context ) ) {
			return;
		}

		$settings   = $element['settings'];
		$label_type = $settings['label'];
		$label      = $this->_application->Display_Render_elementLabel( $element['settings'], $this->displayElementStringId( $bundle->name, $element['display'], $element['_element_id'], 'label' ) );
		if ( ! is_array( $rendered ) ) {
			$rendered = array( 'html' => $rendered );
		}
		if ( ! strlen( $label ) ) {
			if ( isset( $rendered['raw'] ) ) {
				return $rendered;
			}
			$rendered['html'] = '<div class="drts-entity-field-value">' . $rendered['html'] . '</div>';
			return $rendered;
		}

		if ( empty( $settings['label_as_heading'] ) ) {
			$heading_class = '';
		} else {
			$heading_class = ' drts-display-element-header';
			$label         = '<span>' . $label . '</span>';
		}
		$label = '<div class="drts-entity-field-label drts-entity-field-label-type-' . $label_type . $heading_class . '">' . $label . '</div>';

		if ( isset( $rendered['raw'] ) ) {
			$rendered['html'] = $label . $rendered['raw'];
			unset( $rendered['raw'] );
		} else {
			$rendered['html'] = $label . '<div class="drts-entity-field-value">' . $rendered['html'] . '</div>';
		}

		return $rendered;
	}

	public function displayElementTitle( Bundle $bundle, array $element ) {
		return $this->_application->Display_Render_elementLabel( $element['settings'] );
	}
}
