<?php

class EventController 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 $dateEvent;
	public $coverThumb;
	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('create', 'update', 'view', 'delete', 'admin', 'index', 'image', 'result', 'enable', 'disable', 'clone', 'reschedule', 'scheduleevent', 'detailschedule','invite','inviteto','list','previewcertificate','certificate','sertifikat','invitation','certificate','sendreschedule'),
				'users' => array('@'),
				'expression' => 'Yii::app()->user->record->level!=4',
			),
			array(
				'allow',
				'actions' => array('my', 'invitation'),
				'users' => array('@'),
				'expression' => 'Yii::app()->user->record->level==4',
			),
			array(
				'allow',
				'actions' => array('attend','watch','certificate'),
				'users' => array('@'),
			),
			array(
				'allow',
				'actions' => array('detail','search','certificate','invitation','sinkronisasi'),
				'users' => array('*'),
			),
			array(
				'deny',
				'users' => array('*'),
			),
		);
	}

	/**
	* Displays a particular model.
	* @param integer $id the ID of the model to be displayed
	*/
	public function actionView($id)
	{
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('view', array(
				'model' => $this->loadModel($id),
			), false, true);
		} else {
			$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()
	{
		// $this->layout = "back_page";
		$model = new Event;
		$model->setScenario('add');

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

		if (isset($_POST['Event'])) {
			$model->attributes = $_POST['Event'];
			$model->created_id = YII::app()->user->id;
			$model->created_date = date('Y-m-d');
			$model->status = 1;
			$model->status_album = 1;
			$model->status_certificate = 0;
			$model->quota = 0;


			if ($model->save()) {
				$model->token = md5($model->id_event);
				$model->update();

				Activities::model()->my($model->created_id, $model->title, $model->id_event, 2, 3, 2);
				Yii::app()->user->setFlash('success', '<b>Successfully!</b> <i>' . $model->title . '</i> has been created.');
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}
		}

		$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)
	{
		// $this->layout = "back_page";
		$model = $this->loadModel($id);
		$model->setScenario('update');

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

		if (isset($_POST['Event'])) {
			$model->attributes = $_POST['Event'];
			$model->update_id = YII::app()->user->id;
			$model->update_date = date('Y-m-d h:i:s');
			$model->token = md5($id);

			if ($model->save()) {
				//$userid,$description,$activityid,$type,$point,$status
				Activities::model()->my($model->created_id, $model->title, $model->id_event, 6, 1, 10);

				Yii::app()->user->setFlash('success', '<b>Successfully!</b> <i>' . $model->title . '</i> has update.');
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}
		}

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

	public function actionDelete($id)
	{
		$model = $this->loadModel($id);
		$imageLocationOrginal = Yii::getPathOfAlias('webroot') . "/image/event/big/";
		$imageLocationSmall = Yii::getPathOfAlias('webroot') . "/image/event/small/";
		$imageLocationMiddle = Yii::getPathOfAlias('webroot') . "/image/event/middle/";
		if (!empty($model->image)) {
			unlink($imageLocationOrginal . $model->image);
			unlink($imageLocationSmall . $model->image);
			unlink($imageLocationMiddle . $model->image);
		}
		$model->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if (!isset($_GET['ajax']))
			Yii::app()->user->setFlash('danger', '<b>Successfully!</b> Your post has remove.');
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	* Lists all models.
	*/
	public function actionResult($find = '')
	{
		$criteria = new CDbCriteria();
		if (strlen($find) > 0)
			$criteria->addSearchCondition('title', $find, true, 'OR');
		$criteria->addSearchCondition('description', $find, true, 'OR');
		$criteria->order = "created_date DESC";

		$dataProvider = new CActiveDataProvider('Event', array('criteria' => $criteria));
		$this->render('result', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionList($find = '')
	{
		$criteria = new CDbCriteria();
		if (strlen($find) > 0)
			$criteria->addSearchCondition('title', $find, true, 'OR');
		$criteria->addSearchCondition('description', $find, true, 'OR');
		$criteria->order = "created_date DESC";
		$criteria->condition = "created_id=".YII::app()->user->id;

		$dataProvider = new CActiveDataProvider('Event', array('criteria' => $criteria));
		$this->render('list', array(
			'dataProvider' => $dataProvider,
		));
	}


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

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

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

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


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

	public function actionImage($id)
	{
		$this->layout = "back_page";
		$model = $this->loadModel($id);
		$model->setScenario('changeImage');
		if (isset($_POST['Event'])) {
			$model->attributes = $_POST['Event'];
			$tmp;
			if (strlen(trim(CUploadedFile::getInstance($model, 'image'))) > 0) {
				$tmp = CUploadedFile::getInstance($model, 'image');
				$model->image = $model->url . '.' . $tmp->extensionName;
			}

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

				$thumbSmall = Yii::app()->phpThumb->create(Yii::getPathOfAlias('webroot') . "/image/event/big/" . $model->image);
				$thumbSmall->adaptiveResize(125, 125);
				$thumbSmall->save(Yii::getPathOfAlias('webroot') . "/image/event/small/" . $model->image);

				$thumbMiddle = Yii::app()->phpThumb->create(Yii::getPathOfAlias('webroot') . "/image/event/big/" . $model->image);
				$thumbMiddle->adaptiveResize(555, 332);
				$thumbMiddle->save(Yii::getPathOfAlias('webroot') . "/image/event/middle/" . $model->image);

				$this->redirect(array('view', 'id' => $model->id_event));
			}
		}

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

	public function actionSearch($find = '')
	{
		$this->layout = "frontend_page";
		$criteria = new CDbCriteria();
		if (strlen($find) > 0)
			$criteria->addSearchCondition('title', $find, true, 'OR');
		$criteria->addSearchCondition('description', $find, true, 'OR');
		$criteria->condition = "status=1 AND status_private=0";
		$criteria->order = "start_date DESC";

		$dataProvider = new CActiveDataProvider('Event', array('criteria' => $criteria));
		$this->render('search', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionDetail($url)
	{
		$this->layout = "frontend_page";
		$model = $this->loadUrl($url);
		$model->setScenario('views');
		$model->views += 1;
		$model->save();
		$this->render('detail', array(
			'model' => $model,
		));
	}

	public function actionWatch($url)
	{
		$this->layout = "frontend_page";
		$model = $this->loadUrl($url);
		$model->setScenario('views');
		$model->views += 1;
		$model->save();
		$this->render('detail_watch', array(
			'model' => $model,
		));
	}

	public function actionEnable($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('status');
		$model->status = 1;
		$model->save();
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		// $this->redirect(array('view','id'=>$model->id_event));
	}

	public function actionDisable($id)
	{
		$model = $this->loadModel($id);
		$model->setScenario('status');
		$model->status = 0;
		$model->save();
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		// $this->redirect(array('view','id'=>$model->id_event));
	}

	public function actionClone($id)
	{
		$clone = $this->loadModel($id);
		$model = new Event;
		$model->attributes = $clone->attributes;
		$model->save();
		$this->redirect(array('update', 'id' => $model->id_event));
	}

	public function actionReschedule($id)
	{
		// $this->layout = "back_page";
		$model = $this->loadModel($id);
		$model->setScenario('update');

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

		if (isset($_POST['Event'])) {
			$model->attributes = $_POST['Event'];
			$model->reschedule_id = YII::app()->user->id;
			$model->reschedule_date = date('Y-m-d h:i:s');

			if ($model->save()) {
				//$userid,$description,$activityid,$type,$point,$status
				Activities::model()->my($model->created_id, $model->title, $model->id_event, 6, 1, 10);

				Yii::app()->user->setFlash('success', '<b>Successfully!</b> <i>' . $model->title . '</i> has update.');
				$this->redirect(array('view', 'id' => $model->id_event));
			}
		}

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

	public function actionSendReschedule($id)
	{
		$this->layout = "signin";
		Yii::import('ext.yii-mail.YiiMailMessage');
		$model = $this->loadModel($id);
		$email = new YiiMailMessage;
		$message_title = "Notification";
		$message_content = $model->reschedule_description;
		$message_link = YII::app()->getBaseUrl(true) . "/event/" . $model->url;
		$message_button = "Detail";
		$email->subject = "[ Reschedule Event ] - " . $model->title . " - West Java Investment Hub";
		foreach (Registration::getRegister($model->id_event) as $data) {
			$email->addTo($data['email']);
		}
		$email->setFrom(array(Setting::model()->email() => Setting::model()->name()));
		$message_template = $this->renderPartial(
			'/email/informasi',
			array(
				'email' => "infomugi@gmail.com",
				'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)) {
			Yii::app()->user->setFlash('success', 'Email Notifikasi Reschedule Terkirim');
			$model->reschedule_notification = 1;
			$model->save();
			$this->redirect(array('view', 'id' => $model->id_event));
		}
	}

	public function actionMy()
	{
		// Yii::app()->user->setFlash('Warning', 'Peserta sudah Absen.');
		$this->layout = "frontend_dashboard";
		$criteria = new CDbCriteria();
		$criteria->condition = "created_id=" . YII::app()->user->id;
		$criteria->order = "created_date DESC";
		$dataProvider = new CActiveDataProvider('Registration', array('criteria' => $criteria));
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function loadOnlineToken($eventID)
	{
		$model=Registration::model()->findByAttributes(array('created_id'=>YII::app()->user->id,'event_id'=>$eventID));
		$event = Event::model()->findByPk($eventID);
		if($model===null)
			if(YII::app()->user->record->level==4){
				$this->redirect(array('main/event/detail', 'url' => $event->url));
			}
			return $model;
		}

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

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

		public function actionInvitation($token)
		{
			$this->layout = "eticket";
			$model = $this->loadToken($token);
			$this->render('print_eticket', array(
				'model' => $model,
			));
		}

		public function actionScheduleEvent()
		{
			$items = array();
			$criteria = new CDbCriteria();
			$criteria->condition = 'status=:status';
			$criteria->params = array(':status' => 1);
			$model = Event::model()->findAll($criteria);

			foreach ($model as $value) {
				$items[] = array(
					'id' => $value->id_event,
					'title' => 'Event: ' . $value->title . ' - ' . $value->location,
					'start' => $value->start_date . ' ' . $value->start_time,
					'end' => date('Y-m-d', strtotime('+1 day', strtotime($value->end_date . ' ' . $value->end_time))),
					'color' => Event::generateColor(),
				);
			}

			echo CJSON::encode($items);
			Yii::app()->end();
		}

		public function actionDetailSchedule($id)
		{
			if (Yii::app()->request->isAjaxRequest) {
				$this->renderPartial('view', array(
					'model' => $this->loadModel($id),
				), false, true);
			} else {
				$this->render('view', array(
					'model' => $this->loadModel($id),
				));
			}
		}

		public function actionAttend($token)
		{
			$this->layout = "landing";
			$model = $this->loadEventToken($token);
			$this->loadOnlineToken($model->id_event);
			$this->render('detail_attend', array(
				'model' => $model,
			));
		}

		public function actionInvite($id)
		{
			$model = new Users('search');
			$model->unsetAttributes();
			if (isset($_GET['Users']))
				$model->attributes = $_GET['Users'];

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

		public function actionInviteto()
		{
			if(Yii::app()->request->getIsAjaxRequest()){
				$checkedIDs=$_POST['checked'];
				$success = 0;
				$error = 0;
				foreach($checkedIDs as $id){
					$users = $this->loadUsers($id);
					$model=new Registration;
					$model->created_date = date('Y-m-d h:i:s');
					$model->update_date = NULL;
					$model->verified_date = NULL;
					$model->verified_id = 0;
					$model->enter_status = 0;
					$model->status_invite = 1;
					$model->event_id = $_POST['event_id'];
					$model->created_id = $users->id_user;
					$model->name = $users->fullname;
					$model->email = $users->email;
					$model->phone = $users->phone;
					$model->event_log = "Undangan untuk Event ke ".$model->email." telah dikirim oleh ".YII::app()->user->record->username;
					$model->token = md5($model->created_date.$model->name);
				// $model->save();
					if($model->save()){

						if($model->Event->zoom_link!="-" || $model->Event->zoom_link!=NULL){
							$online = "<BR><BR>Event ini juga tersedia secara virtual pada tanggal dan jam yang sama untuk akses ke <b>Zoom Meeting</b> dapat klik tautan berikut ini <a href='".$model->Event->zoom_link."'>".$model->Event->zoom_link."</a>";
						}else{
							$online = "";
						}

						$success ++ ;
					// START: Email Notification
						Yii::import('ext.yii-mail.YiiMailMessage');
						$email = new YiiMailMessage;
						$message_title = $model->Event->title;
						$message_content =
						"Hallo <b>".$model->name."</b>, </br></br> Selamat Anda sudah berhasil Registrasi untuk Event ".$model->Event->title." yang akan berlangsung Pada ".$model->Event->start_date." Pukul ".$model->Event->start_time." berlokasi di ".$model->Event->location.".</br>".$online;
						$message_link = YII::app()->getBaseUrl(true) ."/main/event/invitation/token/".$model->token;
						$message_button = "Lihat E-Tiket Event";
						$email->subject = "E-Ticket Event [ ".$model->Event->title." ] - ".$model->name;
						$email->addTo($model->email);
						$email->setFrom(array(Setting::model()->email() => Setting::model()->name()));
						$message_template = $this->renderPartial('/email/informasi',
							array(
								'email'=>$model->email,
								'title'=>$message_title,
								'message'=>$message_content,
								'link'=>$message_link,
								'button'=>$message_button
							),TRUE);
						$email->setBody($message_template, 'text/html');
						Yii::app()->mail->send($email);
					// END: Email Notification

					}else{
						$error ++;
					}
				}
				echo "Berhasil: ".$success. " - Gagal: ".$error;
			}
		}

		public function actionSertifikat($id)
		{
			$this->layout = "back_page";
			$model = $this->loadModel($id);
		// $model->setScenario('changeImage');
			if (isset($_POST['Event'])) {
				$model->attributes = $_POST['Event'];
				$tmp;
				if (strlen(trim(CUploadedFile::getInstance($model, 'image_sertifikat'))) > 0) {
					$tmp = CUploadedFile::getInstance($model, 'image_sertifikat');
					$model->image_sertifikat = $model->url . '.' . $tmp->extensionName;
				}

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

					$this->redirect(array('view', 'id' => $model->id_event));
				}
			}

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

		public function actionPreviewCertificate($token)
		{
			$this->layout = "eticket";
			$model = $this->loadEventToken($token);
			$this->render('print_esertifikat_preview', array(
				'model' => $model,
			));
		}

		public function actionCertificate($token)
		{
			$this->layout = "eticket";
			$model = $this->loadToken($token);
			$this->render('print_esertifikat', array(
				'model' => $model,
			));
		}

		public function actionSinkronisasi()
		{
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://dashboardbedas.bandungkab.go.id/api/agenda-bupati-bandung',
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => '',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 0,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => 'GET',
				CURLOPT_HTTPHEADER => array(
					'Cookie: XSRF-TOKEN=eyJpdiI6IjJJNXZUWmtYMm1RQXFOK1NuNmNMU3c9PSIsInZhbHVlIjoiNDRMazFQNmhiN3luSmtQMkhsd25vR3Z5MC9yeWFlZUh2WDUvaGg4MjRKcm4xOVVYWEsxWTJZT1k5SEc4WFNYcW9ndGV6TFBrZ0xoMHlHd1gyNEgrUTBOU3Y1OTdtZjBjemJCQWtlbzZRbWFoWjBuTTZaR1pNYktRM1cyRFZMcTMiLCJtYWMiOiIxZjU4ZmJmNzQ2ODZmYTA5OTQ2NzNkZmVhNzg1ZDFlZDQ5ZmM5NWU0YWQ4NmU0NzQ4NDUyNGY5M2MwYWI5MDQ0In0%3D; laravel_session=eyJpdiI6Imgyd3JXeHVCYjA3YXorTEN6bmxuTEE9PSIsInZhbHVlIjoiZTRlQ1RGY2J4UDlPQVNmVHo4OTQ0Q3JXbnNjV2hXYmw1dHQ2RzRrTm1yeHNGY0NRN3phb0tlZ29zNTd0aDVoeWJLZWNuNnkxYWtUVFRuU1V3NVVuZmVEOVAwSmQ3T0tGNnhQNm1ZbXhhd3k2ZWxDQW9UUW85K1Bxcm5YbzFERkwiLCJtYWMiOiI5NjQ3OWYyZDA4NTlmMDQ5OTlmYmZiMDE1Njk5ZjljZTliZWJiMWM1ZjQ4MzE0NmM1N2VlZjM4OGZiOGQ0OTE0In0%3D'
				),
			));

			$response = curl_exec($curl);
			curl_close($curl);
			$json = json_decode($response,true);
			foreach ($json['data']['info'] as $value) {
				$model = Event::model()->findByAttributes(array('title' => $value['nama']));

				if ($model === null) {
					$model = new Event;
					$model->created_id = 1;
					$model->created_date = date('Y-m-d H:i:s');
					$model->status = 1;
					$model->status_album = 1;
					$model->status_certificate = 0;
					$model->quota = 0;
					$model->status_private = 0;
					$model->status_event = 0;
					$model->status_streaming = 0;
					$model->id_category = 3;
					$model->id_tag = 8;
				}

				$model->update_date = date('Y-m-d H:i:s');
				$model->title = $value['nama'];
				$model->description = $value['keterangan'];
				$model->start_date = date("Y-m-d", strtotime($value['tanggal']));
				$model->end_date = date("Y-m-d", strtotime($value['tanggal']));
				$model->start_time = $value['jam_mulai'];
				$model->end_time = $value['jam_akhir'];
				$model->location = $value['lokasi_kegiatan'];

				if ($model->save()) {
					// if ($model->isNewRecord) {
					$album = new Album;
					$album->created_date = date('Y-m-d H:i:s');
					$album->user_id = 1;
					$album->title = $model->title;
					$album->description = $model->keyword;
					$album->location = $model->location;
					$album->status = 1;
					$album->save();
					$model->id_album = $album->id_album;
					$model->save();
					// }
				}
			}
			Yii::app()->user->setFlash('success', 'Data Agenda Kegiatan Bupati Bandung Berhasil di Sinkronisasi');
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}

	}
