<?php
class ProductController 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','updateProductGroup','updateProductCategory','updateProduct','updateProductType','deleteproductimage','upload','download','deletefile','mapptoanother'
				),				
				'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 Product;
		$model2	=	array( new ProductFeatureRelation );
		$model3	=	array( new ProductDownloadableRelation );
		$model4	= 	array(new ProductImages);
		$mappingModel	=	array (new ProductMapping);
		// 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['Product'])){
			Yii::import('application.extensions.imagecropper.ImageCropper');
			$rnd = rand(0,9999);
			$model->attributes	=	$_POST['Product'];			
			$uploadedFile=CUploadedFile::getInstance($model,'product_image');	
			if(!empty($uploadedFile))  // check if uploaded file is set or not
            {
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);  // random number + file name
				$model->product_image = $fileName;
			}
			$valid = $model->validate();
			$mappingModel	=	array(new ProductMapping);
			$i=0;
			if(is_array($_POST['ProductMapping']))
			foreach ( $_POST['ProductMapping'] as $i => $productMapping )  
			{
				if($productMapping['user_group_id']!='')
				{
					$mappingModel[$i] = new ProductMapping;
					//$mappingModel[$i]->product_id 	=	$model->id;
					$mappingModel[$i]->user_group_id 	=	$productMapping['user_group_id'];
					$mappingModel[$i]->product_group_id 	 	=	$productMapping['product_group_id'];
					$mappingModel[$i]->category_id 	=	$productMapping['category_id'];
					$mappingModel[$i]->type_id  	=	$productMapping['type_id'];
				}
			}
			$i++;
			if(is_array($_POST['user_group_id']))
			foreach($_POST['user_group_id'] as $j => $value )
			{
				if($_POST['user_group_id'][$j]!='')
				{
					$mappingModel[$i+$j] = new ProductMapping;
					//$mappingModel[$i+$j]->product_id 	=	$model->id;
					$mappingModel[$i+$j]->user_group_id 	=	$_POST['user_group_id'][$j];
					$mappingModel[$i+$j]->product_group_id 	 	=	$_POST['product_group_id'][$j];
					$mappingModel[$i+$j]->category_id 	=	$_POST['category_id'][$j];
					$mappingModel[$i+$j]->type_id  	=	$_POST['type_id'][$j];
				}
			}
			if(is_array($_POST['ProductImagesId']))
			foreach ($_POST['ProductImagesId'] as $i=>$eachImage)
			{
				$model4[$i]	=	new ProductImages;
			}
			foreach ( $_POST['ProductFeatureRelation']['feature_id'] as $i => $productFeature )  
			{
				$model2[$i] = new ProductFeatureRelation;
				$model2[$i]->feature_id	=	$productFeature;
				$model2[$i]->feature_value	=	$_POST['ProductFeatureRelation']['feature_value'][$i];
				$valid = $valid && $model2[$i]->validate();               
			}
			foreach ( $_POST['ProductDownloadableRelation']['item_id'] as $i => $productDownloadable ) 
			{
				$model3[$i] = new ProductDownloadableRelation;
				$model3[$i]->item_id	=	$productDownloadable;
				$model3[$i]->item_value	=	$_POST['ProductDownloadableRelation']['item_value'][$i];
				$valid = $valid && $model3[$i]->validate();               
			}
			if($valid	&&	$model->save())			
			{
				if(!empty($uploadedFile))
				{
					$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_images/'.$fileName);
					$imagename	=	Yii::app()->basePath.'/../media/product_images/'.$model->product_image;
					$imagename_thumb	=	Yii::app()->basePath.'/../media/product_images/thumbs/'.$model->product_image;
					
					/*$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
					$imagename_resized	=	Yii::app()->basePath.'/../media/product_images/image_resized/'.$model->product_image;					
					Yii::import("ext.EPhpThumb.EPhpThumb");
					
					$thumb=new EPhpThumb();
					$thumb->init(); //this is needed
					//chain functions
					$thumb->create($imagename)->resize(500,350)->save($imagename_resized);
					$thumb->create($imagename)->resize(300,300)->save($imagename_thumb);
				}
				$product_id	=	$model->id;	
				if(is_array($mappingModel))
				foreach($mappingModel as $eachmappingModel)
				{
					$eachmappingModel->product_id	=	$product_id;
					$eachmappingModel->save();
				}			
				foreach ( $model2 as $i => $m2 ) 
				{
					$m2->product_id = $product_id;
					$m2->save();
            	}
				//$uploadedFile	=	CUploadedFile::getInstancesByName('ProductDownloadableRelationFF');
				foreach ( $model3 as $i => $m3 ) 
				{
					$m3->product_id	= $product_id;					
					$rnd = rand(0,9999);
					$uploadedFile	=	CUploadedFile::getInstanceByName('ProductDownloadableRelationFF['.$i.']');
					$fileName='';
					if(!empty($uploadedFile))  // check if uploaded file is set or not
					{
						$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);  // random number + file name
						$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_item_downloadables/'.$fileName);
						$m3->files_available	=	$fileName;
					}
					
					$m3->save();
            	}
				
				foreach($model4 as $i=>$m4)
				{
					$m4->product_id	= $product_id;					
					$rnd = rand(0,9999);
					$uploadedFile	=	CUploadedFile::getInstanceByName('ProductImagesFF['.$i.']');
					$fileName='';
					if(!empty($uploadedFile))  // check if uploaded file is set or not
					{
						$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);  // random number + file name
						$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_images/'.$fileName);
						$m4->product_image	=	$fileName;
						
						$imagename	=	Yii::app()->basePath.'/../media/product_images/'.$m4->product_image;
						$imagename_thumb	=	Yii::app()->basePath.'/../media/product_images/thumbs/'.$m4->product_image;
						
						/*$cropper=new ImageCropper;
						$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
						$imagename_resized	=	Yii::app()->basePath.'/../media/product_images/image_resized/'.$m4->product_image;					
						Yii::import("ext.EPhpThumb.EPhpThumb");
						
						$thumb=new EPhpThumb();
						$thumb->init(); //this is needed
						//chain functions
						$thumb->create($imagename)->resize(500,350)->save($imagename_resized);
						$thumb->create($imagename)->resize(300,300)->save($imagename_thumb);
						$m4->save(false);
					}
					
									
				}
				
				Yii::app()->user->setFlash('success', "Product saved!");				
				if(isset($_POST['yt0']))
					$this->redirect(array('create'));
				else if(isset($_POST['yt2']))
					$this->redirect(array('index'));
				else
				{
					$model->id='';
					$model->isNewRecord = true;
				}
				}
		}
		$this->render('create',array(
			'model'=>$model,
			'model2'=>$model2,
			'model3'=>$model3,
			'model4'=>$model4,
			'mappingModel'=>$mappingModel,
		));
	}

	public function actionDeleteproductimage()
	{
		$id	=	$_POST['id'];
		$model	=	ProductImages::model()->findByPk($id);
		if($model!=null)
		{
		@unlink(Yii::app()->basePath.'/../media/product_images/'.$model->product_image);
		@unlink(Yii::app()->basePath.'/../media/product_images/thumbs/'.$model->product_image);
		@unlink(Yii::app()->basePath.'/../media/product_images/image_resized/'.$model->product_image);
		$model->delete();
		}
	}
	/**
	 * 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);
		$model2	=	ProductFeatureRelation::model()->findAll(array('condition'=>'product_id='.$model->id));
		if(count($model2)==0)
		$model2	=	array( new ProductFeatureRelation );
		$model3	=	ProductDownloadableRelation::model()->findAll(array('condition'=>'product_id='.$model->id));
		if(count($model3)==0)
		$model3	=	array( new ProductDownloadableRelation );
		
		$model4	=	ProductImages::model()->findAll(array('condition'=>'product_id='.$model->id));
		if(count($model4)==0)
		$model4	=	array( new ProductImages );
		$mappingModel	=	ProductMapping::model()->findAll(array('condition'=>'product_id='.$model->id));
		if(count($mappingModel)==0)
		$mappingModel	=	array (new ProductMapping);
		// 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['Product'])){
			Yii::import('application.extensions.imagecropper.ImageCropper');
			/*if(($temp=$model->product_image)!='')
			{
				$_POST['Product']['product_image'] = $model->product_image; 
			}*/
			$model->attributes=$_POST['Product'];
			
			ProductFeatureRelation::model()->deleteAll('product_id='.$model->id);
			ProductDownloadableRelation::model()->deleteAll('product_id='.$model->id);
			ProductMapping::model()->deleteAll('product_id='.$model->id);
			//echo 'Working on<pre>';
			$mappingModel	=	array(new ProductMapping);
			$i=0;
			if(is_array($_POST['ProductMapping']))
			foreach ( $_POST['ProductMapping'] as $i => $productMapping )  
			{
				if($productMapping['user_group_id']!='')
				{
					$mappingModel[$i] = new ProductMapping;
					//$mappingModel[$i]->product_id 	=	$model->id;
					$mappingModel[$i]->user_group_id 	=	$productMapping['user_group_id'];
					$mappingModel[$i]->product_group_id 	 	=	$productMapping['product_group_id'];
					$mappingModel[$i]->category_id 	=	$productMapping['category_id'];
					$mappingModel[$i]->type_id  	=	$productMapping['type_id'];
				}
			}
			$i++;
			if(is_array($_POST['user_group_id']))
			foreach($_POST['user_group_id'] as $j => $value )
			{
				if($_POST['user_group_id'][$j]!='')
				{
					$mappingModel[$i+$j] = new ProductMapping;
					//$mappingModel[$i+$j]->product_id 	=	$model->id;
					$mappingModel[$i+$j]->user_group_id 	=	$_POST['user_group_id'][$j];
					$mappingModel[$i+$j]->product_group_id 	 	=	$_POST['product_group_id'][$j];
					$mappingModel[$i+$j]->category_id 	=	$_POST['category_id'][$j];
					$mappingModel[$i+$j]->type_id  	=	$_POST['type_id'][$j];
				}
			}
			
			
			$rnd = rand(0,9999);			
			$uploadedFile	=	CUploadedFile::getInstance($model,'product_image');	
			if($temp=='' && !empty($uploadedFile))  // check if uploaded file is set or not
            {
				$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);  // random number + file name
				$model->product_image = $fileName;
			}
			$valid = $model->validate();
			if(is_array($_POST['ProductFeatureRelation']['feature_id']))				
			foreach ( $_POST['ProductFeatureRelation']['feature_id'] as $i => $productFeature )  
			{
				$model2[$i] = new ProductFeatureRelation;
				$model2[$i]->feature_id	=	$productFeature;
				$model2[$i]->feature_value	=	$_POST['ProductFeatureRelation']['feature_value'][$i];
				$valid = $valid && $model2[$i]->validate();               
			}
			if(is_array($_POST['ProductDownloadableRelation']['item_id']))
			foreach ( $_POST['ProductDownloadableRelation']['item_id'] as $i => $productDownloadable ) 
			{
				$model3[$i] = new ProductDownloadableRelation;
				$model3[$i]->item_id	=	$productDownloadable;
				$model3[$i]->item_value	=	$_POST['ProductDownloadableRelation']['item_value'][$i];
				$model3[$i]->files_available	=	$_POST['ProductDownloadableRelationFFh'][$i];
				$valid = $valid && $model3[$i]->validate();               
			}
			
			if(is_array($_POST['ProductImagesId']))
			foreach ($_POST['ProductImagesId'] as $i=>$eachImage)
			{
				$model4[$i]	=	new ProductImages;
				$model4[$i]->product_image	=	$_POST['ProductImagesFFh'][$i];
			}

			if($valid && $model->save())
			{
				if(!empty($uploadedFile))
				{
					$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_images/'.$model->product_image);
					$imagename	=	Yii::app()->basePath.'/../media/product_images/'.$model->product_image;
					$imagename_thumb	=	Yii::app()->basePath.'/../media/product_images/thumbs/'.$model->product_image;					
					$imagename_resized	=	Yii::app()->basePath.'/../media/product_images/image_resized/'.$model->product_image;					
					Yii::import("ext.EPhpThumb.EPhpThumb");
					
					$thumb=new EPhpThumb();
					$thumb->init(); //this is needed
					//chain functions
					$thumb->create($imagename)->resize(500,350)->save($imagename_resized);
					$thumb->create($imagename)->resize(300,300)->save($imagename_thumb);

					
					/*$cropper=new ImageCropper;
					$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
				}
				if(is_array($mappingModel))
				foreach($mappingModel as $eachmappingModel)
				{
					if($eachmappingModel->user_group_id!='' && $eachmappingModel->product_group_id!='')
					{
						$eachmappingModel->product_id	=	$model->id;
						$eachmappingModel->save();
					}
				}
				foreach ( $model2 as $i => $m2 ) 
				{
					$m2->product_id = $model->id;
					$m2->save();
            	}

				
				foreach ( $model3 as $i => $m3 ) 
				{
					$rnd = rand(0,9999);
					$uploadedFile	=	CUploadedFile::getInstanceByName('ProductDownloadableRelationFF['.$i.']');
					
					$fileName='';
					if(!empty($uploadedFile))  // check if uploaded file is set or not
					{
						
						$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);
						$stringWithoutNonLetterCharacters = preg_replace("/[\/\&%#\$]/", "_", $uploadedFile);
						///----/// 
						$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_item_downloadables/'.$fileName);
						$m3->files_available	=	$fileName;
					}
					
					$m3->product_id = $model->id;
					$m3->save();
            	}
				
				foreach($model4 as $i=>$m4)
				{
					$m4->product_id	= $model->id;					
					$rnd = rand(0,9999);
					$uploadedFile	=	CUploadedFile::getInstanceByName('ProductImagesFF['.$i.']');
					$fileName='';
					if(!empty($uploadedFile))  // check if uploaded file is set or not
					{
						$fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
						$fileName	=	str_replace(array('+'," "),'_',$fileName);
						$uploadedFile->saveAs(Yii::app()->basePath.'/../media/product_images/'.$fileName);
						$m4->product_image	=	$fileName;
						
						$imagename	=	Yii::app()->basePath.'/../media/product_images/'.$m4->product_image;
						$imagename_thumb	=	Yii::app()->basePath.'/../media/product_images/thumbs/'.$m4->product_image;
						$imagename_resized	=	Yii::app()->basePath.'/../media/product_images/image_resized/'.$m4->product_image;					
						/*$cropper=new ImageCropper;
						$cropper->resize_and_crop($imagename, $imagename_thumb, 230, 143, 80 );*/
						Yii::import("ext.EPhpThumb.EPhpThumb");
					
						$thumb=new EPhpThumb();
						$thumb->init(); //this is needed
						
						//chain functions
						$thumb->create($imagename)->resize(500,350)->save($imagename_resized);
						$thumb->create($imagename)->resize(300,300)->save($imagename_thumb);
						$m4->save(false);
					}
					
									
				}
				
				Yii::app()->user->setFlash('success', "Product saved!");
				$this->redirect(array('index'));
			}
		}
		$this->render('update',array(
			'model'=>$model,'model2'=>$model2,'model3'=>$model3,'model4'=>$model4,'mappingModel'=>$mappingModel
		));
	}

	/**
	 * 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
			$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'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all models.
	 */

	public function actionIndex($isFeaturedItem=null,$isIntoPromotion=null)
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if($isFeaturedItem!=nul)
			$model->isFeaturedItem	=	$isFeaturedItem;
		if($isIntoPromotion!=nul)
			$model->isIntoPromotion	=	$isIntoPromotion;
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];
		$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=Product::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-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}	
	
	public function actionMapptoanother()
	{
		$this->renderPartial('_mapping','',false,true);
	}
}