<?php

$title = "Восстановление пароля";
require (CORE."head.php");

echo "<div class=\"app-block\"><div class=\"list\"><div class=\"app-block-w\">";

if ($__user = DB :: $dbh -> queryFetch("SELECT `id` FROM `users` WHERE `restore` = ? LIMIT 1;", array(system :: check($_GET['key'])))) 
{
	if(isset($_POST['cfms-password'])) 
	{
		if (empty($_POST['password']) || system::utf_strlen($_POST['password']) < 6 || system::utf_strlen($_POST['password']) > 32)
		{
			$e = 'Неверны формат пароля.';
		}
		elseif ($_POST['password'] != $_POST['password_r'])
		{
			$e = 'Пароли не совпадают.';
		}
		elseif (!preg_match('|^[a-z0-9\-]+$|i', $_POST['password']))
		{
			$e = 'Недопустимые символы в новом пароле.';
		}
		elseif ($_POST['password'] == $__user['password'] || System::bhash($_POST['password']) == $__user['password'])
		{
			$e = 'Вы ввели уже используемый пароль.';
		}
		else
		{
			$sid = system :: genHash($_POST['password'], $__user['id']);
			$access = rand(100000000, 200000000);

			DB :: $pdo -> query("UPDATE `users` SET `sid` = ?, `password` = ?, `access` = ?, `restore` = ?, `password_update` = ? WHERE `id` = ? LIMIT 1",array($sid, System::bhash($_POST['password']), $access, '', 1, $__user['id']));

			setcookie('xsid', $sid, time()+60*60*24*365, "/");

			header('location: /');
			exit;
		}
	}

	if(isset($e))
	{ 
		system :: show($e); 
	}

	?>
	<form method="post" action="?key=<?= $__user['restore']; ?>">
		<label class="_gray _dbl" for="index-password">Новы пароль:</label>
		<input type="password" class="main-input _w-100" name="password">
		<label class="_gray _dbl" for="index-password-r">Пароль еще раз:</label>
		<input type="password" class="main-input _w-100" name="password_r">
		<div class="_center _btn-up">
		<input type="submit" class="main-btn_b _w-100" name="cfms-password" value="Изменить">
		</div>
	</form>
	<?
}
else
{ 
	system :: show('Неверный ключ восстановления.'); 
}
require (CORE."foot.php");
?>