<?php

/**
 * This is the model class for table "mw_developers".
 *
 * The followings are the available columns in table 'mw_developers':
 * @property integer $developer_id
 * @property string $developer_name
 * @property string $description
 * @property string $logo
 * @property string $status
 * @property string $isTrash
 * @property string $added_date
 */
class Developers extends ActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'mw_developers';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('developer_name', 'required'),
            array('developer_name, logo,address', 'length', 'max'=>250),
             array('description,channel,phone,show_home,featured', 'safe' ),
              array('email', 'email' ), 
                array('website', 'url','defaultScheme'=>'https' ), 
              array('phone', 'length', 'max'=>13, 'min'=>8),
            array('status, isTrash', 'length', 'max'=>1),
            array('strating_price, payment_plan, handover, project_title, project_description, header_image', 'safe'),
            array('section_1_heading,description,section_1_img', 'safe'),
            array('section2_heading,section_2_img,section2_content', 'safe'),
            array('section_3_description,section_3_heading,section_3_img', 'safe'),
            array('youtube_url', 'url','defaultScheme'=>'https'),
           //   array('logo', 'file', 'types'=>'jpg,jpeg, gif, png','allowEmpty'=>true ),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('developer_id, developer_name, description, logo, status, isTrash, added_date', 'safe', 'on'=>'search'),
        );
    }
   public function getFilePath($file){
		return Yii::app()->apps->getBaseUrl('uploads/ads/'.$file);
	}	public function getImageDetails($filename){
	    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
	    if(in_array($ext,array('png','jpg','jpeg'))){
	        return Yii::app()->apps->getBaseUrl('uploads/ads/'.$filename);
	    }
	    else{
	          return Yii::app()->apps->getBaseUrl('assets/img/fileext.png' );
	    }
	}
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'developer_id' => 'Developer',
            'state_id' => 'Emirate',
             'city_id' => 'City',
               'address' => 'Address',
            'developer_name' => 'Developer Name',
            'description' => 'Description',
            'logo' => 'Logo',
            'status' => 'Status',
            'isTrash' => 'Is Trash',
            'added_date' => 'Added Date',
            'show_home' => 'Featured',
            'profile_page' => 'Show on listing',
            'section_1_heading' => 'Heading',
            'section_1_img' => 'Image',
            'section2_content' => 'Details',
            'section_2_img' => 'image',
            'section2_heading' => 'Heading',
            'section_3_heading' => 'Heading',
            'section_3_description' => 'Description',
            'section_3_img' => 'Image',
        );
    }
    public $bg_img;
    public $d_logo;
    public $number_of_properties;

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public $id; 
    public function search($return=false)
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('developer_id',$this->developer_id);
        $criteria->compare('developer_name',$this->developer_name,true);
        $criteria->compare('description',$this->description,true);
        $criteria->compare('logo',$this->logo,true);
        $criteria->compare('status',$this->status);
        $criteria->compare('isTrash',0,true);
        $criteria->compare('added_date',$this->added_date,true);
        //$criteria->select = 't.*,(SELECT  count(`id`)  FROM {{place_an_ad}} ad  WHERE  ad.developer_id = t.developer_id )   as number_of_properties';
        if($return){
            return $criteria;
        }
        	$criteria->order ="-t.priority desc,t.developer_name asc";
         return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
             'pagination'    => array(
                'pageSize'  => $this->paginationOptions->getPageSize(),
                'pageVar'   => 'page',
            ),
        ));
    }
    public function beforeSave(){
		 parent::beforeSave();
	 
		 if(defined('OFFPLAN') and empty($this->channel)){
		     $this->channel  = 'O';
		 } 
		 return true;
	 }
    public function getCompanyName(){
        return $this->developer_name;
    }
    public function getlabelItems(){
        return false; 
    }
    public function getAvatarUrl(){
        return $this->BgImage;
    }
    public function getBgImage(){
        if(!empty($this->logo)){
         return   Yii::app()->controller->asset_parent('uploads/images/'.$this->logo);
        }else{
         return Yii::app()->apps->getBaseUrl('assets/img/office-building.png');
            }
    }
     public function getDetailUrl()
    { 
		return Yii::app()->createUrl('vendors/detail',array('slug'=>$this->slug)) ; 
	}
	public $total_properties ; 
    public function findVendors($formData = array(), $count_future = false, $returnCriteria = false, $calculate = false)
    {
        $criteria = $this->search(1);//$criteria->condition = ''; 
         $criteria->distinct = 't.developer_id';
        $criteria->select = 't.*';
        if(defined('SUM')){
           $criteria->select .= ',(SELECT  COALESCE(count(ad.id),0)  FROM {{place_an_ad}} ad  WHERE  ad.developer_id = t.developer_id and  ad.status="A" and  ad.isTrash="0" and  ad.section_id="3" and  ad.channel in ("B","O")         )   as total_properties ';
        }
         
		$filter = @$_GET  ; 
		if(isset($filter['search']) and !empty($filter['search'])){
			$criteria->compare('t.developer_name',$filter['search'],true);
		}
			$criteria->compare('t.status','A');
			if(defined('SUM')){
             $criteria->order  = 't.featured="Y" desc,COALESCE(total_properties,0)  desc,-t.priority desc,COALESCE(t.logo,0) desc, t.developer_id desc';
			}else{
			    $criteria->order  = 't.featured="Y" desc,-t.priority desc,COALESCE(t.logo,0) desc, t.developer_id desc';
			}
        if ($returnCriteria) {
            return $criteria;
        }

        $criteria->limit  = Yii::app()->request->getQuery('limit', '10');
        $criteria->offset = Yii::app()->request->getQuery('offset', '0');
        /* SaFE neighbours */

        if ($calculate and $criteria->offset == 0) {
            $total = self::model()->count($criteria);
        }
        if (!empty($count_future)) {
            $Result = self::model()->findAll($criteria);
            $criteria->offset = $criteria->limit + $criteria->offset;
            $criteria->select = 't.developer_id';
            $criteria->limit = '1';
            $future_count = self::model()->find($criteria);
            return array('result' => $Result, 'future_count' => $future_count, 'total' => $total);
        } else {
            return  self::model()->findAll($criteria);
        }
    }
    
    public function getStatusArray(){
		return array('A'=>'Active','I'=>'Inactive');
	}
    public function getStatusTitle(){
		$ar = $this->getStatusArray();
		return isset($ar[$this->status]) ? $ar[$this->status] : '' ;
	}
	
	public function listData()
    {
		 $criteria=new CDbCriteria;
		 $criteria->select="developer_id,developer_name,t.slug";
		 $criteria->condition="t.status='A' and t.isTrash='0'";
		 $criteria->order="-t.priority desc , t.developer_name asc";
		 return $this->findAll($criteria);
	}
	public function listDatatop()
    {
		 $criteria=new CDbCriteria;
		 $criteria->select="developer_id,developer_name,t.slug";
		 $criteria->condition="t.status='A' and t.isTrash='0'";
		 $criteria->order="t.developer_name asc";
		 $criteria->limit = 130; 
		 return $this->findAll($criteria);
	}
	 public function behaviors(){
    return array_merge(parent::behaviors(),array(
        'SlugBehavior' => array(
            'class' => 'common.models.SlugBehavior.SlugBehavior',
            'slug_col' => 'slug',
            'title_col' =>  'developer_name',
            'overwrite' => false
        ))
    );
   }
   public function getLogoDetat(){
     if(!empty($this->logo)){
        return '<img src="'.Yii::app()->apps->getBaseUrl('uploads/ads/'.$this->logo ).'" style="width:200px;">';
     }
   }
   public function getShortDescription($length = 100)
    {
        return StringHelper::truncateLength($this->description, (int)$length);
    }
     
		public function devloperslist($limit)
    {
		 $criteria=new CDbCriteria;
		 $criteria->select="t.slug,developer_name,t.logo,t.description";
		 $criteria->condition="t.status='A' and t.isTrash='0' and     COALESCE(t.logo,0) > 0 and show_home='1'";
		 $criteria->order="-t.priority desc , t.developer_name asc";
		 $criteria->limit = $limit;
		 return $this->findAll($criteria);
	}
    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Developers the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    function renderImage($image="")
	{
				 $image_name =Yii::app()->basePath . '/../../uploads/developer/'.$image;
				if(@GetImageSize($image_name)) {
					 
					return     $image; 
				}
				else
				{
					 
					return   Yii::app()->theme->baseUrl.'/images/ucnoimage.jpg'; 
				}
			
	}
		public function cacheclistDeveloper(){
	     $cacheKey =  'developlist_cache1';
	
		if ($items = Yii::app()->cache->get($cacheKey) and !isset($_GET['refresh'])) {
		    
			 return $items;
		}
	    $items =CHtml::listData(Developers::model()->listDatatop(),'slug','developer_name');
	    Yii::app()->cache->set($cacheKey, $items,60 * 60 * 24 * 360  );
	 	return $items;
	}
	  protected function afterConstruct()
    {
        $this->fieldDecorator->onHtmlOptionsSetup = array($this, '_setDefaultEditorForContent');
        parent::afterConstruct();
    }
    
    protected function afterFind()
    {
        $this->fieldDecorator->onHtmlOptionsSetup = array($this, '_setDefaultEditorForContent');
        parent::afterFind();
    }
        public function _setDefaultEditorForContent(CEvent $event)
    {
        if (in_array($event->params['attribute'],['description','section2_content','section_3_description'])) {
            $options = array();
            if ($event->params['htmlOptions']->contains('wysiwyg_editor_options')) {
                $options = (array)$event->params['htmlOptions']->itemAt('wysiwyg_editor_options');
            }
            $options['id'] = CHtml::activeId($this, $event->params['attribute']);
            $options['height'] = 100;
            $options['toolbar']= 'Simple';
            $event->params['htmlOptions']->add('wysiwyg_editor_options', $options);
        }
    }

} 
