<?php

namespace frontend\controllers;

use common\modules\product\Filter;
use common\modules\product\helpers\ProductHelper;
use common\modules\rubrication\models\TaxOptionSearch;
use frontend\models\ProductFrontendSearch;
use Yii;
use common\modules\product\models\Brand;
use common\modules\product\models\BrandSearch;
use common\modules\product\models\Category;
use common\modules\product\models\CategorySearch;
use common\modules\product\models\Product;
use common\modules\product\models\ProductCategory;
use common\modules\product\models\ProductOption;
use common\modules\product\models\ProductSearch;
use common\modules\product\models\ProductVariant;
use common\modules\rubrication\models\TaxGroup;
use common\modules\rubrication\models\TaxOption;
use common\modules\rubrication\models\TaxValueString;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\data\Sort;
use yii\db\ActiveQuery;
use yii\web\HttpException;

class CatalogController extends \yii\web\Controller
{
    public function actionSearch() {
        // @todo
    }

    public function actionCategory()
    {
        /** @var Category $category */
        $category = Yii::$app->request->get('category');
        $filter = Yii::$app->request->get('filter', []);
        $word = trim(Yii::$app->request->get('word', ''));

        if (empty($category->category_id) && empty($word)) {
            throw new HttpException(404 ,'Page not found');
        }

        $last_products = ProductHelper::getLastProducts(true);

        if (!empty($word)) {
            $params = [];

            $params['keywords'] = explode(' ', preg_replace("|[\s,.!:&?~();-]|i", " ", $word));
            foreach($params['keywords'] as $i => &$keyword) {
                $keyword = trim($keyword);
                if (empty($keyword)) {
                    unset($params['keywords'][$i]);
                }
            }

            $productModel = new ProductFrontendSearch();
            $productProvider = $productModel->search($category, $params);

            $categoriesQuery = Category::find()
                ->innerJoin(ProductCategory::tableName(), ProductCategory::tableName() .'.category_id = '. Category::tableName() .'.category_id')
                ->innerJoin(Product::tableName(), Product::tableName() .'.product_id = '. ProductCategory::tableName() .'.product_id');
            foreach ($params['keywords'] as $keyword) {
                $categoriesQuery->andWhere(['ilike', 'product.name', $keyword]);
            }
            $categories = $categoriesQuery->all();

            return $this->render(
                'search',
                [
                    'keywords'          => $params['keywords'],
                    'category'          => $category,
                    'productModel'      => $productModel,
                    'productProvider'   => $productProvider,
                    'last_products'     => $last_products,
                    'categories'        => $categories,
                ]
            );

        } elseif ($category->depth < 2) {
            return $this->render(
                'categories',
                [
                    'category' => $category,
                    'last_products' => $last_products,
                ]
            );
        } else {
            $params = [];

            if ( !empty($filter['brands']) ) {
                $brands = Brand::find()->select('brand_id')->where(['in', 'alias', $filter['brands']])->all();
                $params['brands'] = [];
                foreach ($brands as $brand) {
                    $params['brands'][] = $brand->brand_id;
                }
            }

            if ( !empty($filter['options']) ) {
                $params['options'] = $filter['options'];
                /*$optionQuery = TaxOption::find();
                $optionQuery->select('tax_option_id');
                $optionQuery->innerJoinWith('group');
                foreach ($filter['options'] as $option_key => $option_values) {
                    $optionQuery->orWhere([
                        'tax_group_id' => $option_key,
                        'alias' => $filter['options']
                        ]);
                }
                $options = ->where(['in', 'alias', $filter['options']])->all();
                $params['options'] = [];
                foreach ($options as $option) {
                    $params['options'][] = $option->tax_option_id;
                }*/
            }

            if ( !empty($filter['prices']) ) {
                $params['prices'] = $filter['prices'];
            }

            $productModel = new ProductFrontendSearch();
            $productProvider = $productModel->search($category, $params);

            $brandModel = new BrandSearch();
            $brandProvider = $brandModel->getBrands($category, $params);

            $optionsProvider = $productModel->optionsForCategory($category, $params);
            $groups = [];
            foreach ($optionsProvider->models as $option) {
                if (!isset($groups[$option->tax_group_id])) {
                    $groups[$option->tax_group_id] = $option->taxGroup;
                    $groups[$option->tax_group_id]->_options = [];
                }
                $groups[$option->tax_group_id]->_options[] = $option;
            }
            foreach($groups as $i => $group) {
                if (empty($group->_options))
                    unset($groups[$i]);
            }

            $priceLimits = $productModel->priceLimits($category, $params);

            return $this->render(
                'products',
                [
                    'category'          => $category,
                    'brandModel'        => $brandModel,
                    'brandProvider'     => $brandProvider,
                    'filter'            => $filter,
                    'productModel'      => $productModel,
                    'productProvider'   => $productProvider,
                    'optionsProvider'   => $optionsProvider,
                    'groups'            => $groups,
                    'priceLimits'       => $priceLimits,
                    'last_products'     => $last_products,
                ]
            );
        }
    }

    public function actionProduct()
    {
        $product = Yii::$app->request->get('product');

        $groups = [];
        foreach($product->category->getTaxGroups()->all() as $_group) {
            $groups[$_group->tax_group_id] = $_group;
        }
        foreach ($product->options as $option) {
            $groups[$option->tax_group_id]->_options[] = $option;
        }
        foreach($groups as $i => $group) {
            if (empty($group->_options))
                unset($groups[$i]);
        }

        $last_products = ProductHelper::getLastProducts(true);
        ProductHelper::addLastProsucts($product->product_id);

        return $this->render('product', [
            'product' => $product,
            'properties' => $groups,
            'last_products' => $last_products
        ]);
    }

    public function actionBrands()
    {
        return 'actionBrands';
    }

    public function actionBrand($alias)
    {
        return 'actionBrand:'. $alias;
    }

}
