<?php

/**
 * This is the model class for table "mw_contact_us".
 *
 * The followings are the available columns in table 'mw_contact_us':
 * @property integer $id
 * @property integer $type
 * @property string $email
 * @property string $name
 * @property string $meassage
 * @property string $city
 * @property string $date
 */
class ContactUs extends ActiveRecord
{
	 public $verifyCode;public $_recaptcha ;
	 public $accept;
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'mw_contact_us';
    }

    /**
     * @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('email, name, meassage, phone', 'required','message'=>'Required.'),
            array('type', 'numerical', 'integerOnly'=>true),
            array('email, name', 'length', 'max'=>150),
            array('city', 'length', 'max'=>250),
            array('phone', 'length', 'min'=>10),
             
            array('email', 'email'),array('city', 'safe'),
             array('_recaptcha', 'validateRecaptcha' ,"on"=>'insert' ),
            // array('accept', 'validateAccept' ,"on"=>'insert' ),
           // array('verifyCode', 'CaptchaExtendedValidator', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'captchaAction' => 'site/captcha'),
           // array('verifyCode', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, type, email, name, meassage, city, date', 'safe', 'on'=>'search'),
        );
    }
    public function validateRecaptcha($attribute,$params){
		
		  if(!Yii::app()->request->isAjaxRequest and !defined('IS_API')){
 
	 
			$captcha= '';
			if(isset($_POST['g-recaptcha-response'])){
			$captcha=$_POST['g-recaptcha-response'];
			}

			if(!$captcha){
				$this->addError($attribute,  'Please check the   captcha form.' );
			}
		 
				 
			$data = array(
			'secret' =>  Yii::app()->options->get('system.common.google_recaptcha_secret','') ,
			'response' => $captcha,
			'remoteip' => $_SERVER['REMOTE_ADDR']
			);

			$verify = curl_init();
			curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
			curl_setopt($verify, CURLOPT_POST, true);
			curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
			$res = curl_exec($verify);

			$captcha = json_decode($res);
			
		 
				if ($captcha->success) {
						 
				 }
				 else{
					 $this->addError($attribute,  'You are a spammer.' );
				 }
				
 
		 
		  }
		   
	}
	public function validateAccept($attribute,$params){
		
		  if(isset($_GET['home']) and empty($this->accept)){
            $this->addError($attribute,  'Required.' );
		  }
			 
		   
	}
    /**
     * @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(
            'id' => 'ID',
            'type' => 'Subject',
            'email' => 'Email',
            'name' => 'Full Name',
            'meassage' => 'Message',
            'city' => 'Subject',
            'date' => 'Date',
        );
    }
    public  function beforeSave(){
        $this->phone = str_replace(' ','',$this->phone);
		parent::beforeSave();
		$this->date = date('Y:m:d h:i:s');
		return true;
	}
     
    public  function afterSave(){
            
          return parent::afterSave(); 
		
	}
    public $user   = "18775";          
    public $secret = "b3cb34c9dc4e0d72d30e0e3e33bd306ca2edef982efca72bebe3da174e3689ac";      
    public $url    = "https://t3.lianacem.com";   
    public $realm  = "LCBETA"; 
    public $basePath    = 'rest';   
    public $contentType = 'application/json';
    public $method      = 'POST';
    
    /**
     * 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($return=false)
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('type',$this->type);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('name',$this->name,true);
        $criteria->compare('meassage',$this->meassage,true);
        $criteria->compare('city',$this->city,true);
        $criteria->compare('date',$this->date,true);
        $criteria->compare('contact_type','CONTACT');
         $criteria->order="id desc";
         if($return){
             return $criteria;
         }
		$pageSize = (Yii::app()->request->getQuery("page_size")) ?  (int) Yii::app()->request->getQuery("page_size") : $this->paginationOptions->getPageSize();
		return new CActiveDataProvider($this, array(
		'criteria'=>$criteria,
		'pagination'=>array(
		'pageSize'=>$pageSize,
		),
		));
    }

    /**
     * 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 ContactUs the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    public function Model_type()
    {
		return array(
		
		'1' => 'Need help with a technical problem',
		'2' => 'Report Copyright Infringement',
		'3' => 'Report Spam/Abuse/Fraud',
		'4' => 'Advertising on RsClassify',
		'5' => 'My property listing account',
		'6' => 'My Autos listing account',
		'7' => 'Feedback / suggestions',
		'8' => 'Other / General business inquiry',
		 
		);
	}
    public function getType($id)
    {
		$ar = $this->Model_type();
		return  (isset($ar[$id]))?  $ar[$id] : 'No Subject Defined';
		 
		 
	}
}
