<?php defined('MW_PATH') || exit('No direct script access allowed');
 
 
class ListingsController extends  Controller
{
	 
    public $state_model;
    public $city_model;
    public $city_list;
    public $category; 
    	public $state_list;
	public $developer_list;
    public function setForm($formData){
         if(isset($formData['state_slug']) and !empty($formData['state_slug'])){
	         $stateModel = States::model()->findbyAttributes(array('slug'=>$formData['state_slug']));
		     if($stateModel){ 
		        $this->state_model = $stateModel;
    			$formData['_state_id']  = $stateModel->state_id ;
    			$this->city_list = CHtml::listData(City::model()->FindCities($stateModel->state_id),'slug','city_name');
		    }
	      }	
        return $formData;
    }
    function right_replace($string, $search, $replace)
    {
    $offset = strrpos($string, $search);
    if ($offset !== false)
    {
        $length = strlen($search);
        $string = substr_replace($string, $replace, $offset, $length);
    }
    return $string;
    }
	public function actionIndex($view='grid')
    {       
            define('OFFPLAN',1);
            $this->state_list = States::model()->cacheclistStates();
		$this->developer_list = Developers::model()->cacheclistDeveloper();
		$this->category  = Category::model()->developmentCatogoriescache();
            $generated_string1 = array_filter(explode('/',Yii::app()->request->url)); 
            $generated_string = array_shift(array_values($generated_string1)); 
            $generated_string = explode('?',$generated_string);
            $generated_string = $generated_string['0']; 
            $generated_string =   ucwords(strtolower(Yii::t('app',$generated_string,array('?view=list'=>'','-'=>' ','.html'=>'','-city'=>' ','/'=>'','?view=map'=>'')))); 
            $generated_string = Yii::t('app',$generated_string,array('For Sale'=>'for sale',' In '=>' in ',' By '=>' by '));
            $pageTitle = $generated_string=='Properties for sale'?  'Offplan Projects in UAE ' : $generated_string ;
            if(isset($_GET['state_slug']) and isset($_GET['city'])){
                $state  = ucwords(strtolower($_GET['state_slug']));
                $pageTitle =   $this->right_replace($pageTitle,' '.$state,', '.$state);
            }
            
			$categoriesModel             = $this->category;
			$formData = $_GET; 
	        $formData['_sec_id'] = 3; 
		 
			$limit = '30'; 
			$formData = $this->setForm($formData);
	
            $modelCritera = PlaceAnAd::model()->findAds($formData, $count_future = false, 1, $calculate = false);
                   $modelCritera->join        .=     ' left join {{developers}} dvp ON dvp.developer_id = t.developer_id   ';
                 $modelCritera->select      .=    ',case when dvp.developer_name is not null then dvp.developer_name else t.d_name  end as  developer_name,case when dvp.logo is not null then dvp.logo else t.d_logo  end as  d_logo';
  
            $adsCount = PlaceAnAd::model()->count($modelCritera);
            
            if($view!='map'){
            $modelCritera->limit = $limit;
            $pages = new CPagination($adsCount);
            $pages->pageSize = $limit;
            $pages->applyLimit($modelCritera); 
            }
            
            $ads = PlaceAnAd::model()->findAll($modelCritera);
             
             define('LISTING',1);
        $this->setData(array(
            'pageMetaTitle' =>    Yii::t('trans','{title}',array('{title}'=>$pageTitle)), 
            'pageMetaKeyword'   => $this->generateCommon('home_meta_keywords', 'Appointments online'),
            'pageMetaDescription'   => $this->generateCommon('home_meta_description', 'Appointments online'),
            'pageHeading'   => Yii::t('users', 'My Account'),
        )); $apps = $this->app->apps;
        //$this->getData('pageStyles')->add(array('src' => ''));
            $this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/js/jquery.typeahead.min.css')));
    $this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/jquery.typeahead.min.js')));
    
         
    
         define('NOFIXED',1); 
         if(empty($view)){ $view='grid'; }
          $view_file = 'index';
         if($view=='map'){
             $view_file = 'map_new';define('NO_FOOTER',1);
         }define('WHATSAPP',1);
         $communities_selected =  $this->autocomplete_community($_GET);
        $this->render($view_file, compact('categoriesModel' ,'ads' , 'limit', 'formData' , 'adsCount', 'pages','pageTitle','view','communities_selected'));  
       
    } 
  public function actionFind()
    {
       
         $post = array();
            parse_str(Yii::t('app',$_GET['data'],array(';'=>'')), $post);
            $post =array_filter($post); 
        if(!empty($post)){
             
            unset($post['csrf_token']);$html =''; 
            if(isset($post['view'])  ){
                if($post['view']!='grid'){
                $html ='?view='.$post['view'];
                }
                  
                unset($post['view']);
            }
            if(isset($post['keyword'])  ){
                if(empty($html)){
                $html ='?keyword='.$post['keyword'];
                }
                else{
                     $html .='&keyword='.$post['keyword'];
                }
                  
                unset($post['keyword']);
            } 
        $this->redirect($this->app->createUrl('listings/index',array_filter($post)).$html); 
        }else{
            $this->redirect($this->app->createUrl('listings/index'));
        }
    }
    	function returnImg($img,$count,$width=600){
		
	$img_link = $this->app->apps->getBaseUrl('uploads/images/'.$img); 
//	$img_link = 'https://www.ajmanproperties.ae/assets/easyimage/4/44c6af3a13ef586629c6a9826accf409.jpg';
	return  ' class="photo'.$count.' photo-layer lozad" data-background-image="'.$img_link.'" ';
	}
		public function getTag($i=null,$m=null){
	    return $m;
	}
      public function actionProject($slug=null)
    {  		
        define('NOFIXED',1);define('WHATSAPP',1);
          $brochure = new Brochure();
		if (isset($_POST['ajax'])) {
		echo CActiveForm::validate($brochure);
		Yii::app()->end();
		}
		    $criteria=new CDbCriteria;
			$criteria->select = 't.*,  st.slug as state_slug  ,usr.first_name,usr.last_name,usr.phone as user_number,usr.email as email  ,usr.email as contact_email  ,usr.address as user_address,  (SELECT image_name FROM {{ad_image}} img  WHERE  img.ad_id = t.id and  img.status="A" and  img.isTrash="0" limit 1 )   as ad_image';
			$criteria->condition = '1';
			if(Yii::app()->request->getQuery('showTrash','0')=='0'){
		    	$criteria->compare('t.isTrash','0');
				$criteria->compare('t.status','A');
			}
		 
			//$criteria->join  .= ' left join {{section}} sec ON sec.section_id = t.section_id ';
			//$criteria->join  .= ' left join {{category}} cat ON cat.category_id = t.category_id ';
			//$criteria->join  .= ' left join {{subcategory}} sub ON sub.sub_category_id = t.sub_category_id ';
			//$criteria->join  .= ' left join {{community}} com ON com.community_id = t.community_id ';
			//$criteria->join  .= ' left join {{sub_community}} sub_com ON sub_com.sub_community_id = t.sub_community_id ';
			$criteria->join  .= ' left join {{states}} st ON st.state_id = t.state '; 
			//$criteria->join  .= ' left join {{countries}} con ON con.country_id = t.country ';
			$criteria->join  .=   ' INNER JOIN {{listing_users}} usr on usr.user_id = t.user_id ';
			
		 
			  $criteria->select .= ',st.state_name as state_name,ad_title as    ad_title2  ';
		 
			
			if(Yii::app()->user->getId()){
			$criteria->select .= ' ,fav.ad_id as fav ';
			$criteria->join  .= ' left join {{ad_favourite}} fav ON fav.ad_id = t.id and fav.user_id =:user_me';
			$criteria->params[':user_me'] = Yii::app()->user->getId();
			}
			$criteria->condition .= ' and usr.status = "A" and usr.isTrash="0"' ;
			$criteria->condition .= ' and t.slug=:slug ' ;
			$criteria->params[':slug'] = $slug;
			$model = PlaceAnAd::model()->find($criteria);
			if(empty($model)){
				throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
			}
	       
	        $adModel                =    new PlaceAnAd();
            $criteria               =    $adModel->findAds(array('_sec_id'=>3),false,1);
            $criteria->join        .=     ' left join {{developers}} dvp ON dvp.developer_id = t.developer_id   ';
            $criteria->select      .=    ',case when dvp.developer_name is not null then dvp.developer_name else t.d_name  end as  developer_name,case when dvp.logo is not null then dvp.logo else t.d_logo  end as  d_logo';
            $criteria->condition       .=    ' and t.is_new="1"   and  t.id = (select min(id) from {{place_an_ad}} where id > "'.$model->id.'") '; 
            $next_project =   $adModel->find($criteria); 
            if(empty($next_project)){
              $adModel                =    new PlaceAnAd();
            $criteria               =    $adModel->findAds(array('_sec_id'=>3),false,1);
            $criteria->join        .=     ' left join {{developers}} dvp ON dvp.developer_id = t.developer_id   ';
            $criteria->select      .=    ',case when dvp.developer_name is not null then dvp.developer_name else t.d_name  end as  developer_name,case when dvp.logo is not null then dvp.logo else t.d_logo  end as  d_logo';
            $criteria->condition       .=    '  and t.is_new="1"   and  t.id =  (select max(id) from {{place_an_ad}} where id <  "'.$model->id.'")'; 
            $next_project =   $adModel->find($criteria);    
            }
            
	       
	      $request    = Yii::app()->request;
	       if ($request->isPostRequest && ($attributes = (array)$request->getPost($brochure->modelName, array()))) {
	       $notify  = Yii::app()->notify;;
            $brochure->attributes = $attributes;
             $brochure->ad_id = $model->id;
            if (!$brochure->save()) {
                
                  $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            } else { 
                 if(!empty($model->broucher) or !empty($model->b_url)){ 
                   
                     $model->openBrouchre;
                 }else{
                      $notify->addSuccess('<h3>Thank you for your interest</h3><p>One of our agent will contact you soon and send you full brochure link.</p>');
                 }
                $this->refresh();
            }

            Yii::app()->hooks->doAction('controller_action_save_data', $collection = new CAttributeCollection(array(
                'controller'=> $this,
                'success'   => $notify->hasSuccess,
                'article'   => $article,
            )));

            if ($collection->success) {
                $this->redirect(array('articles/index/id/'.$article->category_id));
            }
        }
		
			$this->setData(array(
                    'pageMetaTitle'         => Yii::t('app', '{name} | {p}', array('{name}' =>$model->adTitle   ,'{p}'=> $this->project_name )), 
                    'pageMetaDescription'   => $model->ShortDescription,
                    'image'   =>     $model->ad_image ,
                    'title'   =>     $model->ad_title ,
                    'shareUrl' =>    $model->detailUrlAbsolute,
                    'description'   =>   $model->ShortDescription ,
                     
                ));
		 $floor = $model->adFloorPlans;
		$listingUsers = new ListingUsers();
		$listingUsers->first_name  = $model->first_name;
		$listingUsers->last_name   = $model->last_name;
	 
 
		$listingUsers->email  = $model->email;
	//	$listingUsers->contact_email  = $model->contact_email;
		$user_array = array(
		//'user_type' => $listingUsers->TypeTile,
		//'user-name' => $listingUsers->fullName,
 

		);
		  $type_is = $model->all_property_types_details();
	 $type_is_c = $model->all_property_types_detailsgroup();
		  $overViewhtm  = ''; 
		  $proprty_type_title =  'Property Type' ;
		  $bed_title =  'Bedrooms' ;
		  $size_title =  'Size';
		   if(!empty( $type_is_c)){
			   foreach($type_is_c as $k=>$v){
				   if($k!='0'){ continue; }
				   $c= $v->type_id_c>1 ? '1':''; 
				   $overViewhtm .=' <li><label><i class="bi   bi-circle"></i> '.$proprty_type_title.'</label>'.$v->type->categoryIdLanItSelf($c) .'</li>';
				   if(!empty($v->bed)){
				       if(!empty( rtrim($v->bed_c,','))){
					    if($v->bed=='14'){ $tit = '13+'; }else{ $tit = !empty($v->bed_c) ? rtrim($v->bed_c,','):''; }
				      
					    $overViewhtm .='<li><label><i class="bi   bi-circle"></i> '.$bed_title.'</label>'. $tit .' </li>'; 
				       }
				   }else if(!empty($v->size) and $v->size != '0.00'){
					   $overViewhtm .='<li><label><i class="bi   bi-circle"></i> '.$size_title.'</label>'.number_format( Yii::t('app',$v->size,array('.00'=>'')) ,0,'.',',').' Sq.Ft.</li>'; 
				   }
				  
			   }
		   } 
		  
		  $type_is_overview = $model->payment_plan; 
		  $faq = AdFaq::model()->findAllByAttributes(array('ad_id'=>$model->id));
		  $propertyTypes = '';
		  
		  if(!empty($type_is)){
			  foreach($type_is as $k=>$v){
				  $name = $v->type->categoryIdLanItSelf() ; 
				  $propertyTypes[$name] = $name ; 
			  }
		  }	
		$images = $model->all_images();
			 $size = sizeOf($images);
		$array=  $model->detailList2();
		 	 define('OWL','1'); $apps = Yii::app()->apps;    
		 	$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/jAlert-v3.min.js?q=1')));
		     $this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/jAlert-functions.min.js')));
        $this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/detail_project.css?q=5')));
         $this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/jAlert-v3.css')));
          $this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/js/swiper/swiper-bundle.min.css')));
    $this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/swiper/swiper-bundle.min.js')));
		 $this->render( 'detail/index',compact('images','overViewhtm','size','model','brochure','floor','user_array','listingUsers','array','b_1','type_is' ,'faq','propertyTypes','payment_plan','type_is_overview','next_project'));
	   //$this->render( '_new_style_project',compact('model','floor','user_array','listingUsers','array','b_1'));
    }
    public function actionValidateprojectenquiry(){
		$model = new ProjectEnquiry;
		if (isset($_POST['ajax'])) {
		echo CActiveForm::validate($model);
		Yii::app()->end();
		}
	} 
		public function actionSendprojectenquiry(){
		$request    = Yii::app()->request;
		$model  = new ProjectEnquiry();
		if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			  $model->attributes = $attributes;
			  if(!$model->save()){
				  echo json_encode(array('status'=>'0','msg'=>'<div class="alert alert-danger"><strong>Error!</strong> '.CHtml::errorSummary($model).'. </div>'));
				  Yii::app()->end();
			  }
			  else{
				  echo json_encode(array('name'=> $model->name, 'status'=>'1','msg'=> Yii::t('trans','<strong>{s}</strong> {m}',array('{s}'=> 'Success' ,'{m}'=> 'Succesfully submited' ))));
				  Yii::app()->end();
			  }
		 
		}
	}
	 public function autocomplete_community($GET){
              $item = array();
       if(isset($GET['community']) and !empty($GET['community'])){
                $ar = array_filter(explode('|',$GET['community']));
                $criteria = Community::model()->search(1);
                $criteria->select = 't.slug,t.community_id,t.community_name,city0.city_name';
                $criteria->order = 'community_name asc';
                $criteria->addInCondition('t.slug',$ar);
                $communities = Community::model()->findAll($criteria);
            
                if($communities){
                    foreach($communities as $k=>$v){
                    $item[] = array(
                    "name"          => $v->community_name,
                    "city"          => $v->city_name,
                    "id"            => $v->slug,
                    "typr"         => "com"
                    );
                }
       }
       }
       if(isset($GET['subcommunity']) and !empty($GET['subcommunity'])){
                $ar = array_filter(explode('|',$GET['subcommunity']));
                $criteria = SubCommunity::model()->search(1);
                $criteria->select = 't.slug,t.sub_community_name,community0.community_name as sub_community_id';
                $criteria->order = 'sub_community_name asc';
                $criteria->addInCondition('t.slug',$ar);
                $sub_communities = SubCommunity::model()->findAll($criteria);
             
                if($sub_communities){
                    foreach($sub_communities as $k2=>$v2){
                    $item[] = array(
                        "name"          => $v2->sub_community_name,
                        "city"          => $v2->sub_community_id,
                        "id"            => $v2->slug,
                        "typr"         => "sub"
                    );
                    }
                 }
        }
	   
	   
        return $item; 
      }
       function generateImage($image=null,$width=null,$height=null){
	 
	   return $image; 
			
   }
}
