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

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

class UserRoleFieldWidget extends AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'            => __( 'Select list', 'directories-pro' ),
			'field_types'      => array( $this->_name ),
			'accept_multiple'  => false,
			'default_settings' => array(
				'roles' => null,
			),
		);
	}

	public function fieldWidgetSettingsForm( $fieldType, Entity\Model\Bundle $bundle, array $settings, array $parents = array(), array $rootParents = array() ) {
		return array(
			'roles' => array(
				'#title'            => __( 'Select user roles', 'directories-pro' ),
				'#type'             => 'checkboxes',
				'#options'          => $this->_application->getPlatform()->getRoles(),
				'#options_disabled' => array_keys( $this->_application->getPlatform()->getAdministratorRoles() ),
				'#default_value'    => isset( $settings['roles'] ) ? $settings['roles'] : array( get_option( 'default_role' ) ),
			),
		);
	}

	public function fieldWidgetForm( IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( isset( $entity )
			|| empty( $settings['roles'] )
			|| ( ! $roles_allowed = array_diff_key( $this->_application->getPlatform()->getRoles(), $this->_application->getPlatform()->getAdministratorRoles() ) )
			|| ( ! $roles = array_intersect_key( $roles_allowed, array_flip( $settings['roles'] ) ) )
		) {
			return;
		}

		return array(
			'#type'          => 'select',
			'#options'       => array( '' => __( '— Select —', 'directories-pro' ) ) + $roles,
			'#default_value' => $value,
			'#empty_value'   => '',
		);
	}
}
