<?php

class UsersController 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 = '//layouts/column2';

	/**
	 * @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',
				'actions' => array('profile', 'password', 'avatar'),
				'users' => array('@'),
			),
			array(
				'allow',
				'actions' => array('create', 'update', 'edit', 'view', 'delete', 'admin', 'index', 'changeimage', 'changecover', 'changepassword', 'team', 'default', 'setadmin', 'setuser', 'add', 'member', 'editpassword', 'editprofile', 'evaluator'),
				'users' => array('@'),
				'expression' => 'Yii::app()->user->record->level==1',
			),
			array(
				'allow',
				'actions' => array('team', 'verified', 'verifiedteam'),
				'users' => array('@'),
				'expression' => 'Yii::app()->user->record->level==2',
			),
			array(
				'allow',
				'actions' => array('update', 'view', 'changeimage', 'changecover', 'changepassword', 'editprofile', 'editpassword', 'my'),
				'users' => array('@'),
				// 'expression'=>'Yii::app()->user->record->level==3',
			),
			array(
				'allow',
				'actions' => array('team', 'file'),
				'users' => array('@'),
				// 'expression' => 'Yii::app()->user->record->level==2',
			),
			array(
				'deny',
				'users' => array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */

	public function actionView($id)
	{
		$this->layout = "page_user";
		$model = $this->loadModel($id);

		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('view_ajax', array(
				'model' => $this->loadModel($id),
			), false, true);
		} else {
			$model->setScenario('update');
			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];
				if ($model->save())
					Yii::app()->user->setFlash('Success', 'Profile ' . $model->first_name . ' has been update.');
				$this->redirect(array('profile', 'view' => $model->username));
			}
			$this->render('view_ajax', 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 Users;
		$model->setScenario('create');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);


		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			// $model->level = 3;
			$model->image = "default.png";
			$model->password = md5($model->password);
			$model->repeat_password = md5($model->repeat_password);
			if ($model->save())
				//$userid,$description,$activityid,$type,$point,$status
				Activities::model()->my($model->id_user, "Add account " . $model->username, $model->id_user, 5, 50, 6);
			Yii::app()->user->setFlash('Success', 'Account has been created.');
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			// $this->redirect(array('profile','view'=>$model->username));
		}

		$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($view)
	{
		$model = $this->loadProfile($view);
		$model->setScenario('update');
		if ($view == Yii::app()->user->name) {

			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);

			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];

				//$userid,$description,$activityid,$type,$point,$status
				Activities::model()->my($model->id_user, "Update profile " . $model->username, $model->id_user, 8, 2, 7);

				if ($model->save())
					Yii::app()->user->setFlash('Success', 'Profile has been update.');
				// $this->redirect(array('profile', 'view' => $model->username));
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}

			$this->render('update', array(
				'model' => $model,
			));
		} else {
			throw new CHttpException(403, 'You not authorized to this perfom.');
		}
	}

	public function actionEdit($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('update');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			if ($model->save())
				Yii::app()->user->setFlash('Success', 'Profile has been update.');
			// $this->redirect(array('profile', 'view' => $model->username));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}

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

	public function actionChangePassword($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('changePassword');
		if ($id == Yii::app()->user->record->id_user) {

			// Uncomment the following line if AJAX validation is needed
			$this->performAjaxValidation($model);

			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];
				$model->password = md5($model->password);
				$model->repeat_password = md5($model->repeat_password);
				if ($model->save())
					Yii::app()->user->setFlash('Success', 'Password has been update.');
				$this->redirect(array('profile', 'view' => $model->username));
			}

			$this->render('password', array(
				'model' => $model,
			));
		} else {
			throw new CHttpException(403, 'You not authorized to this perfom.');
		}
	}

	/**
	 * 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)
	{
		$model = $this->loadModel($id);
		Member::model()->deleteAll('team_id = :team_id', array(':team_id' => $model->id_user));
		Paper::model()->deleteAll('researchers_id = :researchers_id', array(':researchers_id' => $model->id_user));
		Review::model()->deleteAll('team_id = :team_id', array(':team_id' => $model->id_user));
		$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'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->layout = "page_user";
		$dataProvider = new CActiveDataProvider('Users');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionLogs()
	{
		$dataProvider = new CActiveDataProvider('Activities', array(
			'criteria' => array(
				'condition' => 'user_id = ' . YII::app()->user->id,
				'order' => 'created_date DESC'
			)
		));
		$this->render('logs', array(
			'dataProvider' => $dataProvider,
		));
	}

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

		$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 $id the ID of the model to be loaded
	 * @return Users the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model = Users::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	public function loadModelMember($id)
	{
		$model = Member::model()->findByAttributes(array('team_id'=>$id));
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	public function loadPaper($id)
	{
		$model = Paper::model()->findByAttributes(array('researchers_id' => $id));
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	public function loadProfile($view)
	{
		$model = Users::model()->findByAttributes(array('username' => $view));
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Users $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'users-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}


	public function actionChangeImage($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('changeImage');
		if ($id == Yii::app()->user->record->id_user) {

			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];
				$tmp;
				if (strlen(trim(CUploadedFile::getInstance($model, 'image'))) > 0) {
					$tmp = CUploadedFile::getInstance($model, 'image');
					$model->image = $model->username . '.' . $tmp->extensionName;
				}

				if ($model->save()) {
					if (strlen(trim($model->image)) > 0)
						$tmp->saveAs(Yii::getPathOfAlias('webroot') . '/image/avatar/' . $model->image);
					Users::model()->thumbAvatar($model->image);
					Yii::app()->user->setFlash('Success', 'Avatar ' . $model->first_name . ' has been update.');
					$this->redirect(array('profile', 'view' => $model->username));
				}
			}

			$this->render('image', array(
				'model' => $model,
			));
		} else {
			throw new CHttpException(403, 'You not authorized to this perfom.');
		}
	}

	public function actionDefault($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('team');
		$model->verified = 0;
		$model->save();
		$this->redirect(array('index'));
	}

	public function actionSetAdmin($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('level');
		$model->level = 1;
		$model->save();
		Yii::app()->user->setFlash('Info', '<i>' . $model->first_name . '</i> set as Administrator.');
		$this->redirect(array('index'));
	}

	public function actionSetUser($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('level');
		$model->level = 2;
		$model->save();
		Yii::app()->user->setFlash('Success', '<i>' . $model->first_name . '</i> set as Member.');
		$this->redirect(array('index'));
	}

	public function actionPassword()
	{
		$this->layout = "page_user";
		$model = $this->loadModel(YII::app()->user->id);
		if ($model->id_user == Yii::app()->user->record->id_user) {

			$model->setScenario('changePassword');
			$this->performAjaxValidation($model);

			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];
				$model->password = md5($model->password);
				$model->repeat_password = md5($model->repeat_password);
				if ($model->save()) {
					Yii::app()->user->setFlash('Success', 'Password has been update.');
					$this->redirect(array('password'));
				}
			}

			$this->render('password', array(
				'model' => $model,
			));
		} else {
			throw new CHttpException(403, 'Anda tidak diijinkan merubah password orang lain.');
		}
	}


	public function actionProfile()
	{
		$this->layout = "page_user";

		$model = $this->loadProfile(YII::app()->user->record->username);
		$user = Yii::app()->user->id;

		$model->setScenario('update');
		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			if ($model->save())
				Yii::app()->user->setFlash('Success', 'Profile ' . $model->fullname . ' has been update.');
			$this->redirect(array('profile'));
		}


		$this->render('view_ajax', array(
			'model' => $this->loadProfile(YII::app()->user->record->username),

		));
	}


	public function actionFile()
	{
		$this->layout = "page_user";

		$model = $this->loadProfile(YII::app()->user->record->username);
		$user = Yii::app()->user->id;

		$model->setScenario('update');
		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			$model->status = 0;
			$tmp;
			if (strlen(trim(CUploadedFile::getInstance($model, 'image'))) > 0) {
				$tmp = CUploadedFile::getInstance($model, 'image');
				$model->image = uniqid() . "-" . time() . '.' . $tmp->extensionName;
			}
			if ($model->save()) {
				$paper = $this->loadPaper($model->id_user);
				$paper->status = 0;
				$paper->update();

				if (strlen(trim($model->image)) > 0) {
					$tmp->saveAs(Yii::getPathOfAlias('webroot') . '/image/files/document/' . $model->image);
				}

				Activities::model()->my("Peserta an. " . YII::app()->user->record->fullname . " Upload Ulang File Dokumen Pernyataan", 1, 7, 1, 1, 1);
				// Yii::app()->user->setFlash('Success', 'Profile ' . $model->fullname . ' has been update.');
				$this->redirect(array('integration/users/my'));
			}
		}


		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('view_file', array(
				'model' => $this->loadProfile(YII::app()->user->record->username),
			), false, true);
		} else {
			$this->render('view_file', array(
				'model' => $this->loadProfile(YII::app()->user->record->username),
			));
		}
	}


	public function actionMember($name)
	{
		$this->layout = "page_user";
		$model = $this->loadProfile($name);
		$user = Yii::app()->user->id;

		$model->setScenario('update');
		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			if ($model->save())
				Yii::app()->user->setFlash('Success', 'Profile ' . $model->first_name . ' has been update.');
			$this->redirect(array('profile', 'view' => $model->username));
		}


		$this->render('view_ajax', array(
			'model' => $this->loadProfile($name),

		));
	}

	public function actionAvatar($id)
	{
		$model = $this->loadModel($id);
		if (is_array($_FILES)) {
			if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
				$sourcePath = $_FILES['userImage']['tmp_name'];
				$temp = explode(".", $_FILES['userImage']['name']);
				$newfilename = $model->username . '.' . end($temp);
				$targetPath = "image/avatar/" . $newfilename;
				$model->image = $newfilename;
				$this->is_image($targetPath);
				$model->save();

				if (move_uploaded_file($sourcePath, $targetPath)) {
					Yii::app()->end('Foto Profil ' . $newfilename . ' Berhasil di Perbaharui', true);
					return;
				}
			}
		}
	}


	function is_image($path)
	{
		$a = getimagesize($path);
		$image_type = $a[2];

		if (in_array($image_type, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) {
			return true;
		} else {
			Yii::app()->end('Foto Profil anda Tidak Valid', true);
			return false;
		}
	}


	public function actionEditPassword($id)
	{
		$this->layout = "page_user";
		$model = $this->loadModel($id);

		$model->setScenario('changePassword');
		$this->performAjaxValidation($model);

		if (Yii::app()->user->record->level == 1) {

			if (isset($_POST['Users'])) {
				$model->attributes = $_POST['Users'];
				$model->password = md5($model->password);
				$model->repeat_password = md5($model->repeat_password);
				if ($model->save()) {
					Yii::app()->user->setFlash('Success', 'Password has been update.');
					$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
					// $this->redirect(array('profile', 'view' => $model->username));
				}
			}
			$this->render('password', array(
				'model' => $model,
			));
		} else {

			if ($model->id_user == Yii::app()->user->record->id_user) {

				if (isset($_POST['Users'])) {
					$model->attributes = $_POST['Users'];
					$model->password = md5($model->password);
					$model->repeat_password = md5($model->repeat_password);
					if ($model->save()) {
						Yii::app()->user->setFlash('Success', 'Password has been update.');
						$this->redirect(array('profile', 'view' => $model->username));
					}
				}
				$this->render('password', array(
					'model' => $model,
				));
			} else {
				throw new CHttpException(403, 'Anda tidak diijinkan merubah password orang lain.');
			}
		}
	}


	public function actionEditProfile()
	{
		$model = $this->loadProfile(YII::app()->user->name);
		$user = Yii::app()->user->id;

		$model->setScenario('update');
		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			if ($model->save()) {
				Yii::app()->user->setFlash('Success', 'Profile ' . $model->first_name . ' has been update.');
				$this->redirect(array('site/dashboard'));
			}
		}
		if (YII::app()->user->record->level != 1) {
			$this->layout = "page_user";
		}
		$this->render('view_ajax_edit', array(
			'model' => $this->loadProfile(YII::app()->user->name),

		));
	}

	public function actionTeam()
	{
		if (Yii::app()->user->record->level == 3) {
			$this->redirect(array('my'));
		}

		$model = new Users('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Users']))
			$model->attributes = $_GET['Users'];

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

	public function actionMy()
	{
		$dataProvider = new CActiveDataProvider('Users', array(
			'criteria' => array(
				'condition' => 'id_user = ' . YII::app()->user->id,
			)
		));
		$this->render('my', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionEvaluator()
	{
		$dataProvider = new CActiveDataProvider('Users', array(
			'criteria' => array(
				'condition' => 'level = 2',
			)
		));
		$this->render('evaluator', array(
			'dataProvider' => $dataProvider,
		));
	}



	public function actionVerifiedTeam()
	{
		$dataProvider = new CActiveDataProvider('Users', array(
			'criteria' => array(
				'condition' => 'level=3 AND status=1 AND status_video=1',
			)
		));
		$this->render('verified_team', array(
			'dataProvider' => $dataProvider,
		));
	}
}
