<?php

namespace console\controllers;

use \common\models\FilterCache;
use common\modules\product\helpers\FilterHelper;
use common\modules\product\helpers\ProductHelper;
use common\modules\product\models\Category;
use common\modules\product\models\Product;
use common\modules\product\models\ProductVariant;
use common\modules\rubrication\models\TaxGroup;
use common\modules\rubrication\models\TaxOption;
use Yii;
use yii\console\Controller;
use yii\db\ActiveQuery;

class FilterController extends Controller
{

    public $count = 1;
    public $begin_time;
    const DEPTH = 5;




    public function actionIndex()
    {
        $categories = Category::find()->all();

        foreach($categories as $category){
            /**
             *@var TaxGroup $taxGroup
             *@var Category $category
             *@var TaxOption $option
             */

            $taxOptions = $category->filterQuery->all();
            $brands = $category->brands;
            foreach($brands as $brand){
                $taxOptions[] =  [
                    'group_alias' => 'brands',
                    'option_alias' => $brand->brand_id,
                    'tax_option_id' => $brand->brand_id,
                ];
            }
            $count = count($taxOptions);
            $key = 0;
//            $sumArray = FilterCache::find()->select('options_key')->column();
//            print_r($sumArray);
//            die();
            $sumArray=[];
            $optionsIdArray = [];
            $params = [];

            $this->begin_time = time() - 1272000000 + floatval(microtime());
            $this->RecursiveOptionFinder($category,$count, $taxOptions,$key,$sumArray,$optionsIdArray,$params);

            $end_time = time() - 1272000000 + floatval(microtime()) - $this->begin_time;
            print_r($end_time);
            die();

            }
    }


    /**
     * @param Category $category
     * @param $count
     * @param TaxOption array $taxOptions
     * @param $key
     * @param $sumArray
     * @param $optionsIdArray
     * @param array $params
     */

    public function RecursiveOptionFinder($category, $count, $taxOptions, $key, &$sumArray, $optionsIdArray,$params){

        for($o = $key; $o <= $count; $o++){
            if(isset($taxOptions[$o]) && (count($optionsIdArray) < self::DEPTH)){
                $_optionsIdArray = $optionsIdArray;
                $_optionsIdArray[] = $taxOptions[$o]['tax_option_id'];
                $sum = FilterCache::createCacheKey($_optionsIdArray);
                if( !in_array( $sum, $sumArray)){

                    $sumArray[]  = $sum;
                    $key = $o+1;
                    $this->selectParams($params,$taxOptions[$o]['group_alias'], $taxOptions[$o]['option_alias']);
                    $this->RecursiveOptionFinder($category,$count, $taxOptions, $key, $sumArray,$optionsIdArray,$params);
                    $optionsIdArray[] = $taxOptions[$o]['tax_option_id'];
                    $this->saveFilterCache($category,$params, $sum,$optionsIdArray);
                    $o++;
                } else {
                    $optionsIdArray[] = $taxOptions[$o]['tax_option_id'];
                    $key = $o+1;
                    $this->selectParams($params,$taxOptions[$o]['group_alias'], $taxOptions[$o]['option_alias']);
                    $this->RecursiveOptionFinder($category,$count, $taxOptions, $key, $sumArray,$optionsIdArray,$params);
                    $o++;
                }
            }
        }
    }

    public function selectParams(&$params,$alias,$optionAlias){

        if(isset($params[$alias])){
            $params[$alias][] = $optionAlias;
        } else {

            $params = array_merge($params, [$alias=>[$optionAlias]]);
        }
        return $params;
    }

    /**
     *
     * @param Category $category
     * @param array $params
     * @param $options_key
     * @param array $optionsIdArray
     */

    public function saveFilterCache($category,$params, $options_key,$optionsIdArray){
        $count = $this->findItem($category,$params);

        $model = new FilterCache();
        $model->category_id = $category->category_id;
        $model->count = $count;
        $model->depth = count($optionsIdArray);
        $model->options_key = $options_key;
        $model->save();
    }


    /**
     * @param Category $category
     * @param array $params
     * @return int
     */
    public function findItem($category,$params){
        return $this->getSearchQuery($category,$params)->count();
        //$count2 = $this->getSearchQuery2($category,$params)->count();
//        $this->count ++;
//        if($this->count == 100){
//            $end_time = time() - 1272000000 + floatval(microtime()) - $this->begin_time;
//            print_r($end_time);
//            die();
//        }
    }

    public function getSearchQuery($category = null, $params = []) {


            /** @var ActiveQuery $query */
            /**@var Category $category **/
        $query = $category->getProducts();


        $query->select(['product.*']);
        $query->joinWith(['enabledVariants','brand','options', 'category']);

        $query->groupBy(['product.product_id', 'product_variant.price']);

        ProductHelper::_setQueryParams($query, $params);

        $query->andWhere(['!=', ProductVariant::tableName() .'.status', 1]);



        return $query;

    }

//    public function getSearchQuery2($category = null, $params = []) {
//
//
//        /** @var ActiveQuery $query */
//        /**@var Category $category **/
//        $query = $category->getProducts();
//
//
//        $query->select(['product.*']);
//        $query->joinWith(['enabledVariants','brand','options', 'category']);
//
//        $query->groupBy(['product.product_id', 'product_variant.price']);
//
//        FilterHelper::setNewQueryParams($query, $params);
//
//        $query->andWhere(['!=', ProductVariant::tableName() .'.status', 1]);
//
//
//
//        return $query;
//
//    }

}

