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

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

trait QueryableIdTrait {

	public function fieldQueryableInfo( IField $field, $inAdmin = false ) {
		if ( $inAdmin ) {
			$tip     = __( 'Enter IDs separated with commas. Prefix with "-" to exclude, e.g. -2,-10,7.', 'directories-pro' );
			$example = '1,5,-7,12';
		} else {
			$tip     = __( 'Enter IDs or "_current_" (for current post/term if any) separated with commas. Prefix with "-" to exclude, e.g. -2,-10,-_current_.', 'directories-pro' );
			$example = '1,5,-7,12,_current_';
		}
		return array(
			'example' => $example,
			'tip'     => $tip,
		);
	}

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

		$include = $exclude = array();
		foreach ( $ids as $id ) {
			if ( ! is_numeric( $id ) ) {
				if ( in_array( $id, array( '_current_', '-_current_' ) )
					&& ( $entity_id = $this->_getCurrentEntityId() )
				) {
					if ( $id === '-_current_' ) {
						$exclude[] = $entity_id;
					} else {
						$include[] = $entity_id;
					}
				}
			} elseif ( $id < 0 ) {
					$exclude[] = -1 * $id;
			} else {
				$include[] = $id;
			}
		}
		if ( ! empty( $include ) ) {
			$query->fieldIsIn( $fieldName, $include );
		}
		if ( ! empty( $exclude ) ) {
			$query->fieldIsNotIn( $fieldName, $exclude );
		}
	}
}
