<?php

namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\models\FeedbackForm;

use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\db\Connection;
use app\models\SearchForm;
use app\controllers\SearchController;
use DOMDocument;

/**
 * Site controller
 */
class SiteController extends Controller {
	
	/**
	 * @inheritdoc
	 */
	public function behaviors() {
		return [ 
				'access' => [ 
						'class' => AccessControl::className (),
						'only' => [ 
								'logout',
								'signup' 
						],
						'rules' => [ 
								[ 
										'actions' => [ 
												'signup' 
										],
										'allow' => true,
										'roles' => [ 
												'?' 
										] 
								],
								[ 
										'actions' => [ 
												'logout' 
										],
										'allow' => true,
										'roles' => [ 
												'@' 
										] 
								] 
						] 
				],
				'verbs' => [ 
						'class' => VerbFilter::className (),
						'actions' => [ 
								'logout' => [ 
										'post' 
								] 
						] 
				] 
		];
	}
	
	/**
	 * @inheritdoc
	 */
	public function actions() {
		return [ 
				'error' => [ 
						'class' => 'yii\web\ErrorAction' 
				],
				'captcha' => [ 
						'class' => 'yii\captcha\CaptchaAction',
						'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null 
				] 
		];
	}
	
	
	public function actionIndex() {
		$totalRecords = $this->getTotal ();
		$counts = $this->getCounts ( $totalRecords );
		try {
			$news = $this->getNews ();
		} catch ( Exception $e ) {
			$news = [ ];
		}
		
		return $this->render ( 'index', [ 
				'counts' => $counts,
				'contentleft' => "",
				'contentright' => $counts,
				'news' => $news,
				'totalRecords' => $totalRecords 
		] );
	}
	public function actionCookies() {
		return $this->render ( 'cookies' );
	}
	
	// public function actionLogin() {
	// if (! \Yii::$app->user->isGuest) {
	// return $this->goHome ();
	// }
	
	// $model = new LoginForm ();
	// if ($model->load ( Yii::$app->request->post () ) && $model->login ()) {
	// return $this->goBack ();
	// } else {
	// return $this->render ( 'login', [
	// 'model' => $model
	// ] );
	// }
	// }
	// public function actionLogout() {
	// Yii::$app->user->logout ();
	// return $this->goHome ();
	// }
	public function actionContact() {
		$model = new ContactForm ();
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			if ($model->sendEmail ( Yii::$app->params ['adminEmail'] )) {
				Yii::$app->session->setFlash ( 'success', 'Thank you for contacting us. We will respond to you as soon as possible.' );
			} else {
				Yii::$app->session->setFlash ( 'error', 'There was an error sending email.' );
			}
			
			return $this->refresh ();
		} else {
			return $this->render ( 'contact', [ 
					'model' => $model 
			] );
		}
	}
	public function actionAbout() {
		return $this->render ( 'about' );
	}
	// public function actionSignup() {
	// $model = new SignupForm ();
	// if ($model->load ( Yii::$app->request->post () )) {
	// if ($user = $model->signup ()) {
	// if (Yii::$app->getUser ()->login ( $user )) {
	// return $this->goHome ();
	// }
	// }
	// }
	
	// return $this->render ( 'signup', [
	// 'model' => $model
	// ] );
	// }
	// public function actionRequestPasswordReset() {
	// $model = new PasswordResetRequestForm ();
	// if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
	// if ($model->sendEmail ()) {
	// Yii::$app->getSession ()->setFlash ( 'success', 'Check your email for further instructions.' );
	
	// return $this->goHome ();
	// } else {
	// Yii::$app->getSession ()->setFlash ( 'error', 'Sorry, we are unable to reset password for email provided.' );
	// }
	// }
	
	// return $this->render ( 'requestPasswordResetToken', [
	// 'model' => $model
	// ] );
	// }
	// public function actionResetPassword($token) {
	// try {
	// $model = new ResetPasswordForm ( $token );
	// } catch ( InvalidParamException $e ) {
	// throw new BadRequestHttpException ( $e->getMessage () );
	// }
	
	// if ($model->load ( Yii::$app->request->post () ) && $model->validate () && $model->resetPassword ()) {
	// Yii::$app->getSession ()->setFlash ( 'success', 'New password was saved.' );
	
	// return $this->goHome ();
	// }
	
	// return $this->render ( 'resetPassword', [
	// 'model' => $model
	// ] );
	// }
	public function actionSearch() {
		return $this->redirect ( Yii::$app->getUrlManager ()->createUrl ( [ 
				'search/query' 
		] ) );
	}
	public function getCounts($total) {
		$connection = new \yii\db\Connection ( Yii::$app->db );
		$connection->open ();
		
<?php

namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\db\Connection;
use app\models\SearchForm;
use frontend\controllers\PermissionController;
use frontend\models\ValidationForm;
use Solarium\Exception\InvalidArgumentException;
use app\controllers\SearchController;
use DOMDocument;
use frontend\models\frontend\models;
use common\models\User;
use frontend\controllers\ValidationController;
use frontend\controllers\AccountControler;
use yii\widgets\Pjax;
use yii\base\Security;
use yii\base\yii\base;


/**
 * Site controller
 */
class SiteController extends Controller {
	/**
	 * @inheritdoc
	 */
	public function behaviors() {
		return [ 
				'access' => [ 
						'class' => AccessControl::className (),
						'only' => [ 
								'logout',
								'signup' 
						],
						'rules' => [ 
								[ 
										'actions' => [ 
												'signup' 
										],
										'allow' => true,
										'roles' => [ 
												'?' 
										] 
								],
								[ 
										'actions' => [ 
												'logout' 
										],
										'allow' => true,
										'roles' => [ 
												'@' 
										] 
								] 
						] 
				],
				'verbs' => [ 
						'class' => VerbFilter::className (),
						'actions' => [ 
								'logout' => [ 
										'post' 
								] 
						] 
				] 
		];
	}
	
	/**
	 * @inheritdoc
	 */
	public function actions() {
		return [ 
				'error' => [ 
						'class' => 'yii\web\ErrorAction' 
				],
				'captcha' => [ 
						'class' => 'yii\captcha\CaptchaAction',
						'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null 
				] 
		];
	}
	public function actionIndex() {
		// Redirect admin to validation page, if the admin accessed the site following
		// an activation link
		if (isset ( \Yii::$app->session ['activationKey'] )) {
			$token = \Yii::$app->session ['activationKey'];
			\Yii::$app->session->remove ( 'activationKey' );
			return $this->redirect ( Yii::$app->getUrlManager ()->createAbsoluteUrl ( [ 
					'validation/validation',
					'token' => $token 
			] ) );
		}
		$totalRecords = $this->getTotal ();
		$counts = $this->getCounts ( $totalRecords );
		try {
			$news = $this->getNews ();
		} catch ( Exception $e ) {
			$news = [ ];
		}
		
		return $this->render ( 'index', [ 
				'counts' => $counts,
				'contentleft' => "",
				'contentright' => $counts,
				'news' => $news,
				'totalRecords' => $totalRecords 
		] );
	}
	public function actionCookies() {
		return $this->render ( 'cookies' );
	}
	
	/**
	 * renders the login site and resets the session timeout
	 * 
	 * @return \yii\web\Response|Ambigous <string, string>
	 */
	public function actionLogin() {
		Yii::$app->session->set ( 'userSessionTimeout', time () + Yii::$app->params ['sessionTimeoutSeconds'] );
		if (! \Yii::$app->user->isGuest) {
			return $this->goHome ();
		}
		
		$model = new LoginForm ();
		if ($model->load ( Yii::$app->request->post () ) && $model->login ()) {
			return $this->goBack ();
		} else {
			return $this->render ( 'login', [ 
					'model' => $model 
			] );
		}
	}
	
	/**
	 * Overrides the parent function, in order to check before each action whether
	 * the user is still logged-in or whether he was logged out due to long inactivity.
	 * (non-PHPdoc)
	 * 
	 * @see \yii\web\Controller::beforeAction()
	 */
	public function beforeAction($action) {
		if (! parent::beforeAction ( $action )) {
			return false;
		}
		// Check only when the user is logged in
		if (! Yii::$app->user->isGuest) {
			if (Yii::$app->session ['userSessionTimeout'] < time ()) {
				Yii::$app->user->logout ();
				$this->goHome ();
				Yii::$app->session->setFlash ( 'success', 'You have been logged out!' );
			} else {
				Yii::$app->session->set ( 'userSessionTimeout', time () + Yii::$app->params ['sessionTimeoutSeconds'] );
				return true;
			}
		} else {
			return true;
		}
	}
	
	/**
	 * logs the user out and redirects to main page.
	 * 
	 * @return \yii\web\Response
	 */
	public function actionLogout() {
		Yii::$app->user->logout ();
		return $this->goHome ();
	}
	public function actionContact() {
		$model = new ContactForm ();
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			if ($model->sendEmail ( Yii::$app->params ['adminEmail'] )) {
				Yii::$app->session->setFlash ( 'success', 'Thank you for contacting us. We will respond to you as soon as possible.' );
			} else {
				Yii::$app->session->setFlash ( 'error', 'There was an error sending email.' );
			}
			
			return $this->refresh ();
		} else {
			return $this->render ( 'contact', [ 
					'model' => $model 
			] );
		}
	}
	public function actionAbout() {
		{
			if (Yii::$app->request->isPjax) {
				throw new \ErrorException ();
				return $this->renderPartial ( 'about' );
			} else {
				return $this->render ( 'about' );
			}
		}
	}
	
	/**
	 * renders the signup page and is responsible for form validation.
	 * redirects the user to "home" after signup. Due to manual user validation
	 * the user is not automatically logged-in after signup.
	 * 
	 * @return \yii\web\Response|Ambigous <string, string>
	 */
	public function actionSignup() {
		$model = new SignupForm ();
		if ($model->load ( Yii::$app->request->post () )) {
			if ($user = $model->signup ()) {
				Yii::$app->getSession ()->setFlash ( 'success', 'Your registration will be validated manually' );
				return $this->goHome ();
			}
		}
		return $this->render ( 'signup', [ 
				'model' => $model 
		] );
	}
	public function actionRequestPasswordReset() {
		$model = new PasswordResetRequestForm ();
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			if ($model->sendEmail ()) {
				Yii::$app->getSession ()->setFlash ( 'success', 'Check your email for further instructions.' );
				
				return $this->goHome ();
			} else {
				Yii::$app->getSession ()->setFlash ( 'error', 'Sorry, we are unable to reset password for email provided.' );
			}
		}
		return $this->render ( 'requestPasswordResetToken', [ 
				'model' => $model 
		] );
	}
	
	public function actionResetPassword($token) {
		try {
			$model = new ResetPasswordForm ( $token );
		} catch ( InvalidParamException $e ) {
			throw new BadRequestHttpException ( $e->getMessage () );
		}
		
		if ($model->load ( Yii::$app->request->post () ) && $model->validate () && $model->resetPassword ()) {
			Yii::$app->getSession ()->setFlash ( 'success', 'New password was saved.' );
			
			return $this->goHome ();
		}
		
		return $this->render ( 'resetPassword', [ 
				'model' => $model 
		] );
	}
	public function actionSearch() {
		return $this->redirect ( Yii::$app->getUrlManager ()->createUrl ( [ 
				'search/query' 
		] ) );
	}

	public function actionValidation() {
		return $this->redirect ( Yii::$app->getUrlManager ()->createUrl ( [ 
				'validation/validation' 
		] ) );
	}
	public function actionAccount() {
		return $this->redirect ( Yii::$app->getUrlManager ()->createUrl ( [ 
				'account/profile' 
		] ) );
	}
	public function getCounts($total) {
		$connection = new \yii\db\Connection ( Yii::$app->db );
		$connection->open ();
		
		$command = $connection->createCommand ( "SELECT   count(distinct concat(IFNULL(institution,'institutionName'),', ',IFNULL(city,'CityName'))) as cnt  FROM occurrence 
join unitkind on unitkindid=fk_kindofunitid
				join bio_datasource on id=fk_datasourceid
where kindofunit_clean in ('culture','specimen','unknown','eVoucher')
" );
		$dataReader = $command->queryAll ();
		$nbColVouchers = 0;
		foreach ( $dataReader as $row ) {
			$nbColVouchers = $row ["cnt"];
		}
		
		$command = $connection->createCommand ( "SELECT count(distinct concat(IFNULL(institution,'institutionName'),', ',IFNULL(city,'CityName'))) as cnt  FROM occurrence 
join unitkind on unitkindid=fk_kindofunitid
				join bio_datasource on id=fk_datasourceid
where kindofunit_clean not in ('culture','specimen','unknown')
" );
		$dataReader = $command->queryAll ();
		$nbColSamples = 0;
		foreach ( $dataReader as $row ) {
			$nbColSamples = $row ["cnt"];
		}
		
		$command = $connection->createCommand ( 'SELECT * FROM counts' );
		$dataReader = $command->queryAll ();
		$counts = "<span class='big'>Samples</span>";
		$taxa1 = [ ];
		$taxa2 = [ ];
		$col1 = [ ];
		$col2 = [ ];
		$col1b = [ ];
		$col2b = [ ];
		foreach ( $dataReader as $row ) {
			if ($row ['kind'] != "Genera" && $row ['kind'] != "Taxa" && $row ['kind'] != "Families"   && $row ['kind'] != "Species"  
					&& $row ['kind'] != "Cultures" && $row ['kind'] != "Specimens" 
					&& $row ['kind'] != "Unknown" && $row ['kind'] != "eVouchers") {
				array_push ( $col1, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $col2, $row ['counts'] );
			}
			if ($row ['kind'] == "Cultures" || $row ['kind'] == "Specimens" || $row ['kind'] == "Unknown" ||  $row ['kind'] == "eVouchers") {
				array_push ( $col1b, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $col2b, $row ['counts'] );
			}
			if ($row ['kind'] == "Genera" || $row ['kind'] == "Families" || $row['kind'] == "Species" ) {
				array_push ( $taxa1, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $taxa2, $row ['counts'] );
			}
		}
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $col1 ) . "<br/>Repositories</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $col2 ) . "<br/>" . $nbColSamples . "</div></div>";
		
		$counts .= "<span class='big'>Vouchers</span>";
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $col1b ) . "<br/>Collections</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $col2b ) . "<br/>" . $nbColVouchers . "</div></div>";
		
		$counts = $counts . "<span class='big'>Taxa</span>";
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $taxa1 ) . "</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $taxa2 ) . "</div></div>";
		
		$counts = $counts . "<br/><span class='big'>Total </span>";
		$counts .= "<div class='row'><div class='col-lg-6'></div>";
		$counts .= "<div class='col-lg-6'>" . $total . "</div></div>";
		
		Yii::$app->db->close ();
		// Yii::info("getCounts: ".$counts);
		
		return $counts;
	}
	public function getTotal() {
		$connection = new \yii\db\Connection ( Yii::$app->db );
		$connection->open ();
		
		$command = $connection->createCommand ( 'SELECT count(occurrenceid) as cnt FROM occurrence' );
		$dataReader = $command->queryAll ();
		$total = 0;
		foreach ( $dataReader as $row ) {
			$total = $row ['cnt'];
		}
		
		Yii::$app->db->close ();
		// Yii::info("getCounts: ".$counts);
		
		return $total;
	}
	function getNews() {
		ini_set ( 'default_socket_timeout', 3 );
		$news = @file_get_contents ( "http://wiki.bgbm.org/dnabankwiki/api.php?action=parse&prop=sections&page=News&format=json" );
		if (! $news)
			$news = [ ];
		else {
			if(strpos($news, "internal_api_error")>0)
				return [];
			else
			try {
				$jsonnews = json_decode ( $news );
				$newsitems = $jsonnews->parse->sections;
				$news = [ ];
				$year = date ( "Y" );
				foreach ( $newsitems as $newsitem ) {
					if (strpos ( $newsitem->line, strval ( $year ) ))
						array_push ( $news, [
								$newsitem->line,
								"http://wiki.bgbm.org/dnabankwiki/index.php/News#" . $newsitem->anchor
						] );
				}
				if (sizeof ( $news ) === 0) {
					// get last year
					$year --;
					foreach ( $newsitems as $newsitem ) {
						$tmp = $newsitem->line;
						if (stripos ( $newsitem->line, strval ( $year ) ))
							array_push ( $news, [
									$newsitem->line,
									"http://wiki.bgbm.org/dnabankwiki/index.php/News#" . $newsitem->anchor
							] );
					}
				}
			} catch ( Exception $e ) {
				$news=[];
			}
			
		}
		return $news;
	}
" );
		$dataReader = $command->queryAll ();
		$nbColSamples = 0;
		foreach ( $dataReader as $row ) {
			$nbColSamples = $row ["cnt"];
		}
		
		$command = $connection->createCommand ( 'SELECT * FROM counts' );
		$dataReader = $command->queryAll ();
		$counts = "<span class='big'>Samples</span>";
		$taxa1 = [ ];
		$taxa2 = [ ];
		$col1 = [ ];
		$col2 = [ ];
		$col1b = [ ];
		$col2b = [ ];
		foreach ( $dataReader as $row ) {
			// echo $row["kind"]." ==== ".$row["counts"]."<br/>";
			if ($row ['kind'] != "Genera" && $row ['kind'] != "Taxa" && $row ['kind'] != "Families" && $row ['kind'] != "Cultures" && $row ['kind'] != "Specimens" && $row ['kind'] != "Unknown") {
				array_push ( $col1, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $col2, $row ['counts'] );
				// $counts=$counts."<li>" . explode(" samples", $row ['kind'])[0] . " " . $row ['counts'].'</li>';
			}
			if ($row ['kind'] == "Cultures" || $row ['kind'] == "Specimens" || $row ['kind'] == "Unknown") {
				array_push ( $col1b, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $col2b, $row ['counts'] );
				// $counts=$counts."<li>" . explode(" samples", $row ['kind'])[0] . " " . $row ['counts'].'</li>';
			}
			if ($row ['kind'] == "Genera" || $row ['kind'] == "Families") {
				array_push ( $taxa1, explode ( " samples", $row ['kind'] )[0] );
				array_push ( $taxa2, $row ['counts'] );
			}
		}
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $col1 ) . "<br/>Repositories</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $col2 ) . "<br/>" . $nbColSamples . "</div></div>";
		
		$counts .= "<span class='big'>Vouchers</span>";
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $col1b ) . "<br/>Collections</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $col2b ) . "<br/>" . $nbColVouchers . "</div></div>";
		
		$counts = $counts . "<span class='big'>Taxa</span>";
		$counts .= "<div class='row'><div class='col-lg-6'>" . implode ( "<br/>", $taxa1 ) . "</div>";
		$counts .= "<div class='col-lg-6'>" . implode ( "<br/>", $taxa2 ) . "</div></div>";
		
		$counts = $counts . "<br/><span class='big'>Total </span>";
		$counts .= "<div class='row'><div class='col-lg-6'></div>";
		$counts .= "<div class='col-lg-6'>" . $total . "</div></div>";
		
		Yii::$app->db->close ();
		// Yii::info("getCounts: ".$counts);
		
		return $counts;
	}
	public function getTotal() {
		$connection = new \yii\db\Connection ( Yii::$app->db );
		$connection->open ();
		
		$command = $connection->createCommand ( 'SELECT count(occurrenceid) as cnt FROM occurrence' );
		$dataReader = $command->queryAll ();
		$total = 0;
		foreach ( $dataReader as $row ) {
			$total = $row ['cnt'];
		}
		
		Yii::$app->db->close ();
		// Yii::info("getCounts: ".$counts);
		
		return $total;
	}
	function getNews() {
		ini_set ( 'default_socket_timeout', 3 );
		$news = @file_get_contents ( "http://wiki.bgbm.org/dnabankwiki/api.php?action=parse&prop=sections&page=News&format=json" );
		if (! $news)
			$news = [ ];
		else {
			if (strpos ( $news, "internal_api_error" ) > 0)
				return [ ];
			else
				try {
					$jsonnews = json_decode ( $news );
					$newsitems = $jsonnews->parse->sections;
					$news = [ ];
					$year = date ( "Y" );
					foreach ( $newsitems as $newsitem ) {
						if (strpos ( $newsitem->line, strval ( $year ) ))
							array_push ( $news, [ 
									$newsitem->line,
									"http://wiki.bgbm.org/dnabankwiki/index.php/News#" . $newsitem->anchor 
							] );
					}
					if (sizeof ( $news ) === 0) {
						// get last year
						$year --;
						foreach ( $newsitems as $newsitem ) {
							$tmp = $newsitem->line;
							if (stripos ( $newsitem->line, strval ( $year ) ))
								array_push ( $news, [ 
										$newsitem->line,
										"http://wiki.bgbm.org/dnabankwiki/index.php/News#" . $newsitem->anchor 
								] );
						}
					}
				} catch ( Exception $e ) {
					$news = [ ];
				}
		}
		return $news;
	}
	
	public function actionFeedback(){
		$model = new FeedbackForm();
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			if ($model->sendEmail ( Yii::$app->params ['feedbackMail'] )) {
				Yii::$app->session->setFlash ( 'success', 'Thank you for your feedback.' );
			} else {
				Yii::$app->session->setFlash ( 'error', 'There was an error sending email.' );
			}
				
			return $this->refresh ();
		} else {
			echo $this->renderPartial( 'feedback', [
					'model' => $model
			] );
		}
		
	}
}