<?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 ProjectEnquiry  extends ContactUs
{
	 public $image;
	 public $phone_false;
	 public $_recaptcha ;
	 public $_enable_recaptcha ;
	 public $check_captcha; 
    /**
     * @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('name, email, phone', 'required',    'message'=>  'Required' ),
           // array('i_am,city,phone',defined('OFFPLAN') ? 'safe' :  'required',    'message'=> 'Required' ),
          //   array('city', 'validateItems',    'message'=>   'Required' ),
            array('type,phone,phone_false', 'numerical', 'integerOnly'=>true),
            array('email, name', 'length', 'max'=>150),
            array('meassage', 'safe'  ),
            array('city', 'length', 'max'=>250),
           // array('phone', 'validatePhone' ),
           // array('phone_false', 'validatePhone' ),
            array('phone_false', 'validatePhoneFalse' ),
            array('_recaptcha', 'validateRecaptcha'),
             array('m_id,meassage,m_id3,m_id4,m_id5', 'safe'),
            array('m_id', 'validateEnquiry'),
   
            array('email', 'email',  'message'=>'{attribute} '.  'is not a valid e-mail address.' ),
            array('contact_type,w_talk,user_id,ad_title,ad_id,cords,is_p,i_am', 'safe'),
           // array('verifyCode', 'CaptchaExtendedValidator', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'captchaAction' => 'site/captcha'),
           // array('verifyCode', 'safe'),
           array('ad_title,ad_section,country_name,_enable_recaptcha, check_captcha,ad_title2,channel,m_id2 ', '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,ad_title2', 'safe', 'on'=>'search'),
             array('image', 'file', 'types'=>'pdf,doc,docx', 'allowEmpty'=>true,  'safe' => true),
        );
    }
     public function validateItems($attribute,$params){  
         if(defined('OFFPLAN')){ return true; }
	 		if (empty($this->$attribute)    ){
			    $this->addError('city',   'Required' );
			    
			}
		 
	}
       public function validateEnquiry($attribute,$params){  
	 		if (empty($this->$attribute) and empty($this->ad_id) and !empty($this->user_id)   ){
			    $this->addError('m_id', 'Select enquiry type');
			    
			}
		 
	}
    public function validateRecaptcha($attribute,$params){
		
		  if(  $this->check_captcha =='1'){
 
	 
			$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.recaptcha_secrete_key','6LeJ_cwUAAAAAEgV7xGlhLnYxBF52TRo1Lh6I07Q'),
			'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,  'Please refresh and try again. Spam suspect.' );
				 }
				
 
		 
		  }
		   
	}
    
    	 public function validatePhoneFalse($attribute,$params)
	{
		if(empty($this->phone) and  empty($this->phone_false)){
		        if(!defined('OFFPLAN')){
				 $this->addError($attribute,  Yii::t('app',  'Required' ));
		        }
			 
		}
	}
 
    public function attributeLabels()
    {
	 
        return array(
            'id' => 'ID',
            'ad_id' => 'AD',
            'type' => 'Position',
            'ad_title2' =>'Property/Realtor',
            'phone' =>   'Phone' ,
            'email' =>   'Email' ,
            'ad_title' =>   'Ad Title' ,
           
            'meassage' =>  'Message' ,
            'city' =>   'What\'s your enquiry about?' ,
            'date' => 'Date',
            'w_talk' => 'Date',
             'name' => 'Name' ,
             'phone_false' => 'Phone' ,
             'i_am' =>   'Do you have finance pre-approval?' ,
             'm_id2' => 'What are you looking to do?', 
                   'm_id3'=> 'How many bedrooms are you looking for?',
             'm_id4'=>'What is your budget?',
             'm_id5'=>'When do you want to buy?',
        );
    }
    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(
        'ad' => array(self::BELONGS_TO, 'PlaceAnAd', 'ad_id'),
        'agent' => array(self::BELONGS_TO, 'ListingUsers', 'user_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 $ad_title;
     public $cords;
     public $ad_slug;
     public $ad_section;
     public $country_name;
     public $first_name;
     public $last_name;
     public $company_name;
     public function getRealtorTitle(){
         $html  = '';  
         if(!empty($this->company_name)){
             $html .= $this->company_name.'(agency)<br />';
         }
         $html .= $this->first_name.' '.$this->last_name;
         return $html; 
     }
       public function getDetailUrlAdNew(){
           $html = $this->DetailUrlAd;
		   $html .= '<br />'.$this->RealtorTitle;
		   return $html;
       }
       public $ad_title2;
    public function search($return=false)
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;
        $criteria->condition = '1'; $criteria->select = 't.*';
        $criteria->compare('t.id',$this->id);
        //$criteria->select = ('ads.user_id',$this->user_id);
        //$criteria->compare('ads.user_id',$this->user_id);
        $criteria->compare('ad_title',$this->ad_title,true);
        $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('ad_title',$this->ad_title,true);
        $criteria->compare('cn.country_name',$this->country_name,true);
        $criteria->compare('ads.section_id',$this->ad_section);
         $criteria->select = 't.*,ads.ad_title,ads.slug as ad_slug ,ads.section_id as ad_section, cn.cords, cn.country_name'; 
        $criteria->compare('contact_type','ENQUIRY');
        $criteria->join = ' INNER   JOIN {{place_an_ad}} ads on ads.id = t.ad_id and  ads.isTrash="0" ';
        $criteria->join .= ' LEFT JOIN {{countries}} cn on cn.country_id = ads.country ';
        $criteria->join .= ' LEFT JOIN {{listing_users}} usr on usr.user_id = t.user_id ';
        $criteria->join .= ' LEFT JOIN {{listing_users}} usr2 on usr2.user_id = ads.user_id ';
        if(Yii::App()->isAppName('backend')){
				$criteria->condition .= ' and  t.ad_id IS NOT NULL  ';
					$criteria->condition .= ' and  t.ad_id IS NOT NULL  ';
					 $criteria->select .= ',usr2.first_name,usr2.last_name,(case when usr2.parent_user is null then usr2.company_name else puser.company_name end) as company_name';
		         $criteria->join .= ' LEFT JOIN {{listing_users}} puser on (case when  usr2.parent_user is not null then  puser.user_id = usr2.parent_user ELSE 0 END ) ';
		        if(!empty($this->ad_title2)){
		            $criteria->condition .= ' and ((case when usr2.parent_user is null then usr2.company_name else puser.company_name end) like :kwrd or ad_title like :kwrd )';
		            $criteria->params[':kwrd'] = '%'.$this->ad_title2.'%';
		        }
            
        }
        if(!empty($this->user_id)){
			$criteria->condition .= ' and CASE WHEN t.ad_id IS NOT NULL THEN  (usr2.user_id =:user_id or usr2.parent_user =:user_id) ELSE t.user_id =:user_id END  ';
			$criteria->params[':user_id'] = $this->user_id ; 
		}
        if(!empty($return)){ return $criteria; }
         $criteria->order="t.id desc";
	 	return new CActiveDataProvider($this, array(
		'criteria'=>$criteria,
		   'pagination'    => array(
                'pageSize'  => $this->paginationOptions->getPageSize(),
                'pageVar'   => 'page',
            ),
		));
    }
    public function getEmailPhoneField(){
        return $this->name.'<br />'.$this->email.'<br />'.$this->phone;
    }
      public function getRealtor(){
        return $this->name.'<br />'.$this->email.'<br />'.$this->phone;
    }
        
 public function beforeValidate(){
        parent::beforeValidate();
        	$this->phone = str_replace(['+',' '],'',$this->phone);
        if(!empty($this->city)){
         $this->city = serialize($this->city);
        }
         
	return true;
    }
    public function beforeSave(){
		
	   if(parent::beforeSave()) 
	   {
	        if(!empty($this->visit)){
	           $this->visit = date('Y-m-d',strtotime($this->visit));
	       }
			 $this->contact_type= 'ENQUIRY';
			 $this->is_p='1'; 
	    
		  if(defined('COUNTRY')){
				 $this->cords = COUNTRY ; 
			 }

		  if(defined('OFFPLAN')){
				 $this->channel = 'O' ; 
			 }
			 return true;
	   }
	return true;
	 
	}
    /**
     * 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 afterSave(){
		 
		
		    $options = Yii::app()->options ; 
		    $tem_id = 'lr6078aovad72';
		    if(!empty($this->user_id)){
		     $tem_id = 'ws512z5jm67a8';
		    }
		    $emailTemplate =  CustomerEmailTemplate::model()->getTemplateByUid( $tem_id); 
		    $server = DeliveryServer::pickServer();  
		    $emailTemplate_common =  $options->get('system.email_templates.common')  ;
		 
			if($emailTemplate) { 
				
				$subject       = $emailTemplate->subject;
				$emailTemplate = $emailTemplate->content;
				
				}
			else { 	 return true; }
		   
		    $emailTemplate = str_replace('{name}',$this->name, $emailTemplate);
			$emailTemplate = str_replace('{phone}', $this->phone, $emailTemplate);
			$emailTemplate = str_replace('{email}', $this->email, $emailTemplate);
			if(!empty($this->m_id)){
			   $mid= EnquiryType::model()->findByPk($this->m_id);
			   if( $mid){
			    $emailTemplate = str_replace('{type}', $mid->name, $emailTemplate);
			   }
			}
			$emailTemplate = str_replace('{message}', nl2br($this->meassage), $emailTemplate);
			$emailTemplate = str_replace('{date}', $this->dateAdded, $emailTemplate);
			if(!empty($this->user_id)){
				$emailTemplate = str_replace('{url}', '<a href="'.$this->agent->AgentDetailUrl2.'">'.$this->agent->fullName.'</a>', $emailTemplate);
		    }
		    else if(!empty($this->ad_id)){
				
				
		 
				    $model = new PlaceAnAd();
                    $featuredListingCriteria       =   PlaceAnAd::model()->findAds(array(),$count_future=false,$returnCriteria=1,$calculate=false,$user_id=false);
                    $featuredListingCriteria->compare('t.id',(int)$this->ad_id );  
                    $ad =  PlaceAnAd::model()->find($featuredListingCriteria) ;
		            
		            if($this->is_p=='1'){
		                     	$url =   $ad->detailUrlAbsolute;    
		                    
		                    $emailTemplate = str_replace('{url}', '<a href="'.$url .'">'. $ad->ad_title.'</a>', $emailTemplate);
		   
		            }else{
		        	$emailTemplate = str_replace('{url}', '<a href="'. $ad->DetailUrlAbsolute.'">'. $ad->ad_title.'</a>', $emailTemplate);
		            }
		    }
		    else{
				$emailTemplate = str_replace('{url}','', $emailTemplate);
			}
			if(!empty($this->user_id)){
				$usersList = array_replace( array(Yii::app()->options->get('system.common.contact_email')=>'Admin'),array($this->agent->email=>$this->agent->fullName) ); 
			}
			else if(!empty($this->ad_id)){ 
			    if(!empty($ad->user_id) and  $options->get('system.common.send_enquiry_email_to_property_owner','yes')=='yes'){
			        $customer = $ad->Customer;
			        $customer_email =  !empty( $customer->contact_email  ) ?  $customer->contact_email :  $customer->email;
			        if($customer->user_type=='A'){
			         $customer_name  = $customer->fullName ;
			        }
			        else{
			        $customer_name  = $customer->company_name ;
			        }
			        if(!empty($ad) and  $ad->section_id=='3'){
			             if(!empty($ad->contact_name)){
			                 $customer_name = $ad->contact_name ;
			             }
			             if(!empty($ad->contact_email)){
			                 $customer_email  =  $ad->contact_email ;
			             }
			            
			        }
			        $send_Array = array_replace( array(Yii::app()->options->get('system.common.contact_email')=>'Admin'),array($customer_email=>$customer_name)); 
			        if(!empty($customer->parent_user)){
    			        $parent =  ListingUsers::model()->findByPk($customer->parent_user);
    			        if( $parent){
    			             $customer_email1 =  !empty( $parent->contact_email  ) ?  $parent->contact_email :  $parent->email;
    			             $send_Array[$customer_email1] = $parent->company_name ; 
    			        }
			        }
			        
			        $usersList =  $send_Array ; 
			    }
			    else{
				    $usersList = array(Yii::app()->options->get('system.common.contact_email')=>'Admin') ; 
			    }
			}
			else{
				$usersList = array_replace( array(Yii::app()->options->get('system.common.contact_email')=>'Admin')  ); 
			} 
			$common_name =  Yii::app()->options->get('system.common.site_name');
			$emailTemplate = str_replace('[CONTENT]', $emailTemplate, $emailTemplate_common);
			
			
			
			if(!empty($usersList)){
				foreach($usersList as $k=>$v){
				 
					$status = 'S'; 
					$options	= Yii::app()->options;	
					$email = new TransactionalEmail();
					$email->sendDirectly = true;
					$email->to_name      = $v;
					$email->to_email     = defined('MY_EMAIL') ? MY_EMAIL : $k;
					$email->from_name    = $options->get('system.common.site_name', 'Marketing website');
					$email->subject      = $subject;
					$email->body         = $emailTemplate;
					$email->save(); 
					
				}
			}
			$liamamodel = new ContactUs();
			$adModel                =    new PlaceAnAd();
			$criteria               =    $adModel->findAds(array('_sec_id'=>3),false,1); 
			$criteria->compare('t.id',(int)$this->ad_id);
			$adModel 			=   $adModel->find($criteria);
			if(!empty($adModel)){
			 
		}
			 
	 return true;
       
     
	}
	public function getAdTitle(){
		if(!empty($this->ad_id)){
		$ad =$this->ad ; 
		return '<a href="'.$ad->DetailUrlAbsolute.'" target="_blank">'.$ad->ad_title.'</a>';
		}
		else{
			return '-';
		}
	}
	public function getAdTitleBackend(){
		if(!empty($this->ad_id)){
		$ad =$this->ad ; 
		return  CHtml::link(@$ad->ad_title,  Yii::app()->apps->getBaseUrl("index.php/details/".$ad->slug)) ;
		}
		else{
			return '-';
		}
	}
        public function findEnquiry($formData=array(),$count_future=false ,$returnCriteria =false){
		  
		$criteria=new CDbCriteria;
		$criteria->select = 't.*,ads.ad_title,ads.slug as ad_slug ,ads.section_id as ad_section, cn.cords, cn.country_name'; 
        $criteria->compare('contact_type','ENQUIRY');
        $criteria->join = ' INNER   JOIN {{place_an_ad}} ads on ads.id = t.ad_id and  ads.isTrash="0" ';
        $criteria->join .= ' LEFT JOIN {{countries}} cn on cn.country_id = ads.country ';
        $criteria->join .= ' LEFT JOIN {{listing_users}} usr on usr.user_id = t.user_id ';
   
        if(Yii::App()->isAppName('backend')){
				$criteria->condition .= ' and  t.ad_id IS NOT NULL  ';
		
		}
        if(!empty($this->user_id)){
			$criteria->condition .= ' and CASE WHEN t.ad_id IS NOT NULL THEN ads.user_id =:user_id ELSE t.user_id =:user_id END  ';
			$criteria->params[':user_id'] = $this->user_id ; 
		}
		$order  = 't.id   desc ';		   
	    $criteria->order  =   $order; 		
		$criteria->limit  = Yii::app()->request->getQuery('limit','10');
		$criteria->offset = Yii::app()->request->getQuery('offset','0');
		if($returnCriteria)	 { return  $criteria; }
		if(!empty($count_future)){
			$Result = self::model()->findAll($criteria);
			$criteria->offset = $criteria->limit+$criteria->offset   ;
			$criteria->select = 't.id'; 
			$criteria->limit = '1'; 
			$future_count = self::model()->find($criteria);
			return array('result'=>$Result,'future_count'=>$future_count );
		}
		else{
			return  self::model()->findAll($criteria)  ; 
		 
		}
	 
	}
		public function getShortName($length = 40)
    {
        if(empty($this->meassage)){ return 'No details entered'; }
        return StringHelper::truncateLength($this->meassage, (int)$length);
    }
       public function getDetailUrlAd(){
		 
		if($this->ad_section=='3'){
			$url =   MAIN_SITE_PATH_BASE_COUNTRY.strtolower($this->cords).'/index.php/property/'.$this->ad_slug ;
		}
		 else{
				$url =   MAIN_SITE_PATH_BASE_COUNTRY.strtolower($this->cords).'/index.php/property/'.$this->ad_slug ;
		 }
		return CHtml::link($this->ad_title,$url,array('target'=>'_blank'));
	}
    
    public function sectionArray(){
		return array(
		'1' => 'Buy',
		'2' => 'Rent',
		'3' => 'New Development',
		);
	}
    public function getsectionTitle(){
		 $ar = $this->sectionArray();
		 return isset($ar[$this->ad_section]) ? $ar[$this->ad_section] : '-';
	}
		 public function total_view()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;
 
		$criteria->join = 'INNER JOIN {{place_an_ad}}  ad on ad.id = t.ad_id   ';
		$criteria->join .= 'INNER JOIN {{listing_users}}  usr on usr.user_id = ad.user_id   ';
			$criteria->condition  = '    usr.user_id = :me2 or usr.parent_user =:me2 '; 
			$criteria->params[':me2'] =   (int) Yii::app()->user->getId() ; 
		 return  $this->count($criteria); 
		  
    }
    public function getApprovalloan(){
        return array(
            '1' => 'Yes' ,
            '2'=>  'No' ,
            '3' =>  'Rather not say' , 
            );
    }
     public function getApprovalloanTitle($id){
         $ar = $this->getApprovalloan();
         return isset($ar[$id]) ? $ar[$id] : '-'; 
    }
}
