<?php

/**
 * Snippet to display and action the members login form.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\members
 * @copyright Copyright (c) 2012 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/* @var $tplEngine cfTemplateEngine */
$controller = $tplEngine->controller;

// If already logged in then send to destination page
if(clearFusionCMS::getUser()->isAuthenticated()) {
	if(isset($onLoggedIn) && !isset($formOnly))
		$controller->getResponse()->redirectTo($controller->content->getPageURI($onLoggedIn, true));
}
// Else show form and get user to login
else {
	$loginByUsername = isset($loginByUsername) ? $loginByUsername : 1;
	$loginByEmail = isset($loginByEmail) ? $loginByEmail : 0;
	$pwdReset = isset($pwdReset) ? $pwdReset : 0;
	$prefix = isset($prefix) ? $prefix : '';
	$with2FA = isset($with2FA) ? $with2FA : false;

	$loginPage = isset($loginPage) ? $loginPage : $controller->pageData['id'];
	$form = new flForm(clearFusionCMS::getRequest(), $prefix . 'loginform', $controller->content->getPageURI(isset($loginPage) ? $loginPage : $controller->pageData['id'], true));

	$username = new flFormElementText($form, $prefix . 'username');
	$username->setLabel(($loginByUsername ? __('Username', 'members') : '') . ($loginByEmail ? (($loginByUsername ? ' / ' : '') . __('Email Address', 'members')) : ''))
		->setAutocomplete($loginByUsername ? 'username' : 'email')
		->setRequired()
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorMaxLength(100));

	if(!$loginByUsername && $loginByEmail)
		$username->addValidator(new flFormValidatorEmail());

	$password = new flFormElementPassword($form, $prefix . 'password');
	$password->setLabel(__('Password', 'members'))
		->setAutocomplete('current-password')
		->setRequired()
		->addValidator(new flFormValidatorRequired());

	// If have password reset page
	if($pwdReset)
		$password->setDescription('<a href="' . $tplEngine->controller->content->getPageURI($pwdReset) . '">' . __('Forgotten your password?', 'members') . '</a>');

	if($with2FA) {
		$twoFactor = new flFormElementText($form, 'twoFactor');
		$twoFactor->setLabel(__('Google Authenticator Code', 'members'))
			->setDescription(__('If you have two factor authentication enabled on your account then complete this field, otherwise leave it blank.', 'members'));
	}

	$remember = new flFormElementCheckbox($form, $prefix . 'rememberme', 0);
	$remember->setLabel(__('Remember Me', 'members'))
		->setDescription(__('You should not check this option if you are on a shared or public computer.', 'members'));

	// Enable recaptcha
	if(isset($siteKey) && isset($secretKey)) {
		$recaptcha = new flFormElementRecaptcha($form, $prefix . 'recaptcha', $siteKey, $secretKey);
	}
	else if(isset($recaptcha) && $recaptcha) {
		$cfg = clearFusionCMS::getSiteConfig('cfSystemSocialAPI');
		$recaptcha = new flFormElementRecaptcha($form, $prefix . 'recaptcha', $cfg->get('recaptcha_sitekey'), $cfg->get('recaptcha_secretkey'));
	}

	$submit = new flFormElementSubmit($form, $prefix . 'login');
	$submit->setCaption(__('Login', 'members'))->setCSS('primary');

	if(!isset($noFocus))
		$form->focusElement($username);

	$show = true;
	if($form->isSubmitted() && $form->isValid()) {
		// Authenticate the user & send to destination page
		if(clearFusionCMS::getUser()->authenticate($username->getValue(), $password->getValue(), $remember->getValue(), $loginByUsername && !$loginByEmail ? 'username' : (!$loginByUsername && $loginByEmail ? 'email' : null))) {

			// If two factor authentication enabled test it
			$secret = clearFusionCMS::getUser()->getAuthKey();
			if(isset($twoFactor) && !empty($secret) && !flAuthTOTP::verifyCode($secret, $twoFactor->getValue())) {
				$username->forceError(__('Failed to authenticate you using the supplied credentials. Please check that they are correct and try again.', 'members'));
				clearFusionCMS::getUser()->logout();
			}
			else {
				$show = false;
				if (isset($onLoggedIn))
					$controller->getResponse()->redirectTo($controller->content->getPageURI($onLoggedIn, true));
			}
		}
		// Else show failed
		else
			$username->forceError(__('Failed to authenticate you using the supplied credentials. Please check that they are correct and try again.', 'members'));
	}

	if($show)
		echo $form->render($tplEngine->getCodeBuffer());
}
