<?php

/**
 * Snippet to display and action the members password reset 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 - 2015 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

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

// If step 2 show form to let user update their details
if(clearFusionCMS::getRequest()->hasParam('step') && clearFusionCMS::getRequest()->getParam('step') == 2) {
	$form = new flForm(clearFusionCMS::getRequest(), 'pwdresetform', $controller->content->getPageURI($controller->pageData['id']) . '?step=2', true);

	$email = new flFormElementText($form, 'email');
	$email->setLabel(__('Email Address', 'members'))
		->setRequired()
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorEmail())
		->setDescription(__('Your registered email address.', 'members'));

	$auth = new flFormElementText($form, 'authcode');
	$auth->setLabel(__('Authorization Code', 'members'))
		->setRequired()
		->addValidator(new flFormValidatorRequired())
		->setDescription(__('The authorization code from the email sent to your registered email address in the previous step.', 'members'));

	$pwd = new flFormElementPassword($form, 'pwd');
	$pwd->setLabel(__('New Password', 'members'))
		->setRequired()
		->setDescription(__('The password must be at least 8 characters long.', 'members'))
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorMinLength(8));

	$pwd2 = new flFormElementPassword($form, 'pwd2');
	$pwd2->setLabel(__('Confirm Password', 'members'))
		->setRequired()
		->addValidator(new flFormValidatorSameAs($pwd));

	$submit = new flFormElementSubmit($form, 'resetpwd');
	$submit->setCaption(__('Reset Password', 'members'))->setCSS('primary');

	$form->focusElement($email);

	$show = true;
	if($form->isSubmitted() && $form->isValid()) {

		$userMgr = clearFusionCMS::getUserMgr();
		$uid = $userMgr->find($email->getValue(), array('email'), true);
		if(!count($uid) || $auth->getValue() != $userMgr->getVerificationHash($uid[0]))
			$email->forceError(__('Unable to reset your password as one or more pieces of information are incorrect.', 'members'));
		else {
			$userMgr->setPassword($uid[0], $pwd->getValue());
			$show = false;
			if(isset($onComplete))
				$controller->getResponse()->redirectTo($controller->content->getPageURI($onComplete, true));
			else
				echo __('<p>Your password has been set to the new value.</p>', 'members');
		}
	}

	if($show)
		echo $form->render($tplEngine->getCodeBuffer());
}
// Else show form to get users email address
else {
	$form = new flForm(clearFusionCMS::getRequest(), 'pwdresetform', $controller->content->getPageURI($controller->pageData['id']), true);

	$email = new flFormElementText($form, 'email');
	$email->setLabel(__('Email Address', 'members'))
		->setRequired()
		->addValidator(new flFormValidatorRequired())
		->addValidator(new flFormValidatorEmail())
		->setDescription(__('Please enter your registered email address.', 'members'));

	$submit = new flFormElementSubmit($form, 'forgotpwd');
	$submit->setCaption(__('Reset Password', 'members'))->setCSS('primary');

	$form->focusElement($email);

	if($form->isSubmitted() && $form->isValid()) {

		$userMgr = clearFusionCMS::getUserMgr();
		$uid = $userMgr->find($email->getValue(), array('email'), true);

		if(count($uid) == 1) {
			$info = $userMgr->getInfo($uid[0]);

			$cfg = clearFusionCMS::getSiteConfig('cfMembers');
			$data = array(
				'sitename' => clearFusionCMS::getSiteName(),
				'username' => $info['username'],
				'reseturi' => $controller->content->getPageURI($controller->pageData['id'], true) . '?step=2',
				'hash' => $userMgr->getVerificationHash($uid[0])
			);

			// Process the HTML and text email bodies
			$tplEngine = new cfTemplateEngine($controller);
			$html = $tplEngine->parseString("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n</head>\n<body>\n" . $cfg->pwdResetEmailHTML . "\n</body>\n</html>\n", $data);
			$text = $tplEngine->parseString($cfg->pwdResetEmail, $data);

			$mailer = clearFusionCMS::getMailer();
			if($mailer->connect()) {
				$mailer
					->setTextBody($text)
					->setHTMLBody($html)
					->setSubject(str_replace('[[+sitename]]', clearFusionCMS::getSiteName(), $cfg->pwdResetSubject))
					->addRecipient($email->getValue());

				$mailer->send();
				$mailer->close();

				// Go to step 2
				clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($controller->pageData['id'], true) . '?step=2');
			}
			else
				$email->forceError(__('Failed to send the password reset email, please try again.', 'members'));
		}
		else
			$email->forceError(__('Failed to find a record of that email address, please try again.', 'members'));
	}

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