<!-- Realisatsiooni aluseks on võetud:
Login Registration with Email Verification, Forgot Password using PHP
Kasutatud 6.04.2016
http://www.codingcage.com/2015/09/login-registration-email-verification-forgot-password-php.html
-->

<?php
include "config.php";
session_start();
include_once ROOT . 'db/dbconfig.php';
require_once ROOT . 'admin/objects/kasutaja.class.php';
$user_home = new Kasutaja();

if($user_home->is_logged_in()!="")
{
	$user_home->redirect(ROOT.'index.php');
}

if(isset($_POST['btn-submit']))
{
	$email = $_POST['email'];
	
	$stmt = $user_home->runQuery("SELECT id FROM kasutajad WHERE email=:email LIMIT 1");
	$stmt->execute(array(":email"=>$email));
	$row = $stmt->fetch(PDO::FETCH_ASSOC);	
	if($stmt->rowCount() == 1)
	{
		$id = base64_encode($row['id']);
		$code = md5(uniqid(rand()));
		
		$stmt = $user_home->runQuery("UPDATE kasutajad SET token=:token WHERE email=:email");
		$stmt->execute(array(":token"=>$code,"email"=>$email));
		
		$message= "
		Hea klient,
		<br />
		Soovisite sooritada salasõna vahetust. Uue salasõna seadmiseks klõpsake järgneval lingil:
		<br /><br />
		<a href='".ROOT."scripts/resetpass.php?id=$id&code=$code'>Vaheta salasõna</a>
		<br /><br />
		Lugupidamisega,
		<br />
		Oksjoniportaal
		";
		$subject = "Paroolivahetus";
		
		$user_home->send_mail($email,$message,$subject);
		
		$msg = "<div class='alert alert-success'>
		<button class='close' data-dismiss='alert'>&times;</button>
		Juhised salasõna vahetamiseks saadeti järgnevale meiliaadressile: $email.
	</div>";
}
else
{
	$msg = "<div class='alert alert-danger'>
	<button class='close' data-dismiss='alert'>&times;</button>
	E-maili ei leitud. 
</div>";
}
}
?>

<?php
include ROOT . "header.php";
?>


<div class="container">

	<div class="col-md-6 col-md-offset-3">

		<form class="form-signin" method="post">
			<h2>Salasõna vahetamine</h2><hr />

			<?php
			if(isset($msg))
			{
				echo $msg;
			}
			else
			{
				?>
				<div class='alert alert-info'>
					Palun sisesta registreerimisel kasutatud meiliaadress, kuhu saadetakse juhised salasõna vahetamiseks.</div>
					<?php
				}
				?>

				<div class="form-group">
					<label>E-mail:</label>
					<input type="email" class="form-control" placeholder="E-mail" name="email" required  />
				</div>

				<div class="form-group">
					<center>             
						<button type="submit" class="btn btn-default" name="btn-submit">
							<span class="glyphicon glyphicon-log-in"></span> &nbsp; Saada
						</button> 
					</center>
				</div> 

			</form>
			<hr />
			<center>
				<a href="signup.php">Ei ole veel kasutajat? Registreeru siin! </a>
			</center>
		</div>

		<?php
		include ROOT . "footer.php";
		?>
