<?php
    
    namespace frontend\controllers;
    
    use common\modules\product\models\Product;
    use yii\data\ActiveDataProvider;
    use yii\web\Controller;
    
    /**
     * Search controller
     */
    class SearchController extends Controller
    {
        
        /**
         * Displays search result.
         * @return string
         */
        public function actionIndex()
        {
            $search = \Yii::$app->request->get('search');
            if(empty( $search )) {
                return $this->redirect([ 'site/index' ]);
            }
            $query = Product::find()
                            ->joinWith('lang', true, 'INNER JOIN')
                            ->joinWith('variants.lang', true, 'INNER JOIN')
                            ->joinWith('brand.lang', true, 'INNER JOIN')
                            ->where([
                                'ilike',
                                'product_lang.name',
                                $search,
                            ])
                            ->orWhere([
                                'ilike',
                                'brand_lang.name',
                                $search,
                            ])
                            ->orWhere([
                                'ilike',
                                'product_variant_lang.name',
                                $search,
                            ]);
            $dataProvider = new ActiveDataProvider([
                'query'      => $query,
                'pagination' => [
                    'pageSize' => 20,
                ],
            ]);
            
            return $this->render('index', [
                'dataProvider' => $dataProvider,
                'search'       => $search,
            ]);
        }
    }
