<?php defined('MW_PATH') || exit('No direct script access allowed');

function myFilter($var){
		return ($var !== NULL && $var !== FALSE && $var !== '');
	}
  
 
class OffplanController extends Controller
{
 
    /**
     * Define the filters for various controller actions
     * Merge the filters with the ones from parent implementation
     */
     public $Controlloler_title= "Ad";
     public $focus = "country";
     	public $member;
     	public $options;
	public $app;
	public $tag;
	public $project_name  ;
	public function getTag($i,$m){
	    return $m;
	}
     public function init()
    {
		  
	 
		define('OFFPLAN',1);
		$this->app = Yii::app();
		$this->options = $this->app->options;
		$this->tag = $this;
		$this->project_name =  $this->tag->getTag('site_name',$this->options->get('system.common.site_name',''));
		
		parent::Init();
	     
        
    }
   public function actionIndex($user_id=null,$tag=null,$typ=null)
    {
         $request = Yii::app()->request;
         $notify = Yii::app()->notify;
         $model = new PlaceAnAd('serach');
         if($request->isPostRequest) {
                $sortOrderAll = $_POST['priority'];
				if(count($sortOrderAll)>0)
				{
					foreach($sortOrderAll as $menuId=>$sortOrder)
					{
						$model->isNewRecord =true; 
						$model->updateByPk($menuId,array('priority'=>$sortOrder)); 
					}
				}
				  $notify->addSuccess(Yii::t('app', 'Priority successfully updated!'));
				  $this->redirect(Yii::app()->request->urlReferrer) ;
        }
       
        $model->unsetAttributes();
        $model->attributes = (array)$request->getQuery($model->modelName, array());
        $model->isTrash = '0';
        if(!empty($user_id)){$model->user_id = $user_id; 
        $user = ListingUsers::model()->findByPk($user_id);
        if(empty($user)){throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.')); }
        $this->Controlloler_title = $user->mainTitle .' Ads ';
        }
         if(!empty($tag)){
				 switch($tag){
					 case 'R':
					  $model->recmnded = "1";
					 break;
					 case 'P':
					 $model->promoted = "1";
					 break;
					 case 'F':
					  $model->featured = "Y";
					 break;
				 }
			 }
			 if(!empty($typ)){ $model->category_id = $typ; }
			
	$model->section_id = 3  ;
			   $this->Controlloler_title = ' New Developments ';
			 
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title} List"), 
            'pageHeading'       => Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title} List"),
            'pageBreadcrumbs'   => array(
                Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
                Yii::t('app', 'View all')
            )
        ));
        $this->render('list', compact('model','development'));
    }
    
     public function  beforeAction($action)
    {   
		 
				if(in_array($action->id,array('create','success','update','success_edit','choose_location','preview'))){
				$apps = Yii::app()->apps;
	 
				$this->getData('pageStyles')->add(array('src' =>$apps->getBaseUrl('backend/assets/css/styles/jqx.base.css')));
				$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/table_common.css?q=3')));
				$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('backend/assets/css/styles/jqx.energyblue.css')));
				$this->getData('pageStyles')->add(array('src' =>  'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css'));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jqwidgets/jqxcore.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/custom.js?q=6')));
				$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/property_detail.css?q=1')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jqwidgets/jqxbuttons.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jqwidgets/jqxscrollbar.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jqwidgets/jqxlistbox.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jqwidgets/jqxcombobox.js')));
				$this->getData('pageScripts')->add(array('src' =>$apps->getBaseUrl('backend/assets/js/jqwidgets/jqxdropdownlist.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/jquery.autocomplete.js')));
				$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/select2.min.css')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/select2.min.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/select2script.js')));
				}
					if(in_array($action->id,array('create' ,'update' ))){
			
				$this->getData('pageScripts')->mergeWith(array(
					array('src' =>  Yii::app()->apps->getBaseUrl('assets/js/cropper/dist/cropper.min.js'), 'priority' => -100),
					array('src' =>  Yii::app()->apps->getBaseUrl('assets/js/_imageCrop.js?q=1'), 'priority' => -100),
				));
				  $this->getData('pageStyles')->mergeWith(array(
			array('src' =>  Yii::app()->apps->getBaseUrl('assets/js/cropper/dist/cropper.min.css'), 'priority' => -100),
		 
		));
				}
				return parent::beforeAction($action);
	}
	
		public function actionSimple($section=null,$type=null,$category=null,$state=null,$city=null,$id=null,$pot=null )
    {  
		

	 
		if(empty($pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
		$goto_ad = false;
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $sectionModel =  Section::model()->ListData();
        $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => 'List Off-Plan Property ' ,'{p}'=> Yii::app()->options->get('system.common.site_name'))),   
			'pageHeading'       => Yii::t(Yii::app()->controller->id, "List Off-Plan Property"),
			 
        ));
        $view = '_section';
        if(!empty($section)){
			$sectionM =  Section::model()->findByAttributes(array('slug'=>$section));
		}
		 $goto_ad = true;	 
	 
		/*
		if(!empty($state)){ 
			 
			$statesM2 = States::model()->findByAttributes(array('slug'=>$state));			 
		}
	 
		if(!empty($statesM2)){ 
			
				$cityM   = City::model()->ListDataForJSON($statesM2->state_id,false) ;
				if(!empty($cityM )){
					
				 
					$view  = '_city';
				}
				else{
					 
					$goto_ad = true;
				}
		}
		if(!empty($city)){ 
			 
			$cityM2 = City::model()->findByAttributes(array('slug'=>$city));
			$goto_ad = true;			 
		}
		*/
	 
		if($goto_ad ){	
				$ar = $this->renderPartial('root.apps.backend.views.offplan.new._breadcrumb', compact('sectionModel','sectionM','list_typeModel','type','typeM','view','categoryM','categoryM2','statesM','statesM2','cityM','cityM2','id','pot'),true); 
			    Yii::app()->user->setState("place_holder".$pot, $ar);
				$model = new PlaceAnAd();
				if($id){
					$model =	PlaceAnAd::model()->findByPk($id);
					if(empty($model)){
						throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
					}
				}
				$apps = Yii::app()->apps;
					$sec_attributes =   Yii::app()->user->getState("attribute_array".$pot);
					 
					if($sec_attributes){
						 
						foreach($sec_attributes as $field=>$vl){
						$model->$field = $vl;
						}
					}
					 			
					
				$model->section_id = $sectionM->section_id ; 
				$model->listing_type = $typeM->category_id ; 
	
				$model->category_id = $categoryM2->category_id ; 
				
				$default_state = States::model()->findByPk('55367');
				if(empty($default_state)){ throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));}
				$model->country  = $default_state->country_id ; 
				if(empty($model->state)){
				$model->state  =  $default_state->state_id ; 
				}
				//$model->city  = @$cityM2->city_id ;  
			  
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/myAjax.js')));
				$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/dropzone.min.js')));
				$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('backend/assets/css/dropzone.css')));
				
					 		$model->dynamic  =  true; 
					//$model->dynamicArray = array_merge(array_diff((array)$fields,$model->dynamicFields()));
					$model->dynamicArray =  $model->getExcludeArray((array)$fields) ;;
					//$model->_notMadatory =  $not_mandatory_fields;
				
					  if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
					 
				     $image_array  = array() ;    
					
					 if($id and empty($model->image)){
							    
							if(isset($model->adImages) )
							{
							foreach($model->adImages as $k=>$v)
							{
							$image_array[] = $v->image_name;
							}
							}
					 } 
					 else if(!empty($model->image)){
							$exp =  explode(",",$model->image);
							if($exp)
							{
							foreach($exp as $k=>$v)
							{
							if($v!="")
							{
							$image_array[] = $v;
							}
							}
						  }
					}
			
				 	$this->render('root.apps.backend.views.offplan.details', compact('model',"category","fields","image_array"));
					Yii::app()->end();
		 }	
        $apps = Yii::app()->apps;
        $this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('assets/css/table_common.css?q=3')));
        $this->render('root.apps.backend.views.offplan.new._pick_section', compact('sectionModel','sectionM','list_typeModel','type','typeM','view','categoryM','categoryM2','statesM','statesM2','cityM','id','pot'));
    }
    public function generateLink($section=null,$type=null,$category=null,$state=null,$city=null,$id=null){
		    $pot = Yii::app()->request->getQuery('pot','');
		     if(!Yii::app()->user->hasState("attribute_array".$pot)){
				throw new CHttpException(404, Yii::t('app', 'Pot unable to setd.'));
			}
			$model = new PlaceAnAd();
			 $attributes = Yii::app()->user->getState("attribute_array".$pot); 	    
			 $model->attributes =  $attributes ; 
			 			 
			if($section==null){
				$sectionM = Section::model()->findByPk($model->section_id);
				if($sectionM){
					$section = $sectionM->slug;
				}
			}
			if($type==null){
				$typeM = MainCategory::model()->findByPk($model->listing_type);
				if($typeM){
					$type = $typeM->slug;
				}
			}
			if($category==null){
				$categoryeM =  Category::model()->findByPk($model->category_id);
				if($categoryeM){
					$category = $categoryeM->slug;
				}
			}
			
			if($state==null){
				$stateM =  States::model()->findByPk($model->state);
				if($stateM){
					$state = $stateM->slug;
				}
			}
			if($city==null){
				$cityM =  City::model()->findByPk($model->city);
				if($cityM){
					$city = $cityM->slug;
				}
			}
			
			$this->actionSimple($section,$type,$category,$state,$city,$id ,$pot );
			Yii::app()->end();
		 
	}
 
       public function actionCreate($section='development',$type=null,$category=null,$state=null,$city=null,$id=null,$pot=null,$goto=null)
    {   
        $request = Yii::app()->request;
        if(!$request->isPostRequest){
			    if(!empty($pot) and Yii::app()->user->hasState("attribute_array".$pot) and empty($goto) ){
					$this->generateLink();
				}
				else{
				  
					if($section==null){
						$pot  = rand(10,1000) ; 
						//Yii::app()->session->remove(Yii::app()->user->getStateKeyPrefix() . 'attribute_array');
					}
				 
					$this->actionSimple($section,$type,$category,$state,$city,$id,$pot);
				}
				Yii::app()->end();
		}
		if(empty($pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
        $notify = Yii::app()->notify;
        $model = new PlaceAnAd();
        $country_val =  $this->options->get('system.common.default_listing_country');
        $countryModel =  Countries::model()->findByAttributes(array('cords'=> $country_val));
        if(!empty( $countryModel)){ $model->country = $countryModel->country_id;  }
        $country = Countries::model()->ListDataForJSON();
        if(!empty($model->country)){
			$state   = States::model()->ListDataForJSON($model->country) ;
	    }
	    else{
			 $state   = CJSON::encode( array('0'=>"&nbsp;Select Region")) ; 
		}
      
        $section = Section::model()->ListDataForJSON_ID();
        $list_type = Category::model()->ListDataTypeForJSON_ID();
         
        $image_array=array();
	    $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => $this->tag->getTag('list-your-property','List Off-Plan Property') ,'{p}'=> $this->project_name)),   
			'pageHeading'       =>$this->tag->getTag('list-your-property','List Off-Plan Property'),
			 
        ));
      //  print_r($_POST);exit;
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			
	  
  
             	$model->dynamic  =  true; 
			//$model->dynamicArray = array_merge(array_diff((array)$fields,$model->dynamicFields()));
			$model->dynamicArray =  $model->getExcludeArray((array)$fields) ;;
		 			
					  
			$model->country = $attributes["country"];
			$model->state = $attributes["state"];
			$model->listing_type = $attributes["listing_type"];
			$model->city = $attributes["city"];
	 
			//$model->city = $attributes["city"];
			$model->sub_category_id = $attributes["sub_category_id"];
			$model->category_id = $attributes["category_id"];
			$model->section_id = $attributes["section_id"];
			 
			if($model->section_id=='3'){

					$model->dynamicArray =array();
			}
			if(isset($attributes['ad_title']))
			{
			    $model->attributes= $attributes;
			    if (isset(Yii::app()->params['POST'][$model->modelName]['ad_description'])) {
				$model->ad_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['ad_description']);
				}
                if (isset(Yii::app()->params['POST'][$model->modelName]['c_description'])) {
				$model->c_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['c_description']);
				}
				
				if (isset(Yii::app()->params['POST'][$model->modelName]['header_content'])) {
				$model->header_content =  Yii::app()->params['POST'][$model->modelName]['header_content'] ;
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['footer_content'])) {
				$model->footer_content =  Yii::app()->params['POST'][$model->modelName]['footer_content'] ;
				}
                if (isset(Yii::app()->params['POST'][$model->modelName]['caption'])) {
                $model->caption = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['caption']);
                }
				
				$model->category_id =  $category->category_id;;
			 
				if(isset($attributes["model"]))
				{
				$model->model = ($attributes["model"]==0)? 'Others': $attributes["model"] ;
				}
				
					if (Yii::app()->request->isAjaxRequest) {
					echo CActiveForm::validate($model);
					Yii::app()->end();
					}
				
				//$model->dynamicArray ="";
				if($model->validate())
				{
					       
						
								$model->amenities = Yii::app()->request->getPost("amenities");
						
								$exp =  explode(",",$model->image);
								if($exp)
								{
									foreach($exp as $k=>$v)
									{
										if($v!="")
										{
											$image_array[] = $v;
										}
									}
								}
								
							 
								$filter_array = array_filter(array_merge($model->attributes,(array)array('amenities'=>$model->amenities,'image'=>$model->image,'floor_plan'=>$model->floor_plan ,'payment_plan'=>!empty($model->payment_plan) ?  serialize($model->payment_plan) : '')),'myFilter');
							     
							    Yii::app()->user->setState("attribute_array".$pot,$filter_array);
							    
							    
								$this->redirect(Yii::app()->createUrl($this->id.'/choose_location',array('pot'=>$pot)));
							
							 
				 }
				 else
				 {
					 
                     $notify->addError(Yii::t('app',  'Your form has a few errors, please fix them and try again!'));
					 $model->amenities = Yii::app()->request->getPost("amenities");
					 $model->payment_plan = !empty($model->payment_plan) ?  serialize($model->payment_plan) : '';
						$exp =  explode(",",$model->image);
						if($exp)
						{
							foreach($exp as $k=>$v)
							{
								if($v!="")
								{
									$image_array[] = $v;
								}
							}
					    }
				 }
				 
				 
				 
 
			}
			$model->sub_category_id = $attributes["sub_category_id"];
			$this->actionDetails($model,$subcategory,$category,$fields,$image_array,$pot);
           
        }
        else
        {
			$this->render('form', compact('model',"country","section","state",'list_type'));
		}
        
 
        
    }
  
     public function actionDetails($model,$subcategory,$category,$fields,$image_array,$pot)
    {
		$apps = Yii::app()->apps;
		$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/myAjax.js')));
		$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('backend/assets/css/dropzone.css')));
        $this->render('root.apps.backend.views.offplan.details', compact('model','subcategory','category',"fields","image_array",'hooks','pot'));
    }
     public function actionDetails_2($model,$subcategory,$category,$fields,$image_array,$jsonData)
    {
		 
		$this->getData('pageScripts')->add(array('src' => AssetsUrl::js('myAjax.js')));
        $this->render('location_view', compact('model','subcategory','category',"fields","image_array","jsonData"));exit;
    }
     public function actionDetails_edit($model,$subcategory,$category,$fields,$image_array,$pot)
    {
		$apps = Yii::app()->apps;
		$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('backend/assets/js/myAjax.js')));
		$this->getData('pageScripts')->add(array('src' => $apps->getBaseUrl('assets/js/dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' => $apps->getBaseUrl('backend/assets/css/dropzone.css')));
        $this->render('root.apps.backend.views.offplan.details', compact('model','subcategory',"category","fields","image_array",'pot'));
    }
     public function actionFindOnMap()
    {
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $model = new PlaceAnAd();
      //  $subcategory= SubCategory::model()->FindSubategory("12");
         
        $this->setData(array(
            'pageMetaTitle'     =>  Yii::t(Yii::app()->controller->id, "Create new {$this->Controlloler_title}"), 
            'pageHeading'       => Yii::t(Yii::app()->controller->id, "Create new {$this->Controlloler_title}"),
            'pageBreadcrumbs'   => array(
                Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
                Yii::t('app', 'Create new'),
            )
        ));
        $this->render('details', compact('model'));
    }
    
    
    /**
     * Update existing user
     */
      public function actionUpdate($id=null,$section=null,$type=null,$category=null,$state=null,$city=null,$pot=null,$goto=null)
    {
		if(empty($pot)){  $pot = rand(1,100000); } 
         $model = PlaceAnAd::model()->findByPk($id);
         if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
       
        $request = Yii::app()->request;
        if(!$request->isPostRequest){
			
		    if(!empty($pot) and Yii::app()->user->hasState("attribute_array".$pot) and empty($goto) ){
				 
					$this->generateLink($section=null,$type=null,$category=null,$state=null,$city=null,$id);
			 }
			 else{
			if($section==null and empty($goto)){
				 
				$sectionM = Section::model()->findByPk($model->section_id);
				if($sectionM){
					$section = $sectionM->slug;
				}
			}
			 
		  
			$this->actionSimple($section,$type,$category,$state,$city,$id,$pot);
			Yii::app()->end();
			}
		}
		
        $notify = Yii::app()->notify;
        $country = Countries::model()->ListDataForJSON();
        $state   = States::model()->ListDataForJSON($model->country) ;
        $city   = City::model()->ListDataForJSON($model->state) ;
        $list_type = Category::model()->ListDataTypeForJSON_ID();
        $model->state= ($model->state==0)? 'All Cities' : $model->state;
        $section = Section::model()->ListDataForJSON_ID();
        $category = Category::model()->ListDataForJSON_ID_BySEction($model->listing_type);
        $sub_category =   Subcategory::model()->ListDataForJSON_ID($model->category_id) ;
        $subcategory=Subcategory::model()->findByPk($model->sub_category_id);
        $fields=array();
        $vehicleModel =array();
      
 	 
	    $this->setData(array(
			'pageMetaTitle'     =>  $this->tag->getTag('update-property',"Update Property").' :: '.$this->project_name, 
			'pageHeading'       => Yii::t(Yii::app()->controller->id, $this->tag->getTag('update-property',"Update Property")),
			'pageBreadcrumbs'   => array(
				Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
				Yii::t('app', 'Edit'),
			)
        ));
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			
			 
 
         
 	 
           	$model->dynamic  =  true; 
			//$model->dynamicArray = array_merge(array_diff((array)$fields,$model->dynamicFields()));
		 
					  if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
			$model->country = $attributes["country"];
			$model->state = $attributes["state"];
			$model->listing_type = $attributes["listing_type"];
			$model->city = $attributes["city"];
			$model->section_id = $attributes["section_id"];
			$model->sub_category_id = $attributes["sub_category_id"];
			if(isset($attributes["model"]))
			{
			$model->model = ($attributes["model"]==0)? 'Others': $attributes["model"] ;
		    }
			  
			$image_array  = array() ;        
            if(isset($model->adImages) )
            {
				foreach($model->adImages as $k=>$v)
				{
					$image_array[] = $v->image_name;
				}
		    }
		    
			if(isset($attributes['ad_title']))
			{
				 
			    $model->attributes= $attributes;
			    if (isset(Yii::app()->params['POST'][$model->modelName]['ad_description'])) {
				$model->ad_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['ad_description']);
				}
                 if (isset(Yii::app()->params['POST'][$model->modelName]['c_description'])) {
				$model->c_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['c_description']);
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['header_content'])) {
				$model->header_content =  Yii::app()->params['POST'][$model->modelName]['header_content'] ;
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['footer_content'])) {
				$model->footer_content =  Yii::app()->params['POST'][$model->modelName]['footer_content'] ;
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['caption'])) {
                $model->caption = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['caption']);
                }
			    if(isset($attributes["model"]))
				{
				$model->model = ($attributes["model"]==0)? 'Others': $attributes["model"] ;
				}
				$model->category_id = $category->category_id;
				//$model->dynamicArray ="";
			  //  $model->added_date = date("Y-m-d h:i:s");
			  
			  if (Yii::app()->request->isAjaxRequest) {
					echo CActiveForm::validate($model);
					Yii::app()->end();
					}
				if($model->validate())
				{
				    
				    if(Yii::app()->request->getPost('step_vlaue','')=='Finish Update'){
				        $model->payment_plan = !empty($model->payment_plan) ?  serialize($model->payment_plan) : '';
							 if($model->save()){
								 $this->afterSaveProcess($model,$pot);
								 exit;
							 }
						 }
						 
						   $image_array = array();
						   $model->amenities = Yii::app()->request->getPost("amenities");
						   	$model->add_property_types = Yii::app()->request->getPost("add_property_types");
						   
						    $model->faq = Yii::app()->request->getPost("faq");
						  $model->image = $model->image;
							$exp =  explode(",",$model->image);
							 
							if($exp)
							{
								foreach($exp as $k=>$v)
								{
									if($v!="")
									{
										$image_array[] = $v;
									}
								}
							}
							
							 
							 	$filter_array = array_filter(array_merge($model->attributes,(array)array('image'=>$model->image,'add_property_types'=>$model->add_property_types,'faq'=>$model->faq,'amenities'=>$model->amenities,'floor_plan'=>$model->floor_plan ,'payment_plan'=>!empty($model->payment_plan) ?  serialize($model->payment_plan) : '' )),'myFilter');
							  
						 
							    Yii::app()->user->setState("attribute_array".$pot,$filter_array);
								$this->redirect(Yii::app()->createUrl($this->id.'/choose_location',array('id'=>$model->id,'pot'=>$pot)));
						    
				 }
				 else
				 {
					
					 $model->amenities = Yii::app()->request->getPost("amenities");
					  $model->payment_plan = !empty($model->payment_plan) ?  serialize($model->payment_plan) : '';
					 $image_array=array();
						$exp =  explode(",",$model->image);
						if($exp)
						{
							foreach($exp as $k=>$v)
							{
								if($v!="")
								{
									$image_array[] = $v;
								}
							}
					    }
					 
					 
				 }
				 
				 
				 
 
			}
			
			 
			$model->sub_category_id = $attributes["sub_category_id"];
			 
			$this->actionDetails_edit($model,$subcategory,$category,$fields,$image_array,$pot);
           
        }
        else
        {
			$this->render('form-edit', compact('model',"country","category","state","sub_category","city","section","vehicleModel",'list_type')); 
		}
    }
    
  
    
    /**
     * Delete existing user
     */
    public function actionDelete($id)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);
        
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        
            $model->updateByPk($id,array('isTrash'=>Yii::app()->params['onTrash']));    
         

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'The item has been successfully deleted!'));
            $this->redirect($request->getPost('returnUrl', array(Yii::app()->controller->id.'/index')));
        }
    }
    public function actionFeatured($id,$featured)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);
        
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
            $featured = ($featured=="N") ? "Y" : "N";
            $model->updateByPk($id,array('featured'=>$featured ));    
         

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'The item has been successfully updated!'));
            $this->redirect($request->getPost('returnUrl', array(Yii::app()->controller->id.'/index')));
        }
    }
    
    public function actionStatus2($id,$status)
    { 
        $model = PlaceAnAd::model()->findByPk((int)$id);
        $status=(string)$status;
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        $status =  'A'; 
		$model->updateByPk($id,array('status'=>$status ));    
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'Successfully changed status'));
            $this->redirect($request->getPost('returnUrl', array(Yii::app()->controller->id.'/index')));
        }
    }
    public function actionStatus($id,$status)
    {
		 
		 
        $model = PlaceAnAd::model()->findByPk((int)$id);
        $status=(string)$status;
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
          
			  $status =  'I'; 
		   
      
    
            $model->updateByPk($id,array('status'=>$status ));    
         

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'Successfully changed status'));
            $this->redirect($request->getPost('returnUrl', array(Yii::app()->controller->id.'/index')));
        }
    }
    public function actionSelect_state()
    {
	  echo   States::model()->ListDataForJSON(Yii::app()->request->getPost("country")) ;exit;
	}
    public function actionSelect_city()
    {
	  echo   City::model()->ListDataForJSON(Yii::app()->request->getPost("state")) ;exit;
	}
    public function actionSelect_category()
    {
	  echo   Category::model()->ListDataForJSON_ID_BySEction(Yii::app()->request->getPost("section")) ;exit;
	}
    public function actionSelect_sub_category()
    {
	  echo   Subcategory::model()->ListDataForJSON_ID(Yii::app()->request->getPost("category")) ;exit;
	}
	public function actionSelect_model($id)
    {
	    $subcategory =  Subcategory::model()->findByPk($id);
		
		$fields=array();
		$fields=  ($subcategory->change_parent_fields=="N") ? CHtml::listData($subcategory->category->relatedFields,'field_name','field_name'):CHtml::listData($subcategory->relatedFields,'field_name','field_name');
 
			if(in_array('model',$fields))
			{
				echo   VehicleModel::model()->ListDataForJSON_ID_ByModel($id) ;exit;
			}
			else
			{
				echo 0;
			}
		 
	 
	  
	}
	public $image_size;
	public $image_name;
    public function actionUpload($width=null,$height=null)
    {
	 
	 
	  
	   $path =  Yii::getPathOfAlias('root.uploads.images');    
		//Yii::import('backend.extensions.ResizeImage');
		if($_FILES['file']['tmp_name'])
				{
					ini_set('memory_limit', '-1');
					$file = $_FILES['file']['name'];
					$file_orginal = $_FILES['file']['tmp_name'];
					$ext = pathinfo($file, PATHINFO_EXTENSION);
					$File = pathinfo($file, PATHINFO_FILENAME);
					$new_name =  substr(preg_replace("/[^a-zA-Z0-9._-]/", '_', "{$File}"),0,220);
					$new_name = empty($new_name) ? 'Untitled' : $new_name;
					$img = date('dmyHis').'_'.rand(000000, 999999).'_'.".".$ext;
					if(!empty($width)){
					 
						$detSize = getimagesize($_FILES['file']['tmp_name']);
						if($detSize){
							if(empty($height)){
								$aspectRatio = $detSize[1] / $detSize[0];
								$newHeight = (int)($aspectRatio * $width)  ;
							}
							else{
								$newHeight = $height ; 
							}
							$this->image_size = $detSize ; 
							$this->image_name = $img ; 
							
							$tempPath = Yii::getPathOfAlias('root.uploads.resized');  
							$resized = $this->makeTumbnail($_FILES['file']['tmp_name'],$width,$newHeight,$tempPath);
							
						}
					}
					if(Yii::app()->options->get('system.common.enable_resize','yes')=='yes1'){
							if(strtolower($ext)=='pdf') {
								 
								move_uploaded_file($_FILES['file']['tmp_name'], $path."/{$img}"); 
							}else{
							$fileSize = (int)$_FILES['file']['size']/1000000 ; 
							if($fileSize > 5) { $fileSize = 5; }
							switch($fileSize){
								case '5':
								$quality  = 20; 
								$quality_p  =4; 
								break;
								case '4':
								$quality  = 50; 
								$quality_p  = 4; 
								break;
								case '3':
								$quality  = 60; 
								$quality_p  = 8; 
								break;
								case '2':
								$quality  = 70; 
								$quality_p  = 8; 
								break;
								case '1':
								$quality  = 80; 
								$quality_p  = 8; 
								break;
								default:
								$quality  = 80; 
								$quality_p  = 7;
								break;
							}
							$tempPath = Yii::getPathOfAlias('root.uploads.images');
							$filename = $tempPath.'/'.$img ; 
							$detSize = getimagesize($_FILES['file']['tmp_name']);
							 	$this->image_size = $detSize ; 
							$this->image_name = $img ; 
							$width   = $detSize['0'];
							$newHeight   = $detSize['1'];
							switch($detSize['mime'])
							{
								case 'image/png': 
								 
								//$this->resize_crop_image($width,$newHeight,$url=$_FILES['file']['tmp_name'],$filename,$quality_p);
								break;
								default:
							 	//$this->resize_crop_image($width,$newHeight,$url=$_FILES['file']['tmp_name'],$filename,$quality);
								break;
							}
						}
					}
					else{
					
							move_uploaded_file($_FILES['file']['tmp_name'], $path."/{$img}");
					}
					echo $img;
			    }
			    else
			    {
					echo "0";
				}
	}
   function actionDelete_image()
	{
		  
	
		$str="";
		if(isset($_POST['inp']))
		{
		 
			 
			$ar = explode(',',$_POST['inp']);
			 
			 
			if($ar)
			{
				foreach($ar as $k=>$val)
				{
					 
					if($val!=$_POST['file'] and $val!="")
					{
						 
						$str .= ",".$val;
						 
					}
				}
			}
			 
		}
		echo $str; 
		 
    
   }
   public function actionSuccess($id)
   {
	    $model = PlaceAnAd::model()->findByPk($id);
	    if(empty($model))
	    {
			throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
		}
	     $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => 'List Off-Plan Property ' ,'{p}'=>Yii::app()->options->get('system.common.site_name'))),   
			'pageHeading'       => Yii::t(Yii::app()->controller->id, "List Off-Plan Property"),
			'pageBreadcrumbs'   => array(
				Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
				Yii::t('app', 'Create new'),
			)
        ));
        $this->render('root.apps.backend.views.offplan.success', compact('model'));
   } 
   public function actionSuccess_edit($id)
   {
	    $model = PlaceAnAd::model()->findByPk($id);
	    if(empty($model))
	    {
			throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
		}
		 
	    $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => 'List Off-Plan Property ' ,'{p}'=> Yii::app()->options->get('system.common.site_name'))),   
			'pageHeading'       => Yii::t(Yii::app()->controller->id, "Update Listing"),
			'pageBreadcrumbs'   => array(
				Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
				Yii::t('app', 'Create new'),
			)
        ));
        $this->render('success-edit', compact('model'));
   } 
   
 
     public function actionLoadCities()
	{
	   $id=null;
	   if(isset($_POST['state'])){ $id =$_POST['state'];  }
	   $data=City::model()->FindCities($id);
	   $data=CHtml::listData($data,'city_id','city_name');
	   echo "<option value=''>All Cities</option>";
	   foreach($data as $k=>$v)
	   echo CHtml::tag('option', array('value'=>$k),CHtml::encode($v),true);
	}
	 public function actionImage_management($id)
	{
		 
		$ad = PlaceAnAd::model()->findByPk((int)$id);
        if (empty($ad)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        $user =  new AdImage;
         
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        if ($request->isPostRequest) {
			   $sortOrderAll = $_POST['priority'];
				if(count($sortOrderAll)>0)
				{
					foreach($sortOrderAll as $menuId=>$sortOrder)
					{
						$user->isNewRecord =true; 
						$user->updateByPk($menuId,array('priority'=>$sortOrder)); 
					}
				}
				$up = $user->HighestPriorityImage($id);
				if($up)
				{
					$ad->updateByPk($id,array('image'=>$up->image_name)); 
				}
				 
				$notify->addSuccess(Yii::t('app', 'Priority successfully updated!'));
             
            
            Yii::app()->hooks->doAction('controller_action_save_data', $collection = new CAttributeCollection(array(
                'controller' => $this,
                'success'    => $notify->hasSuccess,
                'user'       => $user,
            )));
            
           /* if ($collection->success) {
                $this->redirect(array('room_manage/index'));
            }
            * */
        }
        
      
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('room_manage', 'Image Management'),
            'pageHeading'       => Yii::t('room_manage', 'Image Management'),
            'pageBreadcrumbs'   => array(
                Yii::t('hotel', 'Ad') => $this->createUrl($this->id.'/index'),
                Yii::t('app', 'Update'),
            )
        ));
        
        $this->render('image_manage', compact('ad','id','user'));
	}
	public function actionDelete_image_db($id)
	{
	 
        $ad = new AdImage();
        $manager = new PlaceAnAd();
        $rm = $ad->find(array("condition"=>"t.id=:id","params"=>array(":id"=>$id)));
        if($rm)
        {
			
			    $man = $manager->findByPk((int)$rm->ad_id);
				if (empty($man)) {
					throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
				}
				else
				{
					$up = $ad->HighestPriorityImage($rm->ad_id);
					if($up)
					{
						 $manager->updateByPk($rm->ad_id,array('image'=>$up->image_name)); 
					}
					else
					{
						$manager->updateByPk($rm->ad_id,array('image'=>"")); 
					}
					$ad->deleteByPk($id);
			    }
		}
          
       
	}
   public function actionApprove($id)
    {
       
        $user = new AdImage();
        $manager = new PlaceAnAd();
        $rm = $user->findByPk((int)$id);
        if (empty($rm)) {
					
					throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
				}
         
       
			 
			    $man = $manager->findByPk((int)$rm->ad_id);
				if (empty($man)) {
					
					throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
				}
				else
				{
					 
					$rm->status = ($rm->status==="A") ? "I" : "A" ;
					$rm->save() ;  
					 
					$up = $user->HighestPriorityImage($rm->ad_id);
					if($up)
					{ 
						 $manager->updateByPk($rm->ad_id,array('image'=>$up->image_name)); 
					}
					else
					{
						 
						$manager->updateByPk($rm->ad_id,array('image'=>"")); 
					}
					
			    }
		 
		 
         

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'The item has been successfully updated!'));
            $this->redirect(Yii::app()->createUrl($this->id."/image_management",array("id"=>$rm->ad_id)));
        }
    }
   public function actionDisapprove($id)
   {
	  $user =  new AdImage;
	   $request = Yii::app()->request;
        $notify = Yii::app()->notify;
	  if ($request->isPostRequest) {
			   $sortOrderAll = $_POST['id'];
				if(count($sortOrderAll)>0)
				{
					foreach($sortOrderAll as $menuId=>$sortOrder)
					{
						$user->isNewRecord =true; 
						$user->updateByPk($menuId,array('status'=>"I")); 
					}
				}
				 
				 
				 
				$notify->addSuccess(Yii::t('app', 'Ssuccessfully Disapproved'));
    }
    $this->redirect($request->urlReferrer);
 
}
   public function actionApprove_selected($id)
   {
		$user =  new AdImage;
		$request = Yii::app()->request;
		$notify = Yii::app()->notify;
	  if ($request->isPostRequest) {
			   $sortOrderAll = $_POST['id'];
				if(count($sortOrderAll)>0)
				{
					foreach($sortOrderAll as $menuId=>$sortOrder)
					{
						$user->isNewRecord =true; 
						$user->updateByPk($menuId,array('status'=>"A")); 
					}
				}
				 
				 
				 
				$notify->addSuccess(Yii::t('app', 'Ssuccessfully Approved'));
    }
    $this->redirect($request->urlReferrer);
 
  }
    public function actionApprove_all($id)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);
        
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        
        $user =  new AdImage;
        $user->updateAll(array('status'=>'A'),array("condition"=>"ad_id=:id","params"=>array(":id"=>$id)));
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $notify->addSuccess(Yii::t('app', 'Ssuccessfully Approved'));
        $this->redirect($request->urlReferrer);
    }
    public function actionDispprove_all($id)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);
        
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        
        $user =  new AdImage;
        $user->updateAll(array('status'=>'I'),array("condition"=>"ad_id=:id","params"=>array(":id"=>$id)));
         

        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        $notify->addSuccess(Yii::t('app', 'Ssuccessfully Disapproved'));
         $this->redirect($request->urlReferrer);
    }
    public function actionAd_image()
    {
         $request = Yii::app()->request;
         $notify = Yii::app()->notify;
         $model =  new PlaceAnAd();
         $this->getData('pageStyles')->add(array('src' => AssetsUrl::css('dropzone.css')));
         
         $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title} List"), 
            'pageHeading'       => Yii::t(Yii::app()->controller->id, "Image Management"),
            'pageBreadcrumbs'   => array(
                Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
                Yii::t('app', 'View all')
            )
        ));
        $this->render('ad_image', compact('model'));
    }
    public function actionImage_approve_manage()
    {
		$id=$_POST["id"];
		$user = new AdImage();
        $rm = $user->findByPk((int)$id);
        if (empty($rm)) {
 					      throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
				}
         
       
			     $manager = new PlaceAnAd();
			    $man = $manager->findByPk((int)$rm->ad_id);
				if (empty($man)) {
					
					throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
				}
				else
				{
					 
					$rm->status = ($rm->status==="A") ? "I" : "A" ;
					$rm->save() ;  
					 
					$up = $user->HighestPriorityImage($rm->ad_id);
					if($up)
					{ 
						 $manager->updateByPk($rm->ad_id,array('image'=>$up->image_name)); 
					}
					else
					{
						 
						$manager->updateByPk($rm->ad_id,array('image'=>"")); 
					}
					
			    }
		 
		 
	}
		function Get_LatLng_From_Google_Maps($address) {

		$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false";

		// Make the HTTP request
		$data = @file_get_contents($url);
		// Parse the json response
		$jsondata = json_decode($data,true);

		// If the json data is invalid, return empty array
		if (!$this->check_status($jsondata))   return array();

		$LatLng = array(
			'lat' => $jsondata["results"][0]["geometry"]["location"]["lat"],
			'lng' => $jsondata["results"][0]["geometry"]["location"]["lng"],
		);

		return $LatLng;
	}

	function check_status($jsondata) {
		if ($jsondata["status"] == "OK") return true;
		return false;
	}
	public function actionCheckModel($id=null)
	{
		$category =  Category::model()->findByPk($id);
		if($category)
		{
			if(in_array('model',CHtml::listData($category->relatedFields,'field_name','field_name')))
			{
				echo 1;
			}
			else
			{
				echo 0;
			}
		}
		else
		{
			echo 0;
		}
		 exit;
	}
   public function actionCommunity(){
		$limit = 30;
		$request=Yii::app()->request;
		$criteria= Community::model()->search(1);
		//$criteria->with = array('district'=>array('with'=>array('city'=>array('with'=>'state'))));
		
		//$criteria->together = true; 
		$region_id = $request->getQuery('state_id');
		$country_id = $request->getQuery('country_id');
		$condition = '';
		if($region_id){
		$criteria->params = array(':state'=>$request->getQuery('state_id')); 
				$condition    .= ' and t.region_id=:state ';
				$criteria->params[':state'] =  $region_id;
		}
		else if(!empty($country_id)){
			$criteria->join  .= ' LEFT JOIN {{countries}} c_st on c_st.country_id = st.country_id  ';
			$condition .= ' and t.country_id=:con or c_st.country_id = :con ';
				$criteria->params[':con'] =  $country_id;
		}
		if($condition){
			if($criteria->condition){
				$criteria->condition .= $condition;
			}
			else{
				$criteria->condition .= '1 and '.$condition;
			
			}
		}
		
		$criteria->compare('community_name',$request->getQuery('q'),true);
		$count = Community::model()->count($criteria);
		$criteria->limit   =  $limit ; 
        $page =Yii::app()->request->getQuery('page',1);
        $offset = ($page==1) ? '0' : ($page - 1) *  $limit + 1;
		$criteria->offset =  $offset ;
		$Result = Community::model()->findAll($criteria);
        $ar = array(); 
        if($Result){
			foreach($Result as $k=>$v){
				 $ar[]= array('id'=>$v->community_id,'text'=>$v->community_name.'('.$v->location.')');
			}
		}
        $record = array( "total_count"=>$count, "incomplete_results"=> false, "items" =>$ar) ; 
		echo  json_encode( $record ); Yii::app()->end();
	}
    public function actionDistrict(){
		$limit = 30;
		$request=Yii::app()->request;
		$criteria=new CDbCriteria;
		$criteria->with = array('city'=>array('with'=>array('state')));
		$criteria->condition = 'state.state_id=:state';
		$criteria->together = true; 
		$criteria->params = array(':state'=>$request->getQuery('state_id')); 
		$criteria->compare('district_name',$request->getQuery('q'),true);
		$count = District::model()->count($criteria);
		$criteria->limit   =  $limit ; 
        $page =Yii::app()->request->getQuery('page',1);
        $offset = ($page==1) ? '0' : ($page - 1) *  $limit + 1;
		$criteria->offset =  $offset ;
		$Result = District::model()->findAll($criteria);
        $ar = array(); 
        if($Result){
			foreach($Result as $k=>$v){
				 $ar[]= array('id'=>$v->district_id,'text'=>$v->district_name);
			}
		}
        $record = array( "total_count"=>$count, "incomplete_results"=> false, "items" =>$ar) ; 
		echo  json_encode( $record ); Yii::app()->end();
	}
    public function actionCustomer(){
		$limit = 30;
		$request=Yii::app()->request;
		$criteria=new CDbCriteria;
		$criteria->compare(new CDbExpression('CONCAT(first_name, " ", last_name)'), $request->getQuery('q') , true);
		$criteria->compare('t.company_name', $request->getQuery('q') , true,'OR');
		$criteria->compare('t.isTrash','0');
		$criteria->compare('t.status','A');
		$count = ListingUsers::model()->count($criteria);
		$criteria->order = 't.first_name'; 
		$criteria->limit   =  $limit ; 
        $page =Yii::app()->request->getQuery('page',1);
        $offset = ($page==1) ? '0' : ($page - 1) *  $limit + 1;
		$criteria->offset =  $offset ;
		
		$Result = ListingUsers::model()->findAll($criteria);
        $ar = array(); 
        if($Result){
			foreach($Result as $k=>$v){
				 $ar[]= array('id'=>$v->user_id,'text'=>$v->mainTitle.' '.'<span class="pull-right">'.$v->typeTile.'</span>');
			}
		}
        $record = array( "total_count"=>$count, "incomplete_results"=> false, "items" =>$ar) ; 
		echo  json_encode( $record ); Yii::app()->end();
	}
    public function actionSubCoummunity(){
		$request=Yii::app()->request;
		$criteria=new CDbCriteria;
		$criteria->condition =   't.community_id=:community_id';
		$criteria->params = array(':community_id'=>$request->getQuery('id')); 
		$criteria->compare('sub_community_name',$request->getQuery('q'),true);
		$count = SubCommunity::model()->count($criteria);
		$Result = SubCommunity::model()->findAll($criteria);
        $ar = array(); 
        if($Result){
			foreach($Result as $k=>$v){
				 $ar[]= array('id'=>$v->sub_community_id,'text'=>$v->sub_community_name);
			}
		}
        $record = array( "total_count"=>$count, "incomplete_results"=> false, "items" =>$ar) ; 
		echo  json_encode( $record ); Yii::app()->end();
	}
	public function makeTumbnail($filename, $width = 150, $height = true,$tempPath) {
			$url      = $filename ;
			$new_file_name =  $this->image_name;
			$filename = $tempPath.'/'.$new_file_name ; 			
			return $this->resize_crop_image($width,$height,$url,$filename,80);
			  
		}        
		/*
	 function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
			 
		$imgsize = $this->image_size;
		$width = $imgsize[0];
		$height = $imgsize[1];
		$mime = $imgsize['mime'];

		switch($mime){
			case 'image/gif':
				$image_create = "imagecreatefromgif";
				$image = "imagegif";
				break;

			case 'image/png':
				$image_create = "imagecreatefrompng";
				$image = "imagepng";
				$quality = 7;
				break;

			case 'image/jpeg':
				$image_create = "imagecreatefromjpeg";
				$image = "imagejpeg";
				$quality = 100;
				break;

			default:
				return false;
				break;
		}
		 
		$dst_img = imagecreatetruecolor($max_width, $max_height);
		if($mime=='image/png'){
			imageAlphaBlending($dst_img, false);
			imageSaveAlpha($dst_img, true);
			imagefilledrectangle($dst_img, 0, 0, $max_width, $max_height, imagecolorallocate($dst_img, 255, 255, 255));
		}
		$src_img = $image_create($source_file);
		 
		$width_new = $height * $max_width / $max_height;
		$height_new = $width * $max_height / $max_width;
		//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
		if($width_new > $width){
			//cut point by height
			$h_point = (($height - $height_new) / 2);
			//copy image
			imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
		}else{
			//cut point by width
			$w_point = (($width - $width_new) / 2);
			imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
		}
		 
		$image($dst_img, $dst_dir, $quality);

		if($dst_img){ imagedestroy($dst_img); return true ; }
		if($src_img) { imagedestroy($src_img); return true ; }
		}
		*/
		function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
			 
		$imgsize = $this->image_size;
		$width = $imgsize[0];
		$height = $imgsize[1];
		$mime = $imgsize['mime'];

		switch($mime){
			case 'image/gif':
				$image_create = "imagecreatefromgif";
				$image = "imagegif";
				break;

			case 'image/png':
			
			 
				$image_create = "imagecreatefrompng";
				$image = "imagepng";
				$quality = $quality;
				break;

			case 'image/jpeg':
				$image_create = "imagecreatefromjpeg";
				$image = "imagejpeg";
				$quality = $quality;
				break;

			default:
				return false;
				break;
		}
		 
		$dst_img = imagecreatetruecolor($max_width, $max_height);
		if($mime=='image/png'){
			imageAlphaBlending($dst_img, false);
			imageSaveAlpha($dst_img, true);
			imagefilledrectangle($dst_img, 0, 0, $max_width, $max_height, imagecolorallocate($dst_img, 255, 255, 255));
		}
		$src_img = $image_create($source_file);
		 
		$width_new = $height * $max_width / $max_height;
		$height_new = $width * $max_height / $max_width;
		//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
		if($width_new > $width){
			//cut point by height
			$h_point = (($height - $height_new) / 2);
			//copy image
			imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
		}else{
			//cut point by width
			$w_point = (($width - $width_new) / 2);
			imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
		}
		 
		$image($dst_img, $dst_dir, $quality);

		if($dst_img){ imagedestroy($dst_img); return true ; }
		if($src_img) { imagedestroy($src_img); return true ; }
		}
  
 public function actionView($id)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        $this->renderPartial('_view', compact('user','model','personal'));
    }
 public function actionTag($id)
    {
        $model = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        $this->renderPartial('_tag', compact('user','model','personal'));
    }
     public function actionStatus_change($id=null,$val=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        $user::model()->updateByPk($id,array('status'=>$val));
        echo 1; 
    }
     public function actionStatus_change2($id=null,$val=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        $user::model()->updateByPk($id,array('featured'=>$val));
        echo 1; 
    }
     public function actionPromoted($id=null,$val=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        $user::model()->updateByPk($id,array('promoted'=>$val));
        echo 1; 
    }
     public function actionIs_new($id=null,$val=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        $user::model()->updateByPk($id,array('is_new'=>$val));
        echo 1; 
    }
    public function actionUpdate_tag($id=null,$fun=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        switch($fun)
        {
				case 'F':
				$val = ( $user->featured =='Y') ? 'N' : 'Y';
				$user::model()->updateByPk($id,array('featured'=>$val));
				if($val=='Y'){
					echo json_encode(array('class'=>'0'));
				}
				else{
					echo json_encode(array('class'=>'1'));
				}
				break;
				case 'R':
				$val = ( $user->recmnded =='1') ? '0' : '1';
				$user::model()->updateByPk($id,array('recmnded'=>$val));
				if($val=='1'){
					echo json_encode(array('class'=>'0'));
				}
				else{
					echo json_encode(array('class'=>'1'));
				}
				break;
				case 'P':
				$val = ( $user->promoted =='1') ? '0' : '1';
				$user::model()->updateByPk($id,array('promoted'=>$val));
				if($val=='1'){
					echo json_encode(array('class'=>'0'));
				}
				else{
					echo json_encode(array('class'=>'1'));
				}
				break;
				case 'N':
				$val = ( $user->is_new =='1') ? '0' : '1';
				$user::model()->updateByPk($id,array('is_new'=>$val));
				if($val=='1'){
					echo json_encode(array('class'=>'0'));
				}
				else{
					echo json_encode(array('class'=>'1'));
				}
				break;
		}
		exit; 
        echo 1; 
    }
     public function actionStatus_recommended2($id=null,$val=null)
    {
		if(!Yii::app()->request->isAjaxRequest){
			return false;
		}
        $user = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        } 
        $user::model()->updateByPk($id,array('recmnded'=>$val));
        echo 1; 
    }
    public function actionUpload_floor_plan($width=null,$height=null)
    {
	 
	  
	    $path =  Yii::getPathOfAlias('root.uploads.floor_plan');    
		//Yii::import('backend.extensions.ResizeImage');
		if($_FILES['file']['tmp_name'])
				{
					ini_set('memory_limit', '-1');
					$file = $_FILES['file']['name'];
					$file_orginal = $_FILES['file']['tmp_name'];
					$ext = pathinfo($file, PATHINFO_EXTENSION);
					$File = pathinfo($file, PATHINFO_FILENAME);
					$new_name =  substr(preg_replace("/[^a-zA-Z0-9._-]/", '_', "{$File}"),0,220);
					$new_name = empty($new_name) ? 'Untitled' : $new_name;
					$img = $new_name.'_'.time().".".$ext;
					move_uploaded_file($_FILES['file']['tmp_name'], $path."/{$img}");
					echo $img;
			    }
			    else
			    {
					echo "0";
				}
	}
   function actionDelete_floor_plan()
	{
		 
	
		$str="";
		if(isset($_POST['inp']))
		{
		 
			 
			$ar = explode(',',$_POST['inp']);
			 
			 
			if($ar)
			{
				foreach($ar as $k=>$val)
				{
					 
					 if (strpos($val, $_POST['file'])  == false) {
						 
						$str .= ",".$val;
						 
					}
				}
			}
			 
		}
		echo $str; 
		 
    
   }
      public function actionChoose_location($pot=null,$id=null)
   {
		if(empty($pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
	    $request = Yii::app()->request ;
	    $notify = Yii::app()->notify ;
	   
	    if(!Yii::app()->user->hasState("attribute_array".$pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
		$attributes2 = Yii::app()->user->getState("attribute_array".$pot); 
		
		 
		 
		if(!empty($id)){
			 $model = PlaceAnAd::model()->findByPk( $id );
			 if(empty($model)){
				throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
			 }
			 		}
		else{
			 $model = new PlaceAnAd();
		}
		unset($attributes2['id']);
		
		 
	 	$model->attributes = $attributes2; 
		$model->dynamic  =  true; 
	 if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
  
		
		 
		$image_array=array();
		$exp =  explode(",",$model->image);
		if($exp)
		{
			foreach($exp as $k=>$v)
			{
			if($v!="")
			{
			$image_array[] = $v;
			}
			}
		}
	    if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			$model->attributes = $attributes;
			 
		 
		 	$model->dynamic  =  true; 
		 		
					  if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
 
		 	 $model->add_property_types = Yii::app()->request->getPost("add_property_types");
			  $model->faq = Yii::app()->request->getPost("faq");
			
			 if(!$model->validate()){
									 
                     $notify->addError(CHtml::errorSummary($model));
			 }
			 else{
			         if (isset(Yii::app()->params['POST'][$model->modelName]['ad_description'])) {
				        	$model->ad_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['ad_description']);
					}
					 if (isset(Yii::app()->params['POST'][$model->modelName]['c_description'])) {
				        	$model->c_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['c_description']);
					}
					if (isset(Yii::app()->params['POST'][$model->modelName]['header_content'])) {
			        	$model->header_content =  Yii::app()->params['POST'][$model->modelName]['header_content'] ;
			    	}
			    	if (isset(Yii::app()->params['POST'][$model->modelName]['footer_content'])) {
				        $model->footer_content =  Yii::app()->params['POST'][$model->modelName]['footer_content'] ;
				    }
				    if (isset(Yii::app()->params['POST'][$model->modelName]['caption'])) {
                      $model->caption = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['caption']);
                    }
					$filter_array = array_filter(array_merge($model->attributes,(array)array('image'=>$model->image,'amenities'=>$model->amenities,'floor_plan'=>$model->floor_plan,'add_property_types'=>$model->add_property_types,'faq'=>$model->faq )),'myFilter');
					Yii::app()->user->setState("attribute_array".$pot,$filter_array);
					if($model->isNewRecord){
						$this->redirect(Yii::app()->createUrl($this->id.'/preview',array('pot'=>$pot)));	
					}else{
						$this->redirect(Yii::app()->createUrl($this->id.'/preview',array('id'=>$id,'pot'=>$pot)));	
					}							   
			 }	
			 
		}
		 
	    
	     $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => $this->tag->getTag('list-your-property','List Off-Plan Property') ,'{p}'=> $this->project_name)),   
			'pageHeading'       => Yii::t(Yii::app()->controller->id,$this->tag->getTag('list-your-property','List Off-Plan Property')),
			'pageBreadcrumbs'   => array(
				Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
				Yii::t('app', 'Create new'),
			)
        ));
        $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('myAjax.js')));
        $this->render('root.apps.backend.views.offplan.location_view', compact('model','subcategory','category',"fields","image_array","jsonData",'pot'));exit;
  
         
   } 
   public function actionPreview($pot=null,$id=null)
   {
	    if(empty($pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
	    $request = Yii::app()->request ;
	    $notify = Yii::app()->notify ;
	     
	    if(!Yii::app()->user->hasState("attribute_array".$pot)){
			throw new CHttpException(404, Yii::t('app', 'Pot unable to set.'));
		}
		if(!empty($id)){
			 $model = PlaceAnAd::model()->findByPk( $id );
			 if(empty($model)){
				throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
			 }
			 		}
		else{
			 $model = new PlaceAnAd();
		}
		$attributes2 = Yii::app()->user->getState("attribute_array".$pot); 
	 
		 		$model->attributes = $attributes2; 
		$model->dynamic  =  true; 
	 				  if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
	 
		
		$image_array=array();
		$exp =  explode(",",$model->image);
		if($exp)
		{
			foreach($exp as $k=>$v)
			{
			if($v!="")
			{
			$image_array[] = $v;
			}
			}
		}
	    if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			$model->attributes = $attributes;
		 
             
		 	$model->dynamic  =  true; 
		 			
					  if($model->section_id=='3'){
	 $model->dynamicArray =array();
  }
		 	  if (isset(Yii::app()->params['POST'][$model->modelName]['ad_description'])) {
				$model->ad_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['ad_description']);
				}
	  if (isset(Yii::app()->params['POST'][$model->modelName]['c_description'])) {
				$model->c_description = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['c_description']);
				}
					if (isset(Yii::app()->params['POST'][$model->modelName]['header_content'])) {
				$model->header_content =  Yii::app()->params['POST'][$model->modelName]['header_content'] ;
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['footer_content'])) {
				$model->footer_content =  Yii::app()->params['POST'][$model->modelName]['footer_content'] ;
				}
				if (isset(Yii::app()->params['POST'][$model->modelName]['caption'])) {
                $model->caption = Yii::app()->ioFilter->purify(Yii::app()->params['POST'][$model->modelName]['caption']);
                }
			 if(!$model->save()){
									 
                     $notify->addError(CHtml::errorSummary($model));
			 }
			 else{
				 
									if(!$model->isNewRecord){
										$room_image = new AdImage;
										$room_image->deleteAll(array("condition"=>"ad_id=:ad_id","params"=>array(":ad_id"=>$model->id)));
										$am = new  AdAmenities();
										$am->deleteAll(array("condition"=>"ad_id=:ad_id","params"=>array(":ad_id"=>$model->id)));
									}
									$room_image = new AdImage;
									$imgArr =  explode(',',$model->image);
									if($imgArr)
									{
										$img_saved= false;
										foreach($imgArr as $k)
										{
												 
												$room_image->isNewRecord = true;
												$room_image->id = "";
												$room_image->ad_id = $model->id;
												$room_image->image_name =  $k;
												$room_image->save();
										}
									 }
									  if($ameni = Yii::app()->request->getPost("amenities"))
									  {
										 $am = new  AdAmenities();
										 foreach($ameni as $k)
										 {
											 
												$am->isNewRecord = true;
												$am->ad_id = $model->id;
												$am->amenities_id =  $k;
												$am->save();
										 }
										 
					 }
					Yii::app()->session->remove(Yii::app()->user->getStateKeyPrefix() . 'attribute_array'.$pot);
					$this->redirect(Yii::app()->createUrl($this->id."/success",array("id"=>$model->id)));								   
			 }
			 
		}
		 
	    
	     $this->setData(array(
			'pageMetaTitle'     =>   Yii::t('app', '{name}   :: {p}', array('{name}' => $this->tag->getTag('list-your-property','List Off-Plan Property') ,'{p}'=> $this->project_name)),   
			'pageHeading'       => Yii::t(Yii::app()->controller->id,$this->tag->getTag('list-your-property','List Off-Plan Property')),
			'pageBreadcrumbs'   => array(
				Yii::t(Yii::app()->controller->id, "{$this->Controlloler_title}") => $this->createUrl(Yii::app()->controller->id.'/index'),
				Yii::t('app', 'Create new'),
			)
        ));
        $array = $model->detailList();
        $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('myAjax.js')));
        $this->getData('pageStyles')->add(array('src' => $this->app->apps->getBaseUrl('backend/assets/css/dropzone.css')));
        $this->getData('pageScripts')->add(array('src' =>  'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'));
        $this->render('root.apps.backend.views.offplan.preview', compact('model','subcategory','category',"fields","image_array","jsonData",'array','pot'));exit;
  
         
   } 
   public function afterSaveProcess($model,$pot){
		
				 
									if(!$model->isNewRecord){
										$room_image = new AdImage;
										$room_image->deleteAll(array("condition"=>"ad_id=:ad_id","params"=>array(":ad_id"=>$model->id)));
										$am = new  AdAmenities();
										$am->deleteAll(array("condition"=>"ad_id=:ad_id","params"=>array(":ad_id"=>$model->id)));
									}
									$room_image = new AdImage;
									$imgArr =  explode(',',$model->image);
									if($imgArr)
									{
										$img_saved= false;
										foreach($imgArr as $k)
										{
											 
												$room_image->isNewRecord = true;
												$room_image->id = "";
												$room_image->ad_id = $model->id;
												$room_image->image_name =  $k;
												$room_image->save();
										}
									 }
									  if($ameni = Yii::app()->request->getPost("amenities"))
									  {
										 $am = new  AdAmenities();
										 foreach($ameni as $k)
										 {
											 
												$am->isNewRecord = true;
												$am->ad_id = $model->id;
												$am->amenities_id =  $k;
												$am->save();
										 }
										 
					 }
					Yii::app()->session->remove(Yii::app()->user->getStateKeyPrefix() . 'attribute_array'.$pot);
					$this->redirect(Yii::app()->createUrl($this->id."/success",array("id"=>$model->id)));
	}
   public function actionChnimge(){
		$img =   Yii::app()->request->getPost('img');$pot =   Yii::app()->request->getPost('pot');
		if($img==null){ echo json_encode(array('status'=>'0','message'=>'Image Cannot be blank') ); exit; }
		if(!Yii::app()->user->hasState("attribute_array".$pot)){
			echo json_encode(array('status'=>'0','message'=>'Pot Cannot be blank') ); exit;
		}
		$attributes  = Yii::app()->user->getState("attribute_array".$pot);
		$attributes['image'] = $img ;
		Yii::app()->user->setState("attribute_array".$pot,$attributes);
		echo json_encode(array('status'=>'1','message'=>'1'));exit;					
		 
	}
   
}
