<?php

class ProductGroupController 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='product';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * 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',
				),				
				'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 ProductGroup('insert');

		// 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['ProductGroup'])){
			$user_group_id=$_POST['ProductGroup']['user_group_id'];
			foreach($_POST['productGroupName'] as $i=>$eachProductGroupName)
			{
				if(trim($eachProductGroupName)!='')
				{
					$rnd = rand(0,9999);
					$uploadedFile	=	CUploadedFile::getInstanceByName('productGroupImage['.$i.']');
					$uploadedFile_icon	=	CUploadedFile::getInstanceByName('productGroupImage_icon['.$i.']');
					$fileName='';
					$fileName_icon='';
					if(!empty($uploadedFile))  // check if uploaded file is set or not
					{
						$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_group_images/'.$fileName);
						
						/*$imagename	=	Yii::app()->basePath.'/../media/product_group_images/'.$fileName;
						$imagename_thumb	=	Yii::app()->basePath.'/../media/product_group_images/thumbs/'.$fileName;
						Yii::import('application.extensions.imagecropper.ImageCropper');
						$cropper=new ImageCropper;
						$cropper->resize_and_crop($imagename, $imagename_thumb, 741, 267, 80 );*/						
					}
					if(!empty($uploadedFile_icon))  // check if uploaded file is set or not
					{
						$fileName_icon = "{$rnd}-{$uploadedFile_icon}";  // random number + file name
						$uploadedFile_icon->saveAs(Yii::app()->basePath.'/../media/product_group_images/'.$fileName_icon);
						
						/*$imagename	=	Yii::app()->basePath.'/../media/product_group_images/'.$fileName;
						$imagename_thumb	=	Yii::app()->basePath.'/../media/product_group_images/thumbs/'.$fileName;
						Yii::import('application.extensions.imagecropper.ImageCropper');
						$cropper=new ImageCropper;
						$cropper->resize_and_crop($imagename, $imagename_thumb, 741, 267, 80 );*/					
					}
					if(strlen($values)>0)
						$values	.=',';
					$values	.=	'('.$user_group_id.',"'.$eachProductGroupName. '","'.$fileName. '","'.$fileName_icon. '","'.$_POST['show_in_partner'][$i]. '","'.$_POST['description'][$i]. '")';
				}
			}
			if(trim($values)!='')
			{
				$sql = 'INSERT INTO {{_product_group}} (user_group_id, product_group_name, product_group_image, product_group_icon, show_in_partner,description) VALUES ' . $values;
				$command = Yii::app()->db->createCommand($sql);
				$command->execute();
				Yii::app()->user->setFlash('success','Product groups created!');
			}
			else
				$this->redirect(array('create'));
			$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['ProductGroup'])){
			if(($temp=$model->product_group_image)!='')
			{
				$_POST['ProductGroup']['product_group_image'] = $model->product_group_image; 
			}
			if(($temp1=$model->product_group_icon)!='')
			{
				$_POST['ProductGroup']['product_group_icon'] = $model->product_group_icon; 
			}
			$model->attributes=$_POST['ProductGroup'];
			$rnd = rand(0,9999);			
			$uploadedFile	=	CUploadedFile::getInstance($model,'product_group_image');	
			$uploadedFile_icon	=	CUploadedFile::getInstance($model,'product_group_icon');	
			if($temp=='' && !empty($uploadedFile))  // check if uploaded file is set or not
            {
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
				$model->product_group_image = $fileName;
			}
			if($temp1=='' && !empty($uploadedFile_icon))  // check if uploaded file is set or not
            {
				$fileName_icon = "{$rnd}-{$uploadedFile_icon}";  // random number + file name
				$model->product_group_icon = $fileName_icon;
			}
			if($model->save())
			{
				if(!empty($uploadedFile))
				{
					$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_group_images/'.$model->product_group_image);
					/*$imagename	=	Yii::app()->basePath.'/../media/product_group_images/'.$model->product_group_image;
					$imagename_thumb	=	Yii::app()->basePath.'/../media/product_group_images/thumbs/'.$model->product_group_image;
					Yii::import('application.extensions.imagecropper.ImageCropper');
					$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 741, 267, 80 );*/
				}
				if(!empty($uploadedFile_icon))
				{
					$uploadedFile_icon->saveAs(Yii::app()->basePath.'/../media/product_group_images/'.$model->product_group_icon);
					/*$imagename	=	Yii::app()->basePath.'/../media/product_group_images/'.$model->product_group_image;
					$imagename_thumb	=	Yii::app()->basePath.'/../media/product_group_images/thumbs/'.$model->product_group_image;
					Yii::import('application.extensions.imagecropper.ImageCropper');
					$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 741, 267, 80 );*/
				}
				Yii::app()->user->setFlash('success','Product groups updated!');
				$this->redirect(array('Update','id'=>$model->id));
			}
		}

		$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)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model	=	$this->loadModel($id);
			
			@unlink('media/product_group_images/'.$model->product_group_image);
			@unlink('media/product_group_images/'.$model->product_group_icon);
			
			$model->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'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

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

		$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=ProductGroup::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']==='product-group-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
