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

/**
 * SiteController
 * 
 * @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 DetailsController extends Controller
{
			
 public function init(){
	   $this->getData('pageScripts')->add(array('src' => Yii::app()->apps->getBaseUrl('assets/js/custom.js')));
        // register class paths for extension captcha extended
        Yii::$classMap = array_merge( Yii::$classMap, array(
            'CaptchaExtendedAction' => Yii::getPathOfAlias('root.apps.extensions.captchaExtended').DIRECTORY_SEPARATOR.'CaptchaExtendedAction.php',
            'CaptchaExtendedValidator' => Yii::getPathOfAlias('root.apps.extensions.captchaExtended').DIRECTORY_SEPARATOR.'CaptchaExtendedValidator.php'
        ));
    }
	
    public function actionIndex($slug=null)
    {
	     //$this->layout = "sub2";
	     
	      $this->layout =   Yii::app()->LayoutClass->layoutpath("detail");
		 $model2 = new Contact;
		 $request = Yii::app()->request;
		 $options = Yii::app()->options;
		
		//$this->getData('pageStyles')->add(array('src' => Yii::app()->baseUrl."/backend/assets/css/table2.css"));
		 
 
	 
	// $model = PlaceAnAd::model()->listDataFromSlug($slug);
	 $criteria=new CDbCriteria;
	 $criteria->condition = "t.isTrash='0' and t.status='A' 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.'));
	 }
	 //Ajax Validation
	 if (Yii::app()->request->isAjaxRequest) {
		echo CActiveForm::validate($model2);
		Yii::app()->end();
	  }
	  if ($request->isPostRequest && ($attributes = (array)$request->getPost($model2->modelName, array())))
		 {
			 
			 $model2->attributes = $attributes;
			  
			 $model2->ad_id = $model->id ;
			 $success ="";
			 if($model2->save())
			 {
			  $success ="1";
			  
			    $emailTemplate =  CustomerEmailTemplate::model()->findByName("contact detial page");
			    if($emailTemplate)
			    {
					 $emailTemplate = $emailTemplate->content;
				}
				else
				{
					    $emailTemplate = $options->get('system.email_templates.common');
				}
				 
			    $ad_details = array("ad_title"=>$model->ad_title,"ad_slug"=>$model->slug );
			
                $emailBody = $this->renderPartial('_email', compact('model2',"ad_details"), true);
                $emailTemplate = str_replace('[CONTENT]', $emailBody, $emailTemplate);
                $logo =  '<a href="'.Yii::app()->createAbsoluteUrl("site/index").'" alt=""><img src="'. Yii::app()->params['uploadDir']."/logo/" .Yii::app()->options->get('system.common.logo').'" style="width:134px;height:56px;"></a> ';
				$emailTemplate = str_replace('{logo}',$logo, $emailTemplate);
				$params = array(
				'to'            =>   Yii::app()->options->get('system.common.admin_email'),
				'fromName'      =>   Yii::app()->options->get('system.common.site_name'),
				'subject'       =>	 'Enquiry Form '.Yii::app()->name  ,
				'body'          =>   $emailTemplate,
				);
				$emailTemplate2= str_replace('Admin', $model->Customer->first_name, $emailTemplate)  ; 
				$params2 = array(
				'to'            =>   $model->Customer->email,
				'fromName'      =>   Yii::app()->options->get('system.common.site_name'),
				'subject'       =>	 'Enquiry Form '.Yii::app()->name  ,
				'body'          =>   $emailTemplate2,
				);
			
				$mapping = DeliveryServer::getTypesMapping();
				$server = DeliveryServer::model($mapping['smtp'])->findByPk((int)4);
			    //Send for Admin
				$server->sendEmail($params);
				 //Send for listing customer
				$server->sendEmail($params2);
			  
			   Yii::app()->user->setFlash('mailsent',1);
			   Yii::app()->user->setFlash('success',"Thank you for contacting us. One of our representative will contact you soon.");
			  $this->redirect(Yii::app()->request->urlReferrer);
			  
			  
			  
			 }
			 else
			 {
				  Yii::app()->user->setFlash('error','Please Fix the following Errors <a href="#respond">View</a>');
			 }
			 
		  
		 }
	 
	 //Related Ad
	 $criteria=new CDbCriteria;
	 $criteria->condition = "t.isTrash='0' and t.status='A' and t.id!=:id and (sub_category_id=:sub_category_id or category_id=:category_id or section_id=:section_id)";
	 $criteria->params[":id"] =$model->id;
	 $criteria->params[":sub_category_id"] =$model->sub_category_id;
	 $criteria->params[":category_id"] =$model->category_id;
	 $criteria->params[":section_id"] =$model->section_id;
	 $criteria->limit = "4";
	  $criteria->order ="featured='Y',priority desc,id desc";
	 $relatedAds=PlaceAnAd::model()->findAll($criteria);
	 
	 //
     $subcategory= Subcategory::model()->findByAttributes(array('sub_category_id'=>$model->sub_category_id));
	 if(empty($subcategory))
	 {
	 
	 $cate= Category::model()->getCatgeory($model->category_id);
          
	 }
	$fields=array();
	if(!empty($subcategory))
	{
		  $fields=  ($subcategory->change_parent_fields=="N") ? CHtml::listData($subcategory->category->relatedFields,'field_name','field_name'):CHtml::listData($subcategory->relatedFields,'field_name','field_name');
	}
	else
	{
		  $fields=   CHtml::listData($cate->relatedFields,'field_name','field_name') ;
  
	}

	 $this->setData(array(
                    'pageMetaTitle'         => Yii::t('app', '{name} :: home', array('{name}' => Yii::app()->name )), 
                    'pageMetaDescription'   => $model->ad_title,
                    
                ));
     $attributes['category_id'] = $model->category_id;
     $attributes['sub_category_id'] = $model->sub_category_id;
     $attributes['model'] = $model->model;
	 $this->render(Yii::app()->LayoutClass->viewpath("index"),compact("model","fields","relatedAds","model2",'attributes'));
    }
    
    public function actionOffline()
    {
        if (Yii::app()->options->get('system.common.site_status') !== 'offline') {
            $this->redirect(array('site/index'));
        }
        
        throw new CHttpException(503, Yii::app()->options->get('system.common.site_offline_message'));
    }
    
    public function actionError()
    {
		 
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo CHtml::encode($error['message']);
            } else {
                $this->setData(array(
                    'pageMetaTitle'         => Yii::t('app', 'Error {code}!', array('{code}' => $error['code'])), 
                    'pageMetaDescription'   => $error['message'],
                ));
                $this->render('error', $error) ;
            }    
        }
    }
  
 

}
