<?php

class PortalController extends Controller
{
	public function accessRules() {
		return array(
			array('allow', // allow all users to perform 'index' and 'view' actions
			  'actions' => array('login', 'error', 'logout'),
			  'users' => array('*'),
			  ),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
			  'actions' => array('Index','Create','GetList','Save','Delete', 'UnBlockPortal','BlockPortal','UploadPortalImage'),
			  'expression' => '$user->isMember()',
			  ),
			array('deny', // deny all users
			  'users' => array('*'),
			  ),
			);
	}
public function actionIndex()
{
	$this->render('index');
}



public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	public function actionGetList()
	{
			$model=new MasPortal();
			$draw    = $_POST['draw'];
			$offset = $_POST['start'];
			$limit  = $_POST['length'];
			$columns = array(
			   0 =>'id',
			   1 =>'portal_name',
			   2 => 'sort_order',
			   3 => 'return_url',
			   );
			$filterColumn = $columns[$_POST['order'][0]['column']];
			$filterOrder  = $_POST['order'][0]['dir'];
			$orderBy   = $filterColumn." ".$filterOrder;
			$condition = '1=1';
			if(isset($_POST['search']['value']) && $_POST['search']['value']!="")
			{
			  $searchString = $_POST['search']['value'];
			 $condition ="  (portal_name LIKE '%".$searchString."%' OR sort_order  LIKE '%".$searchString."%')";
			}
			$count = $model->count(array('condition'=>$condition));
			$model=$model->findAll(array('condition'=>$condition,'limit'=>$limit,'offset'=>$offset,'order'=>$orderBy));
			$recordsTotal = $count;
			$recordsFiltered = $count;
			$data['draw'] = $draw;
			$data['recordsTotal'] = $recordsTotal;
			$data['recordsFiltered'] = $recordsFiltered;
			$rowData=array();
			$m = 1;
			
			foreach ($model as $row)
			{
				$div = '';
				//if(Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["mas_inv_rack_edit"])){
					$div .= '<button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'Portal/create&id='.$row['id'].'\',\'Edit Portal\',\'lg\')"><i class="fa fa-pencil"></i></button>';
			  // }
			   // if(Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["mas_inv_rack_delete"])){
			   //     $div .=  '<a href ="#" class="btn btn-danger btn-xs" onclick="deletePortal('.$row['id'].')"><i class="fa fa-trash-o "></i></a>';
			 //   }

			 //if(isset(Yii::app()->user->havePermissionOn['mas_Portal_disable']) ||  Yii::app()->user->authorised_user == 1)
			//{

			  if ($row->isActive == "Y") 
			  {
				$div .= ' <a href ="javascript:void(0);" class="btn btn-success btn-xs" onclick="disablePortal(' . $row['id'] . ')"><i class="fa fa-toggle-on"></i></a>';
			  }
			  if ($row->isActive == 'N') 
			  {
					$div .= ' <a href ="javascript:void(0);" class="btn btn-danger btn-xs" onclick="enablePortal(' . $row['id'] . ')"><i class="fa fa-ban"></i></a>';
			  }            
			
			//}
				   $rowData[]=array($m,
					   $row['portal_name'],
					   $row['sort_order'],
					   $row['return_url'],
					   '<div class="btn-wrap">'.$div.'</div>',
					   $row['isActive'],
					  );
			
				$m++;
				
			}

			$data['data'] = $rowData;
			echo json_encode($data);
	}


	public function actionCreate()
	{
		$model=new MasPortal();
		$id = (int) Yii::app()->request->getParam('id');
		if($id>0){
			$model=$model->findByPk($id);
		}
			Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false,'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
		$this->render('create', array('model' => $model), false, false);
	}


public function actionSave()
{
		$model = new MasPortal();
		if (isset($_POST['MasPortal']))
		{
		$model->created_by = Yii::app()->user->id;
			$model->created_datetime =date('Y-m-d h:i:s');
		if ((int) @$_POST['MasPortal']['id'] > 0)
			{   $model->updated_by = Yii::app()->user->id;
				$model->updated_datetime =date('Y-m-d h:i:s');
				$id= (int) @$_POST['MasPortal']['id'];
				$model=$model->findByPk($id); 
				$audit_type = 'UPDATED'; 
				$edit_flag=1;
			}else{
			  $audit_type = 'CREATED';
			}
			$model->attributes=$_POST['MasPortal'];
			if ($model->save())
			{
				
				// 	// inserting to audit log
				// 	AuditLog::saveAuditLogs(
				// 	  'Portal_MASTER',
				// 	  Yii::app()->user->id,
				// 	  $audit_type,
				// 	  " with code: - {$model->portal_name}  "
				//   );
				  // end audit log
					$jsonData['status'] = 'success';
					$jsonData['frm'] = $_POST['rack_form'];
					$jsonData['id'] = $model->id;
				echo CJSON::encode($jsonData);
			}
			else
			{
					$error = CActiveForm::validate($model, '', false);
					if ($error != '[]')
				   echo $error;
			}
	  
		}
}


public function actionDelete()
{
  $id = $_POST['id'];
	$model=new MasPortal();
	$del = $model->findByPk($id); // audit log changes
	$model->deleteByPk($id);
	// inserting to audit log
// 	AuditLog::saveAuditLogs(
// 	  'Portal_MASTER',
// 	  Yii::app()->user->id,
// 	  'DELETED',
// 	  " with code: - {$del->portal_name}  "
//   );
	echo "success";
}



public function actionBlockPortal() 
{
  $id = $_POST['id'];
  if ($id > 0) {
	MasPortal::model()->updateByPK($id, array('isActive' => "N"));
	 // inserting to audit log
	 $model=new MasPortal();
	 $upt = $model->findByPk($id); // audit log changes
	//  AuditLog::saveAuditLogs(
	// 	 'Portal_MASTER',
	// 	 Yii::app()->user->id,
	// 	 'BLOCKED',
	// 	 " with name: - {$upt->portal_name}  "
	//  );
	// end audit log
	  $status['status'] = 'success';
  } else {
	  $status['status'] = 'error';
  }
  echo CJSON::encode($status);
}

public function actionUnBlockPortal() {
  $id = $_POST['id'];
  if ($id > 0) {
	MasPortal::model()->updateByPK($id, array('isActive' => "Y"));
	 // inserting to audit log
	 $model=new MasPortal();
	 $upt = $model->findByPk($id); // audit log changes
	//  AuditLog::saveAuditLogs(
	// 	 'Portal_MASTER',
	// 	 Yii::app()->user->id,
	// 	 'UNBLOCKED',
	// 	 " with name: - {$upt->portal_name}  "
	//  );
	// end audit log
	  $status['status'] = 'success';
  } else {
	  $status['status'] = 'error';
  }
  echo CJSON::encode($status);
}

    
public function actionUploadPortalImage($folder = null) {
	Yii::import("ext.EAjaxUpload.qqFileUploader");
	$field_id = "";
	if(isset($_GET['field_id']))
	{
		$field_id = Yii::app()->request->getParam('field_id');
	}
	
	$folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
	// make the directory to store the pic:
	if (!is_dir($folder)) {
		mkdir($folder, 0777, TRUE);
	}
	$allowedExtensions = array("jpg", "jpeg", "gif","png"); //array("jpg","jpeg","gif","exe","mov" and etc...
	$sizeLimit = 2 * 1024 * 1024; // maximum file size in bytes
	$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
	$result = $uploader->handleUpload($folder);
	$result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
	$result['field_id'] = $field_id;
	$return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	$fileName = $result['filename']; //GETTING FILE NAME
	$imagename	=	Yii::app()->basePath.'/../uploads/portalimages/'.$fileName;
	$imagename_thumb	=	Yii::app()->basePath.'/../uploads/portalimages/'.$fileName;
	Yii::import("ext.EPhpThumb.EPhpThumb");
	$thumb=new EPhpThumb();
	$thumb->init(); //this is needed
	//chain functions
	$thumb->create($imagename)->resize(120,120)->save($imagename_thumb);
	echo $return; // it's array
}

}