<?php

/**
 * This is the model class for table "mw_countries".
 *
 * The followings are the available columns in table 'mw_countries':
 * @property integer $country_id
 * @property string $country_name
 * @property string $country_code
 * @property integer $isTrash
 */
class Countries extends ActiveRecord
{
	 
    /**
     * @return string the associated database table name
     */
    public $location ; 
    public function tableName()
    {
        return '{{countries}}';
    }
	protected function afterValidate()
    {
        parent::afterValidate();
        $this->handleUploadedAvatar();
    }
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        $email_logorMimes = null;
        if (CommonHelper::functionExists('finfo_open')) {
            $email_logorMimes = Yii::app()->extensionMimes->get(array('png', 'jpg', 'gif'))->toArray();
        }
        return array(
            array('country_name', 'required'),
            array('isTrash', 'numerical', 'integerOnly'=>true),
            array('country_name', 'length', 'max'=>250),
            array('country_code', 'length', 'max'=>5),
            array('show_on_listing', 'length', 'max'=>1),
             array('flag', 'file', 'types' => array('png', 'jpg', 'gif'), 'mimeTypes' => $email_logorMimes, 'allowEmpty' => true),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('country_id, country_name, country_code, isTrash,image,cords', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @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(
          'statelist'=>array(self::HAS_MANY, 'States', 'country_id','on'=>'statelist.isTrash=0'),
          
        );
    }
     protected function handleUploadedAvatar()
    {
        if ($this->hasErrors()) {
            return;
        }
      

        if (!($avatar = CUploadedFile::getInstance($this, 'flag'))) {
            return;
        }
 
        $storagePath = Yii::getPathOfAlias('root.uploads.logo');
        if (!file_exists($storagePath) || !is_dir($storagePath)) {
            if (!@mkdir($storagePath, 0777, true)) {
                $this->addError('flag', Yii::t('users', 'The logo storage directory({path}) does not exists and cannot be created!', array(
                    '{path}' => $storagePath,
                )));
                return;
            }
        }

        $newAvatarName = uniqid(rand(0, time())) . '-' . $avatar->getName();
        if (!$avatar->saveAs($storagePath . '/' . $newAvatarName)) {
            $this->addError('flag', Yii::t('users', 'Cannot move the avatar into the correct storage folder!'));
            return;
        }

        $this->flag = '/uploads/logo/' . $newAvatarName;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'country_id' => 'Country',
            'country_name' => 'Country Name',
            'country_code' => 'Country Code',
            'isTrash' => 'Is Trash',
        );
    }
  public function getGravatarUrl($width = 50, $height = 50, $forceSize = false)
    {
	 
         if (empty($this->flag)) {
            return  false;
         }
         return ImageHelper::resize($this->flag, $width, $height, $forceSize);
 }
  public function getGravatarUrlFromCookie($width = 50, $height = 50, $forceSize = false)
    {
	  
         if (empty($this->defaultFlag)) {
            return  false;
         }
         return ltrim($this->defaultFlag,'/');
         //return ImageHelper::resize($this->defaultFlag, $width, $height, $forceSize);
 }
  public function getDefaultCountry()
  {
	 
			 if(   Yii::app()->request->cookies['country_id'] !=""  and   Yii::app()->request->cookies['country_name'] !="" ){
				 return Yii::app()->request->cookies['country_name'] ;
			 }
			 else{
				 
				$country =  self::model()->findByPk(Yii::app()->options->get('system.common.default_country',65946));
				if(!empty($country)){
					$cookie = new CHttpCookie('country_name', $country->country_name);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['country_name'] = $cookie;
					
					$cookie = new CHttpCookie('country_id', $country->country_id);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['country_id'] = $cookie;
					$cookie = new CHttpCookie('flag', $country->flag);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['flag'] = $cookie;
				}
				return $country->country_name;
				}
 }
 
  public function getDefaultCountryId()
  {
			 if( Yii::app()->request->cookies['country_id'] !=""  and   Yii::app()->request->cookies['country_name'] != "" ){
				 return Yii::app()->request->cookies['country_id'] ;
			 }
			 else{
				 
				$country =  self::model()->findByPk(Yii::app()->options->get('system.common.default_country',65946));
				if(!empty($country)){
					$cookie = new CHttpCookie('country_name', $country->country_name);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['country_name'] = $cookie;
					
					$cookie = new CHttpCookie('country_id', $country->country_id);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['country_id'] = $cookie;
					$cookie = new CHttpCookie('flag', $country->flag);
					$cookie->expire = time()+60*60*24*180; 
					Yii::app()->request->cookies['flag'] = $cookie;
				}
				return $country->country_id;
				}
 }
  public function getDefaultFlag()
  {
			 if(Yii::app()->request->cookies['flag'] !="" ){
				 return Yii::app()->request->cookies['flag'] ;
			 }
			  return false;
	 
	  
 }
   public function getShow_on_listingHtml(){
	   
	  return CHtml::CheckBox('update_listing',($this->show_on_listing=='1')? true : false, array ( 'onChange'=>'return ChangeListing(this)' , 'value'=> $this->country_id ));
  }
    /**
     * 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 function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('country_id',$this->country_id);
        $criteria->compare('country_name',$this->country_name,true);
        $criteria->compare('country_code',$this->country_code,true);
        $criteria->compare('isTrash',$this->isTrash);
        $criteria->order = "show_on_listing=1,country_name" ;
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
             'pagination'    => array(
                'pageSize'  => $this->paginationOptions->getPageSize(),
                'pageVar'   => 'page',
            ),
        ));
    }

    /**
     * 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 Countries the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    public function Countrylist2()
    {
		  $criteria=new CDbCriteria;
		  $criteria->condition="isTrash='0'  and  show_on_listing='1'";
		  $criteria->order="t.country_name";
		  //$criteria->select="country_id,country_name";
		  return $this->findAll($criteria);
		
	}
    public function Countrylist()
    {
		  $criteria=new CDbCriteria;
		  $criteria->condition="isTrash='0'";
		  $criteria->order="t.country_name";
		  //$criteria->select="country_id,country_name";
		  return $this->findAll($criteria);
		
	}
    public function CountrylistFromCookie()
    {
		  $criteria=new CDbCriteria;
		  if(Yii::app()->request->cookies['country'])
		  {
			  $criteria->condition="isTrash='0' and country_id!=:para";
			  $criteria->params[":para"] = Yii::app()->request->cookies['country'];
		  }
		  else
		  {
			  $criteria->condition="isTrash='0'";
		  }
		  
		 // $criteria->select="country_id,country_name";
		  return $this->findAll($criteria);
		
	}
	 public function getCountryByclass($country)
    {
		  $criteria=new CDbCriteria;
		  $criteria->condition="isTrash='0' and image=:params";
		  $criteria->params[":params"] =$country;
		 // $criteria->select="country_id,country_name";
		  return $this->find($criteria);
		
	}
		 public function getCountryFromCookie()
    {
		  $criteria=new CDbCriteria;
		  $criteria->condition="isTrash='0' and country_id=:params";
		  $criteria->params[":params"] = Yii::app()->request->cookies['country'];
		 // $criteria->select="country_id,country_name";
		  return $this->find($criteria);
		
	}
	 function getCountry_1()
	{
		 static $_options = array();
		 
		 $r= $this->findAll(array("condition"=>"isTrash='0' " ,"order"=>"country_name"));
	 
		 if($r)
		 {
			 foreach($r as $k=>$v)
			 {
				  $_options[$v->country_id] =  $v->country_name; 
			 }
	     }
	     return $_options;
		 
	}
   	public function getStateWithCountry()
	{
		$criteria=new CDbCriteria;
		$criteria->with =array("statelist","statelist.hotelCount"=>array("condition"=>"t.isTrash='0' and t.status='A'"));
		$criteria->condition="t.isTrash=0";
		$criteria->order = "t.country_name";
		$ar =  $this->findAll($criteria);
		$listarray =array();
		 if($ar)
		 {
			 foreach ($ar as $k=>$v)
			 {
				 if($v->statelist)
				 {
					  
					 foreach($v->statelist as $k1=>$v1)
					 {
						  $listarray[$v->country_id.':'.$v1->state_id] = $v->country_name.','.$v1->state_name."(".$v1->hotelCount.")";
					 }
				
			     }
			     else
			     {
					  $listarray[$v->country_id.':0']  = $v->country_name."(0)";
				 }
		      }
		  }
		  return  $listarray;
		 
	}
	public function  ListDataForJSON()
    {
		 $criteria=new CDbCriteria;
		 $criteria->condition = "t.isTrash='0' and  show_on_listing='1'";
		 $criteria->select ="country_id,country_name";
		 $criteria->order="country_name";
		 $arra =  $this->findAll($criteria);
		 $ar =array();
		 if($arra)
		 {
			 foreach($arra as $k=>$v)
			 {
				 $ar[]= array("id"=>$v->country_id , "name" => $v->country_name );
			 }
		 }
	  return CJSON::encode(array_merge(array("0"=>"Select Country"), $ar));
	}
	public function  countriesOtherThanDefault()
    {
		 $criteria=new CDbCriteria;
		 $criteria->condition = "t.isTrash='0' and  show_on_listing='1' and t.country_id !=:default";
		 $criteria->select ="country_id,country_name,flag";
		 $criteria->order="country_name";
		 $criteria->params= array(':default'=>$this->defaultCountryId);
		 return  $this->findAll($criteria);
		 
	}
}
