<?php

class CaseStudyController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='resource';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','update','admin','delete','ajaxupdate','updateProductGroup','updateProductCategory','updateProduct','frontStatusChange'
				),				
				'expression'=>'$user->isAdmin()'
				),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Paper;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0 && isset($_POST['Paper'])){
			$rnd = rand(0,9999);  // generate random number between 0-9999
			$model->attributes=$_POST['Paper'];
			$uploadedFile=CUploadedFile::getInstance($model,'filename');
                        $uploadedImage=CUploadedFile::getInstance($model,'image');
			if(!empty($uploadedFile) && !empty($uploadedImage))  // check if uploaded file is set or not
                        {
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
				$model->filename = $fileName;
                                $imagefileName = "{$rnd}-{$uploadedImage}";  // random number + file name
				$model->image = $imagefileName;
			}			
			$model->date_added	=	date('Y-m-d');
			$model->isActive	=	'Y';
			if($model->save())
			{
				if(!empty($uploadedFile) && !empty($uploadedImage))
				{
					$uploadedFile->saveAs(Yii::app()->basePath.'/../media/paper/'.$fileName);  // image will uplode to rootDirectory/banner/
                                        $uploadedImage->saveAs(Yii::app()->basePath.'/../media/casestudy/'.$imagefileName);  // image will uplode to rootDirectory/banner/
				   
                                         $imagename = Yii::app()->basePath.'/../media/casestudy/'.$imagefileName;
					$imagename_thumb = Yii::app()->basePath.'/../media/casestudy/thumb/'.$imagefileName;
					
					/*$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
					
					Yii::import("ext.EPhpThumb.EPhpThumb");
					$thumb=new EPhpThumb();
					$thumb->init(); 
					$thumb->create($imagename)->resize(180,200)->save($imagename_thumb);
                                        
                                        
                                }	
                                Yii::app()->user->setFlash('success','Successfully added');			
				$this->redirect(array('index'));
				
			}
                        
                        /*$uploadedImage=CUploadedFile::getInstance($model,'image');
			if(!empty($uploadedImage))  // check if uploaded file is set or not
                        {
				$imagefileName = "{$rnd}-{$uploadedImage}";  // random number + file name
				$model->image = $imagefileName;
                                if(!empty($uploadedImage))
				{
					$uploadedImage->saveAs(Yii::app()->basePath.'/../media/casestudy/'.$imagefileName);  // image will uplode to rootDirectory/banner/
				}	
				Yii::app()->user->setFlash('success','Successfully added');			
				$this->redirect(array('index'));
			}*/
                        
				
			
                        
                        
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
        
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0 && isset($_POST['Paper'])){
                     
			if($model->filename!='')
			{
				$_POST['Paper']['filename'] = $model->filename; 
			}
                        $uploadedFileName = $model->filename;
                        $uploadedFIamgeName = $model->image;
                        
			$model->attributes=$_POST['Paper'];
			$rnd = rand(0,9999);			
			$uploadedFile=CUploadedFile::getInstance($model,'filename'); 
                        $uploadedImage=CUploadedFile::getInstance($model,'image');
                        
			if(!empty($uploadedFile) || !empty($uploadedImage))  // check if uploaded file is set or not
                        {
                            if(!empty($uploadedFile)){
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
				$model->filename = $fileName;
                              }
                              else{
                                  $model->filename = $uploadedFileName;
                              }
                              if(!empty($uploadedImage)){
                                $imagefileName = "{$rnd}-{$uploadedImage}";  // random number + file name
				$model->image = $imagefileName;
                              }
                              else{
                                  $model->image = $uploadedFIamgeName;
                              }
			}
                        else{
                            $model->filename = $uploadedFileName;
                            $model->image = $uploadedFIamgeName;
                        }
                       
			$model->date_added	=	date('Y-m-d');
			$model->isActive	=	'Y';
			if($model->save())
			{   
				if(!empty($uploadedFile) || !empty($uploadedImage))
				{ 
                                     if(!empty($uploadedFile))
					$uploadedFile->saveAs(Yii::app()->basePath.'/../media/paper/'.$fileName);  // image will uplode to rootDirectory/banner/
                                     if(!empty($uploadedImage)) { 
                                        $uploadedImage->saveAs(Yii::app()->basePath.'/../media/casestudy/'.$imagefileName);  // image will uplode to rootDirectory/banner/
				
                                        $imagename = Yii::app()->basePath.'/../media/casestudy/'.$imagefileName;
					$imagename_thumb = Yii::app()->basePath.'/../media/casestudy/thumb/'.$imagefileName;
					
					/*$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
					
					Yii::import("ext.EPhpThumb.EPhpThumb");
					$thumb=new EPhpThumb();
					$thumb->init(); 
					$thumb->create($imagename)->resize(180,210)->save($imagename_thumb);
                                     } 
                                        
                                }	
                                Yii::app()->user->setFlash('success','Successfully added');			
				$this->redirect(array('index'));
				
			}
                        
                        
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Paper('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Paper']))
			$model->attributes=$_GET['Paper'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Paper::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='paper-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionFrontStatusChange($id)
	{
		$model=$this->loadModel($id);
		$model->isActive	=	($model->isActive=='Y')?'N':'Y';
		$model->save(false);
		$this->redirect(array('site/index'));
	}
}
