<?php

class SiteController extends Controller
{
	public $debugMode = true;
	/**
	* Declares class-based actions.
	*/
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha' => array(
				'class' => 'CCaptchaAction',
				// 'backColor'=>0xFFFFFF,
				'foreColor' => 0x000000,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page' => array(
				'class' => 'CViewAction',
			),

		);
	}


	public function accessRules()
	{
		return array('allow', 'actions' => array('captcha'), 'users' => array('*'));
	}


	/**
	* Displays the : Intro Site
	*/
	public function actionIndex()
	{
		if (Yii::app()->user->isGuest) {
			$this->actionRegister();
		} else {
			$this->actionLogin();
		}
	}

	/**
	* Displays the : Backend Site
	*/
	public function actionDashboard()
	{
		if (Yii::app()->user->isGuest) {

			$this->redirect(array('site/login'));
		} else {
			if (YII::app()->user->record->level == 2 || YII::app()->user->record->level == 3) :
				$this->layout = "page_user";
		endif;
		$this->layout = "page_user";
		$this->render('index');
	}
}

public function getToken($token)
{
	$model = Users::model()->findByAttributes(array('token' => $token));
	if ($model === null)
		throw new CHttpException(404, 'Token anda tidak valid atau telah kadaluarsa.');
	return $model;
}

public function loadEmail($email)
{
	$model = Users::model()->findByAttributes(array('email' => $email));
	if ($model === null)
		throw new CHttpException(404, 'Email yang anda masukan tidak terdaftar dalam sistem kami.');
	return $model;
}

public function loadUsers($id)
{
	$model = Users::model()->findBypk($id);
	if ($model === null)
		throw new CHttpException(404, 'Data tidak ditemukan.');
	return $model;
}

public function loadPaper($id)
{
	$model = Paper::model()->findByAttributes(array('researchers_id' => $id));
	if ($model === null)
		throw new CHttpException(404, 'Data Tidak diTemukan.');
	return $model;
}


public function loadActivities($id)
{
	$model = Activities::model()->findBypk($id);
	if ($model === null)
		throw new CHttpException(404, 'Data tidak ditemukan.');
	return $model;
}

	/**
	* This is the action to handle external exceptions.
	*/
	public function actionError()
	{
		$this->layout = "error";
		if ($error = Yii::app()->errorHandler->error) {
			if (Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	* Displays the login page
	*/
	public function actionLogin()
	{
		if (Yii::app()->user->isGuest) {
			$model = new LoginForm;

			$this->layout = "signin";

			// if it is ajax validation request
			if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
				echo CActiveForm::validate($model);
				Yii::app()->end();
			}

			// collect user input data
			if (isset($_POST['LoginForm'])) {
				$model->attributes = $_POST['LoginForm'];

				// validate user input and redirect to the previous page if valid
				if ($model->validate() && $model->login()) {

					$id = Yii::app()->user->id;
					$name = Yii::app()->user->name;
					$ip = Yii::app()->request->getUserHostAddress();
					//$userid,$description,$activityid,$type,$point,$status
					Activities::model()->my($id, "Login from IP : " . $ip, 1, 1, 2, 1);

					if (YII::app()->user->record->level == 1) {
						$this->redirect(array('/integration/users/team'));
					} else if (YII::app()->user->record->level == 2) {
						$this->redirect(array('integration/users/verifiedteam'));
						// $this->actionCheck($id);
					} else if (YII::app()->user->record->level == 3) {
						$this->redirect(array('/integration/users/my'));
						// $this->actionCheck($id);
					} else {
						// $this->actionCheck($id);
					}
					// $this->redirect(array('main/paper/admin'));
				}
			}
			// display the login form
			$this->render('login', array('model' => $model));
		} else {
			$this->redirect(array('integration/users/team'));
		}
	}

	/**
	* Logs out the current user and redirect to homepage.
	*/
	public function actionLogout()
	{
		// $model=Users::model()->findByPk(YII::app()->user->id);
		// $model->setScenario('log');
		// $model->active = 0;
		// $ip = Yii::app()->request->getUserHostAddress();

		// //$userid,$description,$activityid,$type,$point,$status
		// Activities::model()->my(YII::app()->user->id,"Logout from IP : ".$ip,0,0,0,0);

		// if($model->save()){
		Yii::app()->user->logout();
		$this->redirect(array('site/login'));
			// }
	}

	public function actionCheck($id)
	{
		$user = $this->loadUsers($id);
		if ($user->email == NULL || $user->fullname == NULL || $user->birth == NULL || $user->gender == NULL || $user->email == NULL) {
			$this->redirect(array('/edit'));
		}
	}

	public function actionReport($type)
	{
		if (Yii::app()->user->isGuest) {
			$this->actionLogin();
		} else {
			$this->layout = "page_user";
			$this->render('report', array('type' => $type));
		}
	}


	public function actionReportChart()
	{
		if (Yii::app()->user->isGuest) {
			$this->actionLogin();
		} else {
			$this->layout = "page_user";
			$this->render('report_chart');
		}
	}


	public function actionExcel($type)
	{
		if (Yii::app()->user->isGuest) {
			$this->actionLogin();
		} else {
			$this->layout = "print";

			if ($type == 1) {
				$where = "Semua";
			} elseif ($type == 2) {
				$where = "Perseorangan";
			} elseif ($type == 3) {
				$where = "Kelompok";
			}

			$filename = "Nilai " . $where . ".xls";
			header("Content-Type: application/vnd.ms-excel");
			header("Content-Disposition: attachment; filename=\"$filename\"");
			$model = Review::model()->getReview($type);
			$this->render('excel', array('model' => $model));
		}
	}

	public function actionRegister($jenis = '')
	{
		$this->layout = "frontend";
		$model = new Users;
		$model->setScenario('create');
			// $model->setScenario('create');
			// $this->performAjaxValidation($model);
		if (isset($_POST['Users'])) {
			$model->attributes = $_POST['Users'];
			$model->create_time = date('Y-m-d h:i:s');
			$model->level = 3;
			$model->ipaddress = 3;
			$model->active = 0;
			$model->status = 0;
			$model->division = 0;

			if ($model->type == YII::app()->baseUrl . "/register-individu") {
				$model->type = 1;
			} else {
				$model->type = 2;
			}

			$tmp = null;
			if (strlen(trim(CUploadedFile::getInstance($model, 'image'))) > 0) {
				$tmp = CUploadedFile::getInstance($model, 'image');
				$model->image = uniqid() . "-" . time() . '.' . $tmp->extensionName;
			}

				// var_dump($model->save());
				// die();

			if ($model->save()) {

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

				if ($model->type == YII::app()->baseUrl . "/register-individu") {

					$member = new Member;
					$member->setScenario('create');
					$member->create_time = date('Y-m-d h:i:s');
					$member->code = $_POST["member_code"];
					$member->fullname = $_POST["member_name"];
					$member->phone = $_POST["member_phone"];
					$member->email = $_POST["member_email"];
					$member->team_id = $model->id_user;

					if ($model->type == 1) {
						$model->code = $member->code;
						$model->fullname = $member->fullname;
						$model->phone = $member->phone;
						$model->email = $member->email;
						$model->update();
					}


						// Upload KTP
					if (is_uploaded_file($_FILES['member_image_identity_1']['tmp_name'])) {
						sleep(1);
						$filename   = uniqid() . "-" . time();
						$extension  = pathinfo($_FILES["member_image_identity_1"]["name"], PATHINFO_EXTENSION);
						$basename   = $filename . "." . $extension;

						$source_path = $_FILES['member_image_identity_1']['tmp_name'];
						$target_path = 'image/files/identity/' . $basename;
						move_uploaded_file($source_path, $target_path);
						$member->image_identity = $basename;
					}


						// Upload Pas Foto
					if (is_uploaded_file($_FILES['member_image_foto_1']['tmp_name'])) {
						sleep(1);
						$filename   = uniqid() . "-" . time();
						$extension  = pathinfo($_FILES["member_image_foto_1"]["name"], PATHINFO_EXTENSION);
						$image_foto   = $filename . "." . $extension;

						$source_path = $_FILES['member_image_foto_1']['tmp_name'];
						$target_path = 'image/files/foto/' . $image_foto;
						move_uploaded_file($source_path, $target_path);
						$member->image_foto = $image_foto;
					}

						// Upload Sosmed
					if (is_uploaded_file($_FILES['member_image_sosmed_1']['tmp_name'])) {
						sleep(1);
						$filename   = uniqid() . "-" . time();
						$extension  = pathinfo($_FILES["member_image_sosmed_1"]["name"], PATHINFO_EXTENSION);
						$image_sosmed   = $filename . "." . $extension;

						$source_path = $_FILES['member_image_sosmed_1']['tmp_name'];
						$target_path = 'image/files/sosmed/' . $image_sosmed;
						move_uploaded_file($source_path, $target_path);
						$member->image_sosmed = $image_sosmed;
					}

					if ($member->save() && $member->validate());
					$errors = $member->getErrors();
				} else {

					$number = count($_POST["member_code"]);
					if ($number > 0) {
						for ($i = 0; $i < $number; $i++) {
							if (trim($_POST["member_code"][$i] != '')) {
								$member = new Member;
								$member->create_time = date('Y-m-d h:i:s');
								$member->code = $_POST["member_code"][$i];
								$member->fullname = $_POST["member_name"][$i];
								$member->phone = $_POST["member_phone"][$i];
								$member->email = $_POST["member_email"][$i];
								$member->team_id = $model->id_user;

								if ($model->type == 1) {
									$model->fullname = $member->fullname;
									$model->phone = $member->phone;
									$model->email = $member->email;
									$model->update();
								}

									// Upload KTP
								if (is_uploaded_file($_FILES['member_image_identity']['tmp_name'][$i])) {
									sleep(1);
									$filename   = uniqid() . "-" . time();
									$extension  = pathinfo($_FILES["member_image_identity"]["name"][$i], PATHINFO_EXTENSION);
									$basename   = $filename . "." . $extension;

									$source_path = $_FILES['member_image_identity']['tmp_name'][$i];
									$target_path = 'image/files/identity/' . $basename;
									move_uploaded_file($source_path, $target_path);
									$member->image_identity = $basename;
								}


									// Upload Pas Foto
								if (is_uploaded_file($_FILES['member_image_foto']['tmp_name'][$i])) {
									sleep(1);
									$filename   = uniqid() . "-" . time();
									$extension  = pathinfo($_FILES["member_image_foto"]["name"][$i], PATHINFO_EXTENSION);
									$image_foto   = $filename . "." . $extension;

									$source_path = $_FILES['member_image_foto']['tmp_name'][$i];
									$target_path = 'image/files/foto/' . $image_foto;
									move_uploaded_file($source_path, $target_path);
									$member->image_foto = $image_foto;
								}

									// Upload Sosmed
								if (is_uploaded_file($_FILES['member_image_sosmed']['tmp_name'][$i])) {
									sleep(1);
									$filename   = uniqid() . "-" . time();
									$extension  = pathinfo($_FILES["member_image_sosmed"]["name"][$i], PATHINFO_EXTENSION);
									$image_sosmed   = $filename . "." . $extension;

									$source_path = $_FILES['member_image_sosmed']['tmp_name'][$i];
									$target_path = 'image/files/sosmed/' . $image_sosmed;
									move_uploaded_file($source_path, $target_path);
									$member->image_sosmed = $image_sosmed;
								}

								$member->save();
							}
						}
					}
				}

				Yii::import('ext.yii-mail.YiiMailMessage');
				$email = new YiiMailMessage;
				$message_title = "Halo Panitia";
				$message_content = "
				Berikut informasi pendaftar baru:

				Nama Tim: " . $model->fullname . "
				Email: " . $model->email . "
				No WA: " . $model->phone . "

				Terimakasih.";
				$message_link = YII::app()->baseUrl . "/main/paper/view/id/" . $model->id_user;
				$message_button = "Aktivasi Akun";
				$email->subject = "Pendaftaran Baru Peserta ".Setting::model()->description()."  an. " . $model->fullname . " [ Belum di Aktivasi ]";
				$email->addTo(Setting::model()->email());
				// $email->addCC('abah.khansa@gmail.com');
				// $email->addCC('idinfografis@gmail.com');
				// $email->addCC('yossyostisa@yahoo.co.id');
				// $email->addCC('rhrhalim@gmail.com');
				// $email->addCC('ahmad.dci56@gmail.com');
				// $email->addCC('staygoodbebetter@gmail.com');
				$email->setFrom(array(Setting::model()->email() => Setting::model()->name()));
				$message_template = $this->renderPartial(
					'/email/default',
					array(
						'email' => $model->email,
						'title' => $message_title,
						'message' => $message_content,
						'link' => $message_link,
						'button' => $message_button
					),
					TRUE
				);
				$email->setBody($message_template, 'text/html');
				if (Yii::app()->mail->send($email)) {
					$this->redirect(array('site/success'));
				}
			}
		}

		if ($jenis == 1) {
			$this->render('register_individu', array(
				'model' => $model,
			));
		} elseif ($jenis == 2) {
			$this->render('register_team', array(
				'model' => $model,
			));
		} else {
			$this->render('frontend', array(
				'model' => $model,
			));
		}
	}

	public function actionSuccess()
	{
		$this->layout = "frontend";
		$this->render('success');
	}

	public function actioncheckAvailability($type)
	{
		if ($type == 1) {
			if (!empty($_POST["email"])) {
				$model = Users::model()->findByAttributes(array('email' => $_POST["email"]));
				if ($model === null) {
					echo 0;
							// echo "<span class='status-not-available'>Email Belum Terdaftar.</span>";
				} else {
					echo 1;
							// echo "<span class='status-available'>Email Sudah Terdaftar.</span>";
				}
			}
		} elseif ($type == 2) {
			if (!empty($_POST["code"])) {
				$model = Users::model()->findByAttributes(array('code' => $_POST["code"]));
				if ($model === null) {
					echo 0;
							// echo "<span class='status-not-available'>Email Belum Terdaftar.</span>";
				} else {
					echo 1;
							// echo "<span class='status-available'>Email Sudah Terdaftar.</span>";
				}
			}
		} elseif ($type == 3) {
			if (!empty($_POST["code"])) {
				$model = Member::model()->findByAttributes(array('code' => $_POST["code"]));
				if ($model === null) {
					echo 0;
							// echo "<span class='status-not-available'>Email Belum Terdaftar.</span>";
				} else {
					echo 1;
							// echo "<span class='status-available'>Email Sudah Terdaftar.</span>";
				}
			}
		}
	}

	public function actionNotification($id)
	{
				// $user = $this->loadUsers($id);
		$activity = $this->loadActivities($id);
		$activity->status = 1;
		$activity->update();
		$this->redirect(array('/main/paper/update', 'id' => $activity->user_id));
	}

	public function actionSeeNotification()
	{
		$dataProvider = new CActiveDataProvider('Activities');
		$this->render('notification', array('dataProvider' => $dataProvider));
	}

	public function actionExpiredNotification()
	{
		foreach (Users::getExpiredNotification() as $data) {
			$status = $data['expired_date'] <= date('Y-m-d h:i:s') ? 'Expired' : 'Waiting';
			echo $data['expired_date'] . " - " . $data['fullname'] . " - " . $status . "</br>";
			$user = $this->loadUsers($data['id_user']);
			$user->status = 3;
			$user->active = 3;
			$user->update();
			$paper = $this->loadPaper($data['id_user']);
			$paper->status = 3;
			$paper->update();

			Yii::import('ext.yii-mail.YiiMailMessage');
			$email = new YiiMailMessage;
			$message_title = "Pendaftaran Expired";
			$message_content =
			"Halo " . $user->fullname . ",

			Mohon Maaf, Akun Anda sudah expired karena tidak Melakukan Update Data pada Aplikasi Lomba Video Kreatif Transhub Community 2021 sesuai peraturan batas Maksimal Update data sampai dengan " . $data['expired_date'] . ".

			Terimakasih
			Panitia Lomba.
			";
			$message_link = "";
			$message_button = "Balitbanghub";
			$email->subject = "[ Expired ] Akun Lomba Video Transhub Community an. " . $user->fullname;
			$email->addTo($user->email);
			$email->setFrom(array(Setting::model()->email() => Setting::model()->name()));
			$message_template = $this->renderPartial(
				'/email/default',
				array(
					'email' => $user->email,
					'title' => $message_title,
					'message' => $message_content,
					'link' => $message_link,
					'button' => $message_button
				),
				TRUE
			);
			$email->setBody($message_template, 'text/html');
			if (Yii::app()->mail->send($email)) {
						// $description,$activityid,$type,$point,$part,$object
						// Activities::model()->my("Akun Peserta an. " . $user->fullname . " [ EXPIRED ] pada " . Paper::model()->getNotificationMy($user->id_user), 1, 7, 1, 1, $user->id_user);
			}
		}
	}
}
