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

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Field\Query;
use SabaiApps\Directories\Component\Field\Type\AbstractType;
use SabaiApps\Directories\Component\Field\Type\IQueryable;

class UserRoleFieldType extends AbstractType implements IQueryable {

	protected function _fieldTypeInfo() {
		return array(
			'label'                          => __( 'User Role', 'directories-pro' ),
			'entity_types'                   => array( 'user' ),
			'creatable'                      => false,
			'display_element_can_admin_only' => false,
		);
	}

	public function fieldTypeOnSaveValues( IField $field, array $values, ?array $currentValues = null, array &$extraArgs = array() ) {
		if ( empty( $values[0] )
			|| ( ! $roles_allowed = array_diff_key( $this->_application->getPlatform()->getRoles(), $this->_application->getPlatform()->getAdministratorRoles() ) )
			|| ! isset( $roles_allowed[ $values[0] ] )
		) {
			return;
		}

		return array( $values[0] );
	}

	public function fieldQueryableInfo( IField $field, $inAdmin = false ) {
		return array(
			'example' => 'administrator,editor,subscriber',
			'tip'     => __( 'Enter role names separated with commas.', 'directories-pro' ),
		);
	}

	public function fieldQueryableQuery( Query $query, $fieldName, $paramStr, Bundle $bundle ) {
		if ( ! $roles = $this->_queryableParams( $paramStr ) ) {
			return;
		}

		$query->addCriteria( $this->_application->WordPressUser_InRolesCriteria( $roles ) );
	}
}
