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

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field;

class TermParentFieldType extends Field\Type\AbstractType implements Field\Type\IQueryable
{
    protected function _fieldTypeInfo()
    {
        return array(
            'label' => __('Parent Term', 'directories'),
            'entity_types' => array('term'),
            'default_widget' => 'entity_term_parent',
            'creatable' => false,
            'icon' => 'fas fa-sitemap',
        );
    }
    
    public function fieldQueryableInfo(Field\IField $field)
    {
        return array(
            'example' => '',
            'tip' => __('Enter a parent ID or "_current_" for current term if any (fallbacks to 0).', 'directories'),
        );
    }
    
    public function fieldQueryableQuery(Field\Query $query, $fieldName, $paramStr, Entity\Model\Bundle $bundle = null)
    {
        $parent_id = trim($paramStr);
        if (!strlen($parent_id)) return;

        if ($parent_id === '_current_') {
            if (isset($GLOBALS['drts_entity'])
                && $GLOBALS['drts_entity']->isTaxonomyTerm()
                && (!isset($bundle) || $bundle->name === $GLOBALS['drts_entity']->getBundleName())
            ) {
                $parent_id = $GLOBALS['drts_entity']->getId();
            } else {
                $parent_id = 0;
            }
        } else {
            if (!is_numeric($parent_id)) {
                $parent_id = 0;
            }
        }

        $query->fieldIs($fieldName, $parent_id);
    }
}