<?php
namespace SabaiApps\Directories\Component\Booking\FieldWidget;

use SabaiApps\Directories\Component\Field\Widget\AbstractWidget;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class StatusFieldWidget extends AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'       => __( 'Booking Status', 'directories-pro' ),
			'field_types' => array( $this->_name ),
		);
	}

	public function fieldWidgetForm( IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( isset( $entity )
			&& ! $entity->isPublished()
		) {
			// Need to render hidden field for IConditionable to work properly
			return array(
				'#type'   => 'item',
				'#markup' => $this->_getLabel( __( 'Pending', 'directories-pro' ), 'warning' )
					. '<input type="hidden" value="" name="' . $this->_application->Form_Form_fieldName( $parents ) . '" />',
			);
		}

		if ( ! $this->_application->HasPermission( 'entity_delete_others_' . $field->Bundle->name ) ) {
			return;
		}

		$statuses = $this->_application->Booking_Util_statuses();
		if ( ! isset( $value ) || ! isset( $statuses[ $value ] ) ) {
			$value = 'pending';
		}

		if ( empty( $statuses[ $value ]['updatable'] ) ) {
			$markup = $this->_application->Booking_Util_statusHtmlLabel( $statuses[ $value ]['label'], $statuses[ $value ]['color'] );
			// Need to render hidden field for IConditionable to work properly
			$markup .= '<input type="hidden" value="' . $value . '" name="' . $this->_application->Form_Form_fieldName( $parents ) . '" />';
			return array(
				'#type'   => 'item',
				'#markup' => $markup,
			);
		}

		$options = $options_disabled = array();
		foreach ( $statuses as $status => $status_info ) {
			$options[ $status ] = $status_info['label'];
			if ( $status === $value ) {
				continue;
			}

			if ( ! isset( $statuses[ $value ]['updatable']['admin'] )
				|| ! in_array( $status, $statuses[ $value ]['updatable']['admin'], true )
			) {
				$options_disabled[] = $status;
			}
		}

		return array(
			'#type'             => 'select',
			'#options'          => $options,
			'#options_disabled' => $options_disabled,
			'#value'            => $value,
		);
	}

	protected function _getHtmlLabel( $label, $color ) {
		return sprintf(
			'<span class="%1$sbadge %1$sbg-%2$s" style="font-size:16px;">%3$s</span>',
			DRTS_BS_PREFIX,
			$color,
			$this->_application->H( $label )
		);
	}
}
