<?php
namespace application\modules\sitemap\repositories;

use \Yii;
use \CDbCacheDependency;
use \Article;
use \Menu;
use \InfoPages;
use \EntriesCategory;
use \Apartment;
use \SeoFriendlyUrl;

class SitemapRepository
{
    private $map = [];
    private $isXml = false;
    private $maxUpdatedApartment;
    private $defaultLastMod;
    private $userLang;
    private $app;

    /** @var \SitemapConfig */
    private $config;

    private $removedUrls = [];

    //public $dateFormat = 'Y-m-dTH:i:sP';
    public $dateFormat = 'c';
    public $defaultLang;
    public $activeLangs;

    public function generateMap($isXml = false, $configApply = true)
    {
        $this->isXml = $isXml;
        $this->userLang = $this->defaultLang = Yii::app()->language;

        if (isFree()) {
            $this->activeLangs = array($this->defaultLang => $this->defaultLang);
        } else {
            $this->defaultLang = \Lang::getDefaultLang();
            $this->activeLangs = \Lang::getActiveLangs();   
        }

        if($configApply){
            $this->config = (new SitemapConfigRepository())->getModelConfig();
            $this->removedUrls = $this->config->getRemovedUrls();
        }

        $this->app = Yii::app();
        $this->map = [];

        $cacheKey = "resAllMap{$this->userLang}{$isXml}";
        
        $resAllMap = Yii::app()->cache->get($cacheKey);
        if ($resAllMap !== false){
            return $resAllMap;
        }

        $this->defaultLastMod = $this->maxUpdatedApartment = date($this->dateFormat, time());
        $excludeFromInfoPages = $articleAll = $menuAll = $infoPagesAll = [];

        // apartments module
        if (issetModule('apartments')) {
            if ($isXml) {
                $dependencyApartment = new CDbCacheDependency('SELECT MAX(date_updated) FROM {{apartment}}');
            }
        }

        // article module
        if (issetModule('articles')) {
            Yii::import('application.modules.articles.models.Article');

            $dependencyArticle = new CDbCacheDependency('SELECT MAX(date_updated) FROM {{articles}}');
            $articleAll = Article::model()->cache(param('cachingTime', 86400), $dependencyArticle)->findAll(array(
                'condition' => 'active = 1',
            ));

            if ($isXml) {
                $sql = 'SELECT MAX(date_updated) as date_updated FROM {{articles}}';
                $maxUpdatedArticles = Yii::app()->db->createCommand($sql)->queryRow();
                $maxUpdatedArticles = isset($maxUpdatedArticles['date_updated']) ? date($this->dateFormat, strtotime($maxUpdatedArticles['date_updated'])) : $this->defaultLastMod;
            }
        }

        // menumanager module
        if (issetModule('menumanager')) {
            $dependencyInfoPages = new CDbCacheDependency('SELECT MAX(date_updated) as date_updated FROM {{menu}}');
            $menuAll = Menu::model()->cache(param('cachingTime', 86400), $dependencyInfoPages)->findAll(array(
                'order' => 'number',
                'condition' => 'active = 1 AND (special = 0 OR id = 5) AND ' .
                    (Yii::app()->theme->name == \Themes::THEME_BASIS_NAME ? '(menu_list_id = 3 OR menu_list_id = 4 OR menu_list_id = 5)' : '(menu_list_id = 1 OR menu_list_id = 2)'),
            ));

            if ($isXml) {
                $sql = 'SELECT MAX(date_updated) as date_updated FROM {{menu}}';
                $maxUpdatedMenu = Yii::app()->db->createCommand($sql)->queryRow();
                $maxUpdatedMenu = isset($maxUpdatedMenu['date_updated']) ? date($this->dateFormat, strtotime($maxUpdatedMenu['date_updated'])) : $this->defaultLastMod;
            }

            if ($menuAll) {
                foreach ($menuAll as $menuItem) {
                    if ($menuItem->type == Menu::LINK_NEW_INFO && $menuItem->pageId && $menuItem->special != 1) {
                        $excludeFromInfoPages[] = $menuItem->pageId;
                    }
                }
            }
        }

        // infopages module
        if (issetModule('menumanager')) {
            $dependencyInfoPages = new CDbCacheDependency('SELECT MAX(date_updated) as date_updated FROM {{infopages}}');

            $condition = 'active = ' . InfoPages::STATUS_ACTIVE . ' AND id != 1';
            if ($excludeFromInfoPages && count($excludeFromInfoPages)) {
                $condition .= ' AND id NOT IN(' . implode(',', $excludeFromInfoPages) . ') ';
            }

            $infoPagesAll = InfoPages::model()->cache(param('cachingTime', 86400), $dependencyInfoPages)->findAll(array(
                'condition' => $condition,
            ));

            if ($isXml) {
                $sql = 'SELECT MAX(date_updated) as date_updated FROM {{infopages}}';
                $maxUpdatedInfo = Yii::app()->db->createCommand($sql)->queryRow();
                $maxUpdatedInfo = isset($maxUpdatedInfo['date_updated']) ? date($this->dateFormat, strtotime($maxUpdatedInfo['date_updated'])) : $this->defaultLastMod;
            }
        }


        ####################################### index page #######################################
        if ($isXml) {
            if ($this->activeLangs && is_array($this->activeLangs)) {
                foreach ($this->activeLangs as $keyLang => $valLang) {
                    $this->app->setLanguage($valLang);

                    $this->map['index_page']['title'][$keyLang] = tt('index_page');
                    $this->map['index_page']['url'][$keyLang] = Yii::app()->createAbsoluteUrl('/');
                    $this->map['index_page']['lastmod'][$keyLang] = (isset($indexPageInfo) && isset($indexPageInfo->date_updated)) ? date($this->dateFormat, strtotime($indexPageInfo->date_updated)) : $this->defaultLastMod;
                }
            }
            $this->app->setLanguage($this->defaultLang);
        } else {
            $this->map['index_page']['title'] = tt('index_page');
            $this->map['index_page']['url'] = Yii::app()->createAbsoluteUrl('/');
        }


        ####################################### contact form and booking form #######################################
        if ($isXml) {
            if ($this->activeLangs && is_array($this->activeLangs)) {
                foreach ($this->activeLangs as $keyLang => $valLang) {
                    $this->app->setLanguage($valLang);

                    $this->map['contact_form']['title'][$keyLang] = tt('contact_form');
                    $this->map['contact_form']['url'][$keyLang] = Yii::app()->createAbsoluteUrl('contactform/main/index');
                    $this->map['contact_form']['lastmod'][$keyLang] = (isset($indexPageInfo) && isset($indexPageInfo->date_updated)) ? date($this->dateFormat, strtotime($indexPageInfo->date_updated)) : $this->defaultLastMod;

                    $this->map['booking_form']['title'][$keyLang] = tt('booking_form');
                    $this->map['booking_form']['url'][$keyLang] = Yii::app()->createAbsoluteUrl('booking/main/mainform');
                    $this->map['booking_form']['lastmod'][$keyLang] = (isset($indexPageInfo) && isset($indexPageInfo->date_updated)) ? date($this->dateFormat, strtotime($indexPageInfo->date_updated)) : $this->defaultLastMod;
                }
            }
            $this->app->setLanguage($this->defaultLang);
        } else {
            $this->map['contact_form']['title'] = tt('contact_form');
            $this->map['contact_form']['url'] = Yii::app()->createAbsoluteUrl('contactform/main/index');

            $this->map['booking_form']['title'] = tt('booking_form');
            $this->map['booking_form']['url'] = Yii::app()->createAbsoluteUrl('booking/main/mainform');
        }

        // entries module
        if (issetModule('entries')) {
            $this->generateEntries();
        }

        $this->generateSearch();

        ##################################### seo summary pages #######################################
        if (issetModule('seo')) {
            $citiesListResult = SeoFriendlyUrl::getActiveCityRoute($this->app->controller->params);
            $objTypesListResult = SeoFriendlyUrl::getActiveObjTypesRoute($this->app->controller->params);

            if (is_array($citiesListResult)) {
                $i = 1;
                if (array_key_exists('subsection', $this->map['quick_search'])) {
                    if ($isXml) {
                        $countSubsection = count($this->map['quick_search']['subsection']);
                        if ($this->activeLangs && is_array($this->activeLangs)) {
                            foreach ($this->activeLangs as $keyLang => $valLang) {
                                foreach ($citiesListResult as $key => $value) {
                                    $this->app->setLanguage($valLang);
                                    if(!empty($value[Yii::app()->language])) {
                                        $this->map['quick_search']['subsection'][$countSubsection + $i]['title'][$keyLang] = $value[Yii::app()->language]['name'];
                                        $this->map['quick_search']['subsection'][$countSubsection + $i]['url'][$keyLang] = Yii::app()->controller->createUrl('/seo/main/viewsummaryinfo',
                                            array('cityUrlName' => $value[Yii::app()->language]['url'])
                                        );
                                        $i++;
                                        foreach ($objTypesListResult as $objKey => $objValue) {
                                            $this->map['quick_search']['subsection'][$countSubsection + $i]['title'] = $value[Yii::app()->language]['name'] . ' - ' . $objValue[Yii::app()->language]['name'];
                                            $this->map['quick_search']['subsection'][$countSubsection + $i]['url'] = Yii::app()->controller->createUrl('/seo/main/viewsummaryinfo',
                                                array('cityUrlName' => $value[Yii::app()->language]['url'], 'objTypeUrlName' => $objValue[Yii::app()->language]['url'],)
                                            );
                                            $i++;
                                        }
                                    }
                                }
                            }
                            $this->app->setLanguage($this->defaultLang);
                        }
                    } else {
                        $countSubsection = count($this->map['quick_search']['subsection']);
                        foreach ($citiesListResult as $key => $value) {
                            if(!empty($value[Yii::app()->language])) {
                                $this->map['quick_search']['subsection'][$countSubsection + $i]['title'] = $value[Yii::app()->language]['name'];
                                $this->map['quick_search']['subsection'][$countSubsection + $i]['url'] = Yii::app()->controller->createUrl('/seo/main/viewsummaryinfo',
                                    array('cityUrlName' => $value[Yii::app()->language]['url'])
                                );
                                $i++;
                                foreach ($objTypesListResult as $objKey => $objValue) {
                                    $this->map['quick_search']['subsection'][$countSubsection + $i]['title'] = $value[Yii::app()->language]['name'] . ' - ' . $objValue[Yii::app()->language]['name'];
                                    $this->map['quick_search']['subsection'][$countSubsection + $i]['url'] = Yii::app()->controller->createUrl('/seo/main/viewsummaryinfo',
                                        array('cityUrlName' => $value[Yii::app()->language]['url'], 'objTypeUrlName' => $objValue[Yii::app()->language]['url'],)
                                    );
                                    $i++;
                                }
                            }
                        }
                    }
                }
            }

        }

        ####################################### special offers  #######################################
        if (issetModule('specialoffers')) {
            $specialOfferPage = Menu::model()->findByPk(Menu::SPECIALOFFERS_ID);

            if ($specialOfferPage && $specialOfferPage->active == 1) {
                $i = 0;

                if ($isXml) {
                    $this->map['special_offers']['title'] = tt('special_offers');
                    $this->map['special_offers']['url'] = Yii::app()->createAbsoluteUrl('specialoffers/main/index');
                    $this->map['special_offers']['lastmod'] = $this->maxUpdatedApartment;

                    $specialOffers = Apartment::model()->cache(param('cachingTime', 86400), $dependencyApartment)->findAllByAttributes(array('is_special_offer' => 1), 'active = :active AND owner_active = :ownerActive', array(':active' => Apartment::STATUS_ACTIVE, ':ownerActive' => Apartment::STATUS_ACTIVE));
                    $k = 0;
                    if (is_array($specialOffers) && count($specialOffers) > 0) {
                        foreach ($specialOffers as $value) {
                            if ($this->activeLangs && is_array($this->activeLangs)) {
                                foreach ($this->activeLangs as $keyLang => $valLang) {
                                    $this->app->setLanguage($valLang);

                                    $this->map['special_offers']['subsection'][$k]['title'][$keyLang] = $value->getStrByLang('title');
                                    $this->map['special_offers']['subsection'][$k]['url'][$keyLang] = $value->getUrl();
                                    $this->map['special_offers']['subsection'][$k]['lastmod'][$keyLang] = date($this->dateFormat, strtotime($value['date_updated']));
                                }
                            }
                            $this->app->setLanguage($this->defaultLang);
                            $k++;
                        }
                    }
                } else {
                    $this->map['special_offers']['title'] = tt('special_offers');
                    $this->map['special_offers']['url'] = Yii::app()->createAbsoluteUrl('specialoffers/main/index');
                }
            }
        }


        ####################################### get all menu pages  #######################################
        if (is_array($menuAll) && $menuAll > 0) {
            $i = 0;

            if ($isXml) {
                if ($this->activeLangs && is_array($this->activeLangs)) {
                    foreach ($this->activeLangs as $keyLang => $valLang) {
                        $this->app->setLanguage($valLang);

                        $this->map['section_infopage']['title'][$keyLang] = tt('section_infopage');
                        $this->map['section_infopage']['url'][$keyLang] = null;
                        $this->map['section_infopage']['lastmod'][$keyLang] = $maxUpdatedMenu;

                        foreach ($menuAll as $value) {
                            // убираем из карты сайта типы "Простая ссылка" и "Простая ссылка в выпад. списке"

                            if ($value['type'] != Menu::LINK_NEW_MANUAL && $value['type'] != Menu::LINK_NONE) {
                                $title = $value->getTitle();
                                if ($title && $value['id'] != 1) {
                                    $this->map['section_infopage']['subsection'][$i]['title'][$keyLang] = $title;

                                    if ($value['type'] == Menu::LINK_NEW_INFO) {
                                        $href = $value->getUrl();
                                    } else {
                                        if ($value['id'] == Menu::SITEMAP_ID) { // sitemap
                                            $href = Yii::app()->controller->createAbsoluteUrl('/sitemap/main/index');
                                        }
                                    }

                                    $this->map['section_infopage']['subsection'][$i]['url'][$keyLang] = $href;
                                    $this->map['section_infopage']['subsection'][$i]['lastmod'][$keyLang] = date($this->dateFormat, strtotime($value['date_updated']));

                                    $i++;
                                }
                            }
                        }
                    }
                }
                $this->app->setLanguage($this->defaultLang);
            } else {
                $this->map['section_infopage']['title'] = tt('section_infopage');
                $this->map['section_infopage']['url'] = null;

                foreach ($menuAll as $value) {
                    $title = $value->getTitle();
                    if ($title && $value['id'] != Menu::MAIN_PAGE_ID && $value['type'] != Menu::LINK_NONE) {
                        $this->map['section_infopage']['subsection'][$i]['title'] = $title;

                        if ($value['type'] == Menu::LINK_NEW_INFO) {
                            $href = $value->getUrl();
                        } else {
                            if ($value['id'] == Menu::SITEMAP_ID) { // sitemap
                                $href = Yii::app()->controller->createAbsoluteUrl('/sitemap/main/index');
                            } else {
                                $href = $value->getUrl();
                            }
                        }

                        if ($href)
                            $this->map['section_infopage']['subsection'][$i]['url'] = $href;

                        $i++;
                    }
                }
            }
        }


        ####################################### get all infopages  #######################################
        if (is_array($infoPagesAll) && $infoPagesAll > 0) {
            $issetSectionInfoPages = (isset($this->map['section_infopage']) && isset($this->map['section_infopage']['subsection'])) ? true : false;
            $i = ($issetSectionInfoPages) ? count($this->map['section_infopage']['subsection']) + 1 : 0;

            if ($isXml) {
                if ($this->activeLangs && is_array($this->activeLangs)) {
                    foreach ($this->activeLangs as $keyLang => $valLang) {
                        $this->app->setLanguage($valLang);

                        if (!$issetSectionInfoPages) {
                            $this->map['section_infopage']['title'][$keyLang] = tt('section_infopage');
                            $this->map['section_infopage']['url'][$keyLang] = null;
                            $this->map['section_infopage']['lastmod'][$keyLang] = $maxUpdatedInfo;
                        }

                        foreach ($infoPagesAll as $value) {
                            $title = $value->getTitle();
                            $href = $value->getUrl();
                            if ($title && $href) {
                                $this->map['section_infopage']['subsection'][$i]['title'][$keyLang] = $title;
                                $this->map['section_infopage']['subsection'][$i]['url'][$keyLang] = $href;
                                $this->map['section_infopage']['subsection'][$i]['lastmod'][$keyLang] = date($this->dateFormat, strtotime($value['date_updated']));

                                $i++;
                            }
                        }
                    }
                }
                $this->app->setLanguage($this->defaultLang);
            } else {
                if (!$issetSectionInfoPages) {
                    $this->map['section_infopage']['title'] = tt('section_infopage');
                    $this->map['section_infopage']['url'] = null;
                }

                foreach ($infoPagesAll as $value) {
                    $title = $value->getTitle();
                    $href = $value->getUrl();
                    if ($title && $href) {
                        $this->map['section_infopage']['subsection'][$i]['title'] = $title;
                        $this->map['section_infopage']['subsection'][$i]['url'] = $href;

                        $i++;
                    }
                }
            }
        }

        ####################################### get all article #######################################
        if (is_array($articleAll) && count($articleAll) > 0) {
            $i = 0;

            if ($isXml) {
                if ($this->activeLangs && is_array($this->activeLangs)) {
                    foreach ($this->activeLangs as $keyLang => $valLang) {
                        $this->app->setLanguage($valLang);

                        $this->map['section_article']['title'] = tt('section_article');
                        $this->map['section_article']['url'] = Yii::app()->createAbsoluteUrl('articles/main/index');
                        $this->map['section_article']['lastmod'] = $maxUpdatedArticles;

                        foreach ($articleAll as $value) {
                            $title = $value->getPage_title();
                            if ($title) {
                                $this->map['section_article']['subsection'][$i]['title'] = $title;
                                $this->map['section_article']['subsection'][$i]['url'] = $value->getUrl();
                                $this->map['section_article']['subsection'][$i]['lastmod'] = date($this->dateFormat, strtotime($value['date_updated']));
                                $i++;
                            }
                        }
                    }
                }
                $this->app->setLanguage($this->defaultLang);
            } else {
                $this->map['section_article']['title'] = tt('section_article');
                $this->map['section_article']['url'] = Yii::app()->createAbsoluteUrl('articles/main/index');

                foreach ($articleAll as $value) {
                    $title = $value->getPage_title();
                    if ($title) {
                        $this->map['section_article']['subsection'][$i]['title'] = $title;
                        $this->map['section_article']['subsection'][$i]['url'] = $value->getUrl();
                        $i++;
                    }
                }
            }
        }

        ####################################### reviews  #######################################
        if (issetModule('reviews')) {
            if ($isXml) {
                $sql = 'SELECT MAX(date_updated) as date_updated FROM {{reviews}}';
                $maxUpdatedReviews = Yii::app()->db->createCommand($sql)->queryScalar();

                if ($this->activeLangs && is_array($this->activeLangs)) {
                    foreach ($this->activeLangs as $keyLang => $valLang) {
                        $this->app->setLanguage($valLang);

                        $this->map['reviews']['title'][$keyLang] = tt('Reviews', 'reviews');
                        $this->map['reviews']['url'][$keyLang] = Yii::app()->createAbsoluteUrl('reviews/main/index');
                        $this->map['reviews']['lastmod'][$keyLang] = date($this->dateFormat, strtotime($maxUpdatedReviews));
                    }
                }
                $this->app->setLanguage($this->defaultLang);
            } else {
                $this->map['reviews']['title'] = tt('Reviews', 'reviews');
                $this->map['reviews']['url'] = Yii::app()->createAbsoluteUrl('reviews/main/index');
            }
        }

        if (param('cachingTime')){
            Yii::app()->cache->set($cacheKey, $this->map, 60 * 60 * param('cachingTime'));
        }

        if(!$isXml && $configApply){
            foreach ($this->map as $key => $item) {
                if(in_array($item['url'], $this->removedUrls)){
                    unset($this->map[$key]);
                    continue;
                }

                if (isset($item['subsection']) && count($item['subsection']) > 0) {
                    foreach ($item['subsection'] as $key2 => $value) {
                        if(in_array($value['url'], $this->removedUrls)){
                            unset($this->map[$key]['subsection'][$key2]);
                            continue;
                        }
                    }
                }
            }
        }

        return $this->map;
    }

    private function generateEntries()
    {
        $entriesCategories = EntriesCategory::model()->findAll();

        $entriesAll = [];

        if ($entriesCategories && is_array($entriesCategories)) {
            $entries = \Entries::model()->cache(param('cachingTime', 86400), new CDbCacheDependency('SELECT MAX(date_updated) FROM {{entries}}'))->findAll(['condition' => 'active = 1']);

            if ($this->activeLangs && is_array($this->activeLangs)) {
                foreach ($this->activeLangs as $keyLang => $valLang) {
                    $this->app->setLanguage($valLang);

                    foreach ($entriesCategories as $category) {
                        $entriesAll[$keyLang]['categories'][$category->id]['name'] = $category->getName();
                        $entriesAll[$keyLang]['categories'][$category->id]['url'] = $category->getUrl();

                        if ($entries && is_array($entries)) {
                            $i = 0;
                            foreach ($entries as $entry) {
                                if ($entry->category_id == $category->id) {
                                    $entriesAll[$keyLang]['categories'][$category->id]['items'][$i]['name'] = $entry->getStrByLang('title');
                                    $entriesAll[$keyLang]['categories'][$category->id]['items'][$i]['url'] = $entry->getUrl();
                                    $entriesAll[$keyLang]['categories'][$category->id]['items'][$i]['date_updated'] = $entry->date_updated;
                                }
                                $i++;
                            }
                        }
                    }
                }
                $this->app->setLanguage($this->userLang);
            }
        }

        ####################################### get all entries #######################################
        if (is_array($entriesAll) && count($entriesAll) > 0) {
            if ($this->isXml) {
                $sql = 'SELECT MAX(date_updated) as date_updated FROM {{entries}}';
                $maxUpdatedEntries = Yii::app()->db->createCommand($sql)->queryRow();
                $maxUpdatedEntries = isset($maxUpdatedEntries['date_updated']) ? date($this->dateFormat, strtotime($maxUpdatedEntries['date_updated'])) : $this->defaultLastMod;

                if ($this->activeLangs && is_array($this->activeLangs)) {
                    foreach ($this->activeLangs as $keyLang => $valLang) {
                        $this->app->setLanguage($valLang);

                        if (isset($entriesAll[$valLang]) && is_array($entriesAll[$valLang])) {
                            foreach ($entriesAll[$valLang] as $valuesArr) {
                                if (is_array($valuesArr)) {
                                    foreach ($valuesArr as $key => $values) {
                                        $this->map['section_entries_' . $key]['title'][$keyLang] = $values['name'];
                                        $this->map['section_entries_' . $key]['url'][$keyLang] = $values['url'];
                                        $this->map['section_entries_' . $key]['lastmod'][$keyLang] = $maxUpdatedEntries;

                                        if (isset($values['items']) && count($values['items'])) {
                                            $i = 0;
                                            foreach ($values['items'] as $item) {
                                                if (isset($item['url']) && isset($item['name'])) {
                                                    $this->map['section_entries_' . $key]['subsection'][$i]['title'][$keyLang] = $item['name'];
                                                    $this->map['section_entries_' . $key]['subsection'][$i]['url'][$keyLang] = $item['url'];
                                                    $this->map['section_entries_' . $key]['subsection'][$i]['lastmod'][$keyLang] = date($this->dateFormat, strtotime($item['date_updated']));

                                                    $i++;
                                                }
                                            }
                                        } else {
                                            unset($this->map['section_entries_' . $key]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $this->app->setLanguage($this->defaultLang);
            } else {
                foreach ($entriesAll as $entryLang => $entries) {
                    if ($entryLang == $this->userLang && is_array($entriesAll[$entryLang])) {
                        foreach ($entriesAll[$entryLang] as $valuesArr) {
                            if (is_array($valuesArr)) {
                                foreach ($valuesArr as $key => $values) {
                                    $this->map['section_entries_' . $key]['title'] = $values['name'];
                                    $this->map['section_entries_' . $key]['url'] = $values['url'];

                                    if (isset($values['items']) && count($values['items'])) {
                                        $i = 0;
                                        foreach ($values['items'] as $item) {
                                            if (isset($item['url']) && isset($item['name'])) {
                                                $this->map['section_entries_' . $key]['subsection'][$i]['title'] = $item['name'];
                                                $this->map['section_entries_' . $key]['subsection'][$i]['url'] = $item['url'];

                                                $i++;
                                            }
                                        }
                                    } else {
                                        unset($this->map['section_entries_' . $key]);
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    public function generateSearch()
    {
        ####################################### search #######################################
        if ($this->isXml) {
            if ($this->activeLangs && is_array($this->activeLangs)) {
                foreach ($this->activeLangs as $keyLang => $valLang) {
                    $this->app->setLanguage($valLang);

                    $this->map['quick_search']['title'][$keyLang] = tt('quick_search');
                    $this->map['quick_search']['url'][$keyLang] = Yii::app()->createAbsoluteUrl('quicksearch/main/mainsearch');

                    $sql = 'SELECT MAX(date_updated) as date_updated FROM {{apartment}}';
                    $maxUpdatedApartment = Yii::app()->db->createCommand($sql)->queryScalar();
                    $this->maxUpdatedApartment = $maxUpdatedApartment ? date($this->dateFormat, strtotime($maxUpdatedApartment)) : $this->defaultLatMod;

                    $this->map['quick_search']['lastmod'][$keyLang] = $this->maxUpdatedApartment;
                }
            }
            $this->app->setLanguage($this->defaultLang);
        } else {
            $this->map['quick_search']['title'] = tt('quick_search');
            $this->map['quick_search']['url'] = Yii::app()->createAbsoluteUrl('quicksearch/main/mainsearch');
        }


        ####################################### search subtypes #######################################
        $types = \HApartment::getTypesForSearch(false, false);
        if (is_array($types)) {
            $i = 0;
            foreach ($types as $key => $value) {
                if ($key > 0) {

                    if ($this->isXml) {
                        $useSeasonalPrices = issetModule('seasonalprices');

                        $apartmentsByType = null;

                        $result = null;
                        $titles = array();
                        if ($this->activeLangs && is_array($this->activeLangs)) {
                            foreach ($this->activeLangs as $keyLang => $valLang) {
                                $titles[] = 'a. title_' . $valLang;
                            }
                        }

                        if (count($titles)) {
                            $titles = implode(',', $titles);

                            $whereCondition = ' a.active = ' . Apartment::STATUS_ACTIVE . ' AND a.owner_active = ' . Apartment::STATUS_ACTIVE;

                            if (strpos($key, '-') !== false) {
                                $typeArr = explode('-', $key);

                                if (count($typeArr) == 2) {
                                    $type = (int)$typeArr[0];
                                    $priceType = (int)$typeArr[1];

                                    if ($useSeasonalPrices) {
                                        $whereCondition .= ' AND ( a.id IN(SELECT apartment_id FROM {{seasonal_prices}} sp WHERE sp.price_type = ' . $priceType . ' ) OR (a.is_price_poa = 1) )';
                                    } else {
                                        $whereCondition .= ' AND a.price_type = ' . $priceType;
                                    }

                                    $whereCondition .= ' AND a.type = ' . $type;
                                }
                            } else {
                                $whereCondition .= ' AND a.type = ' . (int)$key;
                            }

                            $sql = 'SELECT a.id, ' . $titles . ', date_updated FROM {{apartment}} a WHERE ' . $whereCondition . ' ORDER BY a.date_updated DESC';
                            $result = Yii::app()->db->createCommand($sql)->queryAll();

                            unset($titles);
                        }

                        if ($result) {
                            foreach ($result as $item) {
                                $apartmentsByType[$item['id']] = $item;
                            }
                        }

                        $k = 0;
                        if (is_array($apartmentsByType) && count($apartmentsByType) > 0) {
                            $urls = array();
                            if ($this->activeLangs && is_array($this->activeLangs)) {
                                foreach ($this->activeLangs as $keyLang => $valLang) {
                                    $urls[] = 'url_' . $valLang;
                                }
                            }

                            if (issetModule('seo') && count($urls)) {
                                $urls = implode(',', $urls);

                                $sql = 'SELECT model_id, ' . $urls . ' FROM {{seo_friendly_url}} WHERE model_name="Apartment" ORDER BY id ASC';
                                $resultSEO = Yii::app()->db->createCommand($sql)->queryAll();

                                if ($resultSEO) {
                                    foreach ($resultSEO as $item) {
                                        if (isset($apartmentsByType[$item['model_id']])) {
                                            $apartmentsByType[$item['model_id']] = \CMap::mergeArray($apartmentsByType[$item['model_id']], $item);
                                        }
                                    }
                                }
                            }

                            foreach ($apartmentsByType as $value) {
                                if ($this->activeLangs && is_array($this->activeLangs)) {
                                    foreach ($this->activeLangs as $keyLang => $valLang) {
                                        $this->app->setLanguage($valLang);

                                        if (isset($value['title_' . $valLang]) && $value['title_' . $valLang])
                                            $this->map['quick_search']['subsection'][$i]['apartments'][$k]['title'][$keyLang] = $value['title_' . $valLang];

                                        if (isset($value['url_' . $valLang]) && $value['url_' . $valLang])
                                            $this->map['quick_search']['subsection'][$i]['apartments'][$k]['url'][$keyLang] = Yii::app()->createAbsoluteUrl('/apartments/main/view', array('url' => $value['url_' . $valLang] . (param('urlExtension') ? '.html' : '')));
                                        else
                                            $this->map['quick_search']['subsection'][$i]['apartments'][$k]['url'][$keyLang] = Yii::app()->createAbsoluteUrl('/apartments/main/view', array('id' => $value['id']));

                                        if (isset($value['date_updated']) && $value['date_updated'])
                                            $this->map['quick_search']['subsection'][$i]['apartments'][$k]['lastmod'][$keyLang] = date($this->dateFormat, strtotime($value['date_updated']));
                                    }
                                }
                                $this->app->setLanguage($this->defaultLang);
                                $k++;
                            }
                        }
                    } else {
                        //$this->_map['apartment_types'][$i]['title'] = mb_convert_case($value, MB_CASE_TITLE, "UTF-8");
                        // нет смсылсла т.к. ведут на canonical /search
                        $this->map['quick_search']['subsection'][$i]['title'] = $value;
                        $this->map['quick_search']['subsection'][$i]['url'] = Yii::app()->createAbsoluteUrl('quicksearch/main/mainsearch', array('apType' => $key));
                    }
                    $i++;
                }
            }
        }

        //return;
        ####################################### search object types #######################################
        // нет смсылсла т.к. ведут на canonical /search

        $objTypes = Apartment::getObjTypesArray();
        if (is_array($objTypes)) {
            $i = 1;
            if (array_key_exists('subsection', $this->map['quick_search'])) {
                if ($this->isXml) {
                    $countSubsection = count($this->map['quick_search']['subsection']);
                    if ($this->activeLangs && is_array($this->activeLangs)) {
                        foreach ($this->activeLangs as $keyLang => $valLang) {
                            foreach ($objTypes as $key => $value) {
                                $this->app->setLanguage($valLang);

                                $this->map['quick_search']['subsection'][$countSubsection + $i]['title'][$keyLang] = $value;
                                $this->map['quick_search']['subsection'][$countSubsection + $i]['url'][$keyLang] = Yii::app()->createAbsoluteUrl('quicksearch/main/mainsearch', array('objType' => $key));
                                $i++;
                            }
                        }
                        $this->app->setLanguage($this->defaultLang);
                    }
                } else {
                    $countSubsection = count($this->map['quick_search']['subsection']);
                    foreach ($objTypes as $key => $value) {
                        $this->map['quick_search']['subsection'][$countSubsection + $i]['title'] = $value;
                        $this->map['quick_search']['subsection'][$countSubsection + $i]['url'] = Yii::app()->createAbsoluteUrl('quicksearch/main/mainsearch', array('objType' => $key));
                        $i++;
                    }
                }
            }
            // no in xml because all links to listings generated above in search subtypes section
            // duplication link is not needed.
        }

    }
}