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

/**
 * UsersController
 * 
 * Handles the actions for users related tasks
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */
 
class Place_an_adController 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 function init()
    {
       $this->getData('pageStyles')->add(array('src' => AssetsUrl::css('styles/jqx.base.css')));
       $this->getData('pageStyles')->add(array('src' => AssetsUrl::css('table.css')));
       $this->getData('pageStyles')->add(array('src' => AssetsUrl::css('styles/jqx.ui-le-frog.css')));
       $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('jqwidgets/jqxcore.js')));
       $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('jqwidgets/jqxbuttons.js')));
       $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('jqwidgets/jqxscrollbar.js')));
       $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('jqwidgets/jqxlistbox.js')));
     
    
    
        parent::init();
       
        
    }
 
    /**
     * List all available users
     */
    public function actionIndex()
    {
         $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());
        $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'));
    }
    
    public function actionCreate()
    {
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $model = new PlaceAnAd();
        $country = Countries::model()->ListDataForJSON();
        $category = Category::model()->ListDataForJSON();
	    $this->setData(array(
			'pageMetaTitle'     => $this->data->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'),
			)
        ));
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			
			 
	 
            $subcategory= Subcategory::model()->FindSubategory(@$attributes["sub_category_id"]);
            if(empty($subcategory))
			{
				throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
			}
            $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');

			$model->dynamic  =  true; 
			$model->dynamicArray = (array)$fields;
			$model->country = $attributes["country"];
			$model->state = $attributes["state"];
			$model->sub_category_id = $attributes["sub_category_id"];
			
           
			if(isset($attributes['ad_title']))
			{
				 
			    $model->attributes= $attributes;
				$model->section_id = $subcategory->section_id;
				$model->category_id = $subcategory->category_id;
				$model->dynamicArray ="";
			    $model->added_date = date("Y-m-d h:i:s");
				if($model->save())
				{
				 
						$room_image = new AdImage;
						$imgArr =  explode(',',$model->image);
						if($imgArr)
						{
							$i=1;
							foreach($imgArr as $k)
							{
								if($k!="")
								{
									
								 
									if($i==1 and $model->image=="")
									{
									$model->updateByPk($id,array('image'=>$k));  	
									}
									$room_image->isNewRecord = true;
									$room_image->id = "";
									$room_image->ad_id = $model->id;
									$room_image->image_name =  $k;
									$room_image->save();
									$i++;
								}
								
							}
							
						 }
						  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();
							 }
							 
						  }
						  $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
						 $this->redirect(Yii::app()->createUrl("place_an_ad/success",array("id"=>$model->id)));
				 }
				 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->sub_category_id = $attributes["sub_category_id"];
			$this->actionDetails($model,$subcategory,$fields);
           
        }
        else
        {
			$this->render('form', compact('model',"country","category"));
		}
        
 
        
    }
     public function actionDetails($model,$subcategory,$fields)
    {
		 
		$this->getData('pageScripts')->add(array('src' => AssetsUrl::js('myAjax.js')));
		$this->getData('pageScripts')->add(array('src' => AssetsUrl::js('dropzone.min.js')));
		$this->getData('pageStyles')->add(array('src' => AssetsUrl::css('dropzone.css')));
        $this->render('details', compact('model','subcategory',"fields"));
    }
     public function actionFindOnMap()
    {
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $model = new PlaceAnAd();
      //  $subcategory= SubCategory::model()->FindSubategory("12");
         
        $this->setData(array(
            'pageMetaTitle'     => $this->data->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)
    {
		 
        $model = PlaceAnAd::model()->findByPk((int)$id);

        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
         $request = Yii::app()->request;
        $notify = Yii::app()->notify;
         
        $country = Countries::model()->ListDataForJSON();
        $category = Category::model()->ListDataForJSON();
	    $this->setData(array(
			'pageMetaTitle'     => $this->data->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'),
			)
        ));
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			
			 
	 
            $subcategory= Subcategory::model()->FindSubategory(@$attributes["sub_category_id"]);
            if(empty($subcategory))
			{
				throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
			}
            $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');

			$model->dynamic  =  true; 
			$model->dynamicArray = (array)$fields;
			$model->country = $attributes["country"];
			$model->state = $attributes["state"];
			$model->sub_category_id = $attributes["sub_category_id"];
			
            
			if(isset($attributes['ad_title']))
			{
				 
			    $model->attributes= $attributes;
				$model->section_id = $subcategory->section_id;
				$model->category_id = $subcategory->category_id;
				$model->dynamicArray ="";
			    $model->added_date = date("Y-m-d h:i:s");
				if($model->save())
				{
				 
						$room_image = new AdImage;
						$imgArr =  explode(',',$model->image);
						if($imgArr)
						{
							$i=1;
							foreach($imgArr as $k)
							{
								if($k!="")
								{
									
								 
									if($i==1 and $model->image=="")
									{
									$model->updateByPk($id,array('image'=>$k));  	
									}
									$room_image->isNewRecord = true;
									$room_image->id = "";
									$room_image->ad_id = $model->id;
									$room_image->image_name =  $k;
									$room_image->save();
									$i++;
								}
								
							}
							
						 }
						  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();
							 }
							 
						  }
						  $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
						 $this->redirect("success");
				 }
				 else
				 {
					 $model->amenities = Yii::app()->request->getPost("amenities");
				 }
				 
				 
				 
 
			}
			$model->sub_category_id = $attributes["sub_category_id"];
			$this->actionDetails($model,$subcategory,$fields);
           
        }
        else
        {
			$this->render('form', compact('model',"country","category"));
		}
    }
    
    /**
     * 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 actionSelect_state()
    {
	  echo   States::model()->ListDataForJSON(Yii::app()->request->getPost("country")) ;exit;
	}
    public function actionSelect_sub_category()
    {
	  echo   Subcategory::model()->ListDataForJSON(Yii::app()->request->getPost("category")) ;exit;
	}
     public function actionUpload()
    {
	 
	   $path =  Yii::app()->basePath . '/../../uploads' ;
		Yii::import('backend.extensions.ResizeImage');
		if($_FILES['file']['tmp_name'])
				{
				$img = rand(0,9999).'_'.time().".jpg";
				$resize = new ResizeImage($_FILES['file']['tmp_name']);
				$resize->resizeTo(300,160,'exact');
				$resize->saveImage( $path."/ads_thumb/{$img}");
				move_uploaded_file($_FILES['file']['tmp_name'], $path."/ads/{$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'])
					{
						$str .= ",".$val;
					}
				}
			}
			 
		}
    
   }
   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'     => $this->data->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('success', compact('model'));
   } 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.'));
        }
     //   $request = Yii::app()->request;
        
        
        // for filters.
        //$user->attributes = (array)$request->getQuery($user->modelName, array());
      
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('hotel_booking', 'Place An Ad'), 
            'pageHeading'       => Yii::t('hotel_booking', 'Place An Ad'),
            'pageBreadcrumbs'   => array(
                Yii::t('hotel', 'Hotel') => $this->createUrl('place_an_ad/index'),
                Yii::t('app', 'Booking Details')
            )
        ));
      
        $this->render('view', compact('model'));
    }
}
