<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
	/**
	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu=array();
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();
	
	
		public function init() {
            parent::init();
            $this->initAjaxCsrfToken();
    }
	
	
        /*public function init() {
            echo stripos($_SERVER["REQUEST_URI"],'/upload');
            parent::init();
            if(stripos($_SERVER["REQUEST_URI"],'/upload') === FALSE)
            {
              Yii::app()->request->enableCsrfValidation = true;    echo 'false';          
              $this->initAjaxCsrfToken();
            }
            else
            {
            Yii::app()->request->enableCsrfValidation = false;echo 'true'; 
            }
            
            
        }*/
       /* protected function beforeRun()
        {
            $this->controller->enableCsrfValidation = false;
            return parent::beforeRun();
        }*/
        // this function will work to post csrf token.
        protected function initAjaxCsrfToken() {

            Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
                             data: {"' . Yii::app()->request->csrfTokenName . '": "' . Yii::app()->request->csrfToken . '"},
                             cache:false
                        });', CClientScript::POS_HEAD);
        }
        public function beforeAction($action)
        {
            
            $request_uri 		= $_SERVER['REQUEST_URI'];                        
            $len_request_uri 	= strlen($request_uri);

            $constant_length = 100;
            $arr_str_len = parse_url($request_uri);
            $arr_path_info = explode("/",$arr_str_len['path']);
             if (Yii::app()->user->isGuest) {
                 echo Yii::app()->controller->action->id;
                if (Yii::app()->controller->action->id == "page") {
                    
                    if($len_request_uri > $constant_length){
                                $this->render('404');
                                return false;
                        }
                    
                    else{
                    Yii::app()->user->setReturnUrl('page/' . $_GET['id']);
                    if (in_array($_GET['id'], array(20, 22, 23, 53, 54, 55, 56, 57, 59, 60))) {
                        $this->redirect(array('site/login'));
                    }
                    }
                }
                else{
                    if(Yii::app()->user->isGuest )
                		{
                			$this->layout	=	"login";
                		}
                		else if(!(Yii::app()->user->isAdmin()))
                		{
                			Yii::app()->user->logout();
                			//$this->redirect(Yii::app()->homeUrl);
                			//echo 'HTTP Error 401 Unauthorized! You are not an administartor | '.CHtml::link('Home',"index.php");
                			$this->redirect(array('login'));
                			die();
                		}
                }
                
                
                
            }
            else if (isset(Yii::app()->user->id) && Yii::app()->user->id > 0) {
                    return parent::beforeAction($action);
            }
            else{
       
                if (parent::beforeAction($action)) {

                        if($len_request_uri > $constant_length){
                                $this->render('../site/404');
                                return false;
                        }
                    }

                    return true;
            }
            return true;
        }
	
	
	
	
	/*
	*Ajax single file Upload
	*/
         function CropIfImage($folder, $fileName, $width = 100, $height = 100) {
        $imagefile = getimagesize($folder . $fileName);
        if (is_array($imagefile)) {
            $thumb = Yii::app()->phpThumb->create($folder . '/' . $fileName);
            $thumb->resize($width, $height);
            $thumb->save($folder . '/' . $width . $height . '_' . $fileName);
        }
    }
	public function actionUpload($folder)
	{
				Yii::import('ext.EAjaxUpload.qqFileUploader');
				$main_folder=$folder;
				$allowedExtensions = array('pdf','jpg','jpeg','gif','png','doc','docx','zip','mov','avi','wma');//array("jpg","jpeg","gif","exe","mov" and etc...
				$sizeLimit = 700 * 1024 * 1024;// maximum file size in bytes
				$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
				$result = $uploader->handleUpload($main_folder);
				$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		 
				$fileSize=filesize($main_folder.$result['filename']);//GETTING FILE SIZE
				$fileName=$result['filename'];//GETTING FILE NAME
				$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
				echo $return;// it's array
	}
	  public function actionUploadimage($folder = null) {
        Yii::import("ext.EAjaxUpload.qqFileUploader");

        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
// make the directory to store the pic:
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
//chmod($folder, 0755);
        }
        $allowedExtensions = array( "png",  "jpg", "jpeg", "gif"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 20 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        $fileName = $result['filename']; //GETTING FILE NAME
       // print_r($fileName);die();
        $this->CropIfImage($folder, $fileName, 100, 100);
        echo $return; // it's array
    }
	public function actionDownload($file)
	{
		$file_name = $file;
		//$file_url = 'http://www.myremoteserver.com/' . $file_name;
		header('Content-Type: application/octet-stream');
		header("Content-Transfer-Encoding: Binary"); 
		header("Content-disposition: attachment; filename=\"".$file_name."\""); 
		readfile($file_name);
	}
	
	public function actionUpdateProductGroup()
	{
		$data=ProductGroup::model()->findAll('user_group_id=:parent_id', 
		array(':parent_id'=>(int) $_POST['user_group_id']));
		
		$data=CHtml::listData($data,'id','product_group_name');
		echo CHtml::tag('option',array('value'=>''),'Select group',true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	public function actionUpdateProductCategory()
	{
		//$data=ProductCategory::model()->findAll('user_group_id=:parent_id AND product_group_id=:parent_id1', 
		$data=ProductCategory::model()->findAll('category_id=:parent_id AND sub_category_id=:parent_id1', 
		array(
			  ':parent_id'=>(int) $_POST['user_group_id'],
			  ':parent_id1'=>(int) $_POST['product_group_id']
			  )		
		);
		
		$data=CHtml::listData($data,'id','category_name');
		echo CHtml::tag('option',array('value'=>'0'),'No category',true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	public function actionUpdateProductType()
	{
		$data=ProductType::model()->findAll('user_group_id=:parent_id AND product_group_id=:parent_id1 AND category_id=:parent_id2', 
		array(
			  ':parent_id'=>(int) $_POST['user_group_id'],
			  ':parent_id1'=>(int) $_POST['product_group_id'],
			  ':parent_id2'=>(int) $_POST['product_category_id']
			  )		
		);
		
		$data=CHtml::listData($data,'id','type_name');
		echo CHtml::tag('option',array('value'=>'0'),'No Type',true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	public function actionUpdateProduct()
	{
                $condition  =   'isActive="Y" ';
                if($_POST['user_group_id']!='')
                {
                    $condition  .=  ' AND user_group_id='.$_POST['user_group_id'];
                }
                if($_POST['product_group_id']!='')
                {
                    $condition  .=  ' AND product_group_id='.$_POST['product_group_id'];
                }
                if($_POST['product_category_id']!='')
                {
                    $condition  .=  ' AND product_category_id='.$_POST['user_group_id'];
                }
		$data=CHtml::listData(Product::model()->findAll(array('condition'=>$condition)),'id','product_name');
		echo CHtml::tag('option',array('value'=>''),'Select product',true);
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		}
	}
	
	public function actionDeletefile()
	{
		$id	=	$_POST['id'];
		if($id!=0)
		{
			$files	=	$_POST['file1'];
			$modelname	=	$_POST['model'];
			$model	=	new $modelname;
			$model	=	$model->findByPk($id);
			if($model!=null)
			{
				foreach($files as $eachFile)
				{
					unlink(Yii::app()->basePath.'/../'.$eachFile);
				}
				$model->delete();
			}
		}
	}
	
	
	/* Upload files */
	public function actionCommonupload($folder)
	{
		Yii::import('ext.EAjaxUpload.qqFileUploader');
		$mediaFolder					=	'media/'.$folder.'/';
					
		$allowedExtensions		=	array("jpg","jpeg");
		$sizeLimit				=	700 * 1024 * 1024;// maximum file size in bytes
		$uploader				=	new qqFileUploader($allowedExtensions, $sizeLimit);
		$result 				= 	$uploader->handleUpload($mediaFolder);
		
		$fileName			=	$result['filename'];//GETTING FILE NAME
		$imagename			=	$mediaFolder.$fileName;
		$imagename_thumb	=	$mediaFolder.'/thumbs/'.$fileName;
						
		Yii::import('application.extensions.imagecropper.ImageCropper');
		$cropper=new ImageCropper;
		$cropper->resize_and_crop($imagename, $imagename_thumb, 297, 230, 100 );
		
		$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		echo $return;
		exit;
	}
	
	/*
	*	Ajax function for activation, inactivation, sort order updation, deletion
	*/
	public function actionAjaxupdate()
	{
		$act = $_GET['act'];
		
		if($act	==	'doChangeStatus')
		{
			$model=$this->loadModel($_POST['autoId']);
			$model->isActive	=	($model->isActive=='Y')?'N':'Y';
			$model->save(false);
			$img	=	($model->isActive=='Y')?'active.png':'inactive.png';
			echo CHtml::image("images/admin/".$img,"");
		}
		else if($act=='doSortOrder')
		{
			$sortOrderAll = $_POST['sortOrder'];
			if(count($sortOrderAll)>0)
			{
				foreach($sortOrderAll as $menuId=>$sortOrder)
				{
					$model=$this->loadModel($menuId);
					$model->sortOrder = $sortOrder;
					$model->save(false);
				}
			}
		}
		else
		{           
			$autoIdAll = $_POST['autoId'];
			if(count($autoIdAll)>0)
			{
				foreach($autoIdAll as $autoId)
				{
					$model=$this->loadModel($autoId);
					if($act=='doDelete')
						$model->is_delete = 'Y';
					if($act=='doActive')
						$model->is_active = 'Y';
					if($act=='doInactive')
						$model->is_active = 'N';                     
					if($model->save(false))
						echo 'ok';
					else
						throw new Exception("Sorry",500);
		
				}
			}
		}
	}
	
	
}