<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.36.0
 * 	copyright			:	(c) 2016 Monoray
 * 							http://monoray.net
 * 							http://monoray.ru
 *
 * 	website				:	http://open-real-estate.info/en
 *
 * 	contact us			:	http://open-real-estate.info/en/contact-us
 *
 * 	license:			:	http://open-real-estate.info/en/license
 * 							http://open-real-estate.info/ru/license
 *
 * This file is part of Open Real Estate
 *
 * ********************************************************************************************* */
namespace application\modules\yandexRealty\repositories;

use Yii;

class YandexRealtyRepository
{
    public function getAdsWithoutDateCriteria($criteria = null)
    {
        $lang = Yii::app()->language;

        $where = $this->getWhere($criteria);

        $cacheKey = md5('xyx' . $where . $lang);

        $resActiveYandexRealtyAllAds = Yii::app()->cache->get($cacheKey);
        if ($resActiveYandexRealtyAllAds !== false){
            return $resActiveYandexRealtyAllAds;
        }

        $addSelect = $addSelectJoin = '';

        if (issetModule('location')) {
            $addSelect = '
					lc.name_' . $lang . ' as loc_country_name,
					lr.name_' . $lang . ' as loc_region_name,
					lcc.name_' . $lang . ' as loc_city_name,
					ap.loc_country, ap.loc_region, ap.loc_city,
				';
            $addSelectJoin = '
					LEFT JOIN {{location_country}} lc ON lc.id = ap.loc_country
					LEFT JOIN {{location_region}} lr ON lr.id = ap.loc_region
					LEFT JOIN {{location_city}} lcc ON lcc.id = ap.loc_city
				';
        }

        if (issetModule('seo')) {
            $addSelect .= ' seo.url_' . $lang . ' as seoUrl, ';
            $addSelectJoin .= ' LEFT JOIN {{seo_friendly_url}} seo ON (seo.model_id = ap.id) AND (seo.model_name = "Apartment")';
        }

        if (issetModule('seasonalprices')) {
            $addSelect .= ' seasonprice.price as price_rent, seasonprice.price_type as price_type_rent, ';
            $addSelectJoin .= ' LEFT JOIN {{seasonal_prices}} seasonprice ON seasonprice.apartment_id = ap.id';
        }

        $addSelect .= ' ap.price as price, ap.price_type as price_type, ';

        $sql = '
				SELECT ap.id, ap.type, ap.obj_type_id,
				ap.city_id, ap.num_of_rooms, ap.floor, ap.floor_total, ap.square, ap.land_square, ap.window_to,
				ap.title_' . $lang . ', ap.description_' . $lang . ',
				ap.description_near_' . $lang . ', ap.address_' . $lang . ',
				ap.berths, ap.lat, ap.lng, ap.date_manual_updated, ap.date_created,
				ap.open_plan, ap.room_type, ap.balcony_type, ap.wc_type, ap.floor_coat, ap.garage_type, ap.build_year,
				ap.repair, ap.object_state, ap.building_type, ap.plot_type, ap.phone,
			 	' . $addSelect . '
				ac.name_' . $lang . ' as city_name,
				awt.title_' . $lang . ' as window_to_name,
				u.phone as owner_phone, u.email as owner_email, u.id as owner_id, u.username as owner_username, u.type as owner_type, 
				aop.name_' . $lang . ' as obj_type_name, aop.ya_type as ya_type, aop.ya_subtype as ya_subtype
				FROM {{apartment}} ap
				' . $addSelectJoin . '
				LEFT JOIN {{apartment_obj_type}} aop ON aop.id = ap.obj_type_id
				LEFT JOIN {{apartment_city}} ac ON ac.id = ap.city_id
				LEFT JOIN {{apartment_window_to}} awt ON awt.id = ap.window_to
				LEFT JOIN {{users}} u ON u.id = ap.owner_id
				WHERE ' . $where . '
				ORDER BY ap.id DESC
				LIMIT 5500
				';

        $params = $criteria ? $criteria->params : [];

        $activeAds = Yii::app()->db->createCommand($sql)->queryAll(true, $params);

//        $ads = \Apartment::model()->findAll($criteria);
//
//        deb(\CHtml::listData($ads, 'id', 'title'));
//        die;

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

        return $activeAds;
    }

    private function getWhere($criteria)
    {
        if($criteria){
            $criteria->select = 'id';
            $sql = \Apartment::model()->getCommandBuilder()->createFindCommand(\Apartment::model()->tableName(), $criteria)->text;
            return ' ap.id IN ('.$sql.') ';
        }

        $objTypes = \ApartmentObjType::getYANTypes();
        if (!$objTypes) {
            throw new \InvalidArgumentException('Не заданы соответствия типов для объявлений.');
        }
        $objTypeIds = array_keys($objTypes);

        $where = ' ( ap.type = ' . \Apartment::TYPE_RENT . ' OR ap.type = ' . \Apartment::TYPE_SALE . ') '; // только аренда/продажа
        $where .= ' AND ap.is_price_poa = 0 '; // "цена договорная" - не поддерживается Яндексом.

        if($objTypeIds){
            $where .= ' AND ap.obj_type_id IN ('.implode(',', $objTypeIds).') ';
        }

        if (issetModule('userads') && param('useModuleUserAds', 1)) {
            $where .= ' AND owner_active = "' . \Apartment::STATUS_ACTIVE . '" ';
        }

        $where .= ' AND (LENGTH (u.phone) > 0) AND ap.active = "' . \Apartment::STATUS_ACTIVE . '" ';

        return $where;
    }
}