<?php

namespace common\modules\product\helpers;


use common\modules\rubrication\models\TaxGroup;
use yii\base\Object;
use yii\helpers\ArrayHelper;

class FilterHelper extends Object {

    public static $optionsList;

    public static function optionsTemplate(){
        if(empty(static::$optionsList)){
            return static::$optionsList = ArrayHelper::getColumn(TaxGroup::find()->where(['is_filter' => 'TRUE'])->all(),'alias');
        }
        else
        {
            return static::$optionsList;
        }

    }

    /*
     * Return custom filter-option link
     * @var array $filter
     * @var array $options
     * @return array
     */
    public static function getFilterForOption($filter, $key, $value, $remove = false) {

        $optionsTemplate = self::optionsTemplate();
        array_unshift($optionsTemplate, "special", "brands");

        $result = $filter;

        if (is_array($value)) {
            foreach($value as $value_key => $value_items) {
                if (!is_array($value_items)) {
                    $value_items = [$value_items];
                }
                foreach($value_items as $value_item) {
                    if ($remove && isset($result[$key]) && ($i = array_search($value_item, $result[$key][$value_key])) !== FALSE) {
                        unset($result[$key][$value_key][$i]);
                        if (empty($result[$key][$value_key])) {
                            unset($result[$key][$value_key]);
                        }
                    } else {
                        if (!isset($result[$key][$value_key]) || array_search($value_item, $result[$key][$value_key]) === FALSE) {
                            $result[$key][$value_key][] = $value_item;
                        }
                    }
                }
            }
        } else {
            if ($remove && isset($result[$key]) && ($i = array_search($value, $result[$key])) !== FALSE) {
                unset($result[$key][$i]);
                if (empty($result[$key])) {
                    unset($result[$key]);
                }
            } else {
                if (!isset($result[$key]) || array_search($value, $result[$key]) === FALSE) {
                    $result[$key][] = $value;
                }
            }
        }


        $filterView = [];

        foreach($optionsTemplate as $optionKey){
            if(isset($result[$optionKey])){
                $filterView[$optionKey] = $result[$optionKey];
            }


        }

        return $filterView;
    }



}