<!-- 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();
include ROOT . "header.php";

if(empty($_GET['id']) && empty($_GET['code']))
{
	$user_home->redirect(ROOT . 'index.php');
}

if(isset($_GET['id']) && isset($_GET['code']))
{
	$id = base64_decode($_GET['id']);
	$code = $_GET['code'];
	
	$stmt = $user_home->runQuery("SELECT * FROM kasutajad WHERE id=:uid AND token=:token");
	$stmt->execute(array(":uid"=>$id,":token"=>$code));
	$rows = $stmt->fetch(PDO::FETCH_ASSOC);
	
	if($stmt->rowCount() == 1)
	{
		if(isset($_POST['btn-reset-pass']))
		{
			$pass = $_POST['parool1'];
			$cpass = $_POST['parool2'];
			
			if($cpass!==$pass)
			{
				$msg = "<div class='alert alert-danger'>
						<button class='close' data-dismiss='alert'>&times;</button>
						Sisestatud paroolid ei ühti!
						</div>";
			}
			else
			{
				$password = md5($cpass);
				$stmt = $user_home->runQuery("UPDATE kasutajad SET parool=:upass WHERE id=:uid");
				$stmt->execute(array(":upass"=>$password,":uid"=>$rows['id']));
				
				$msg = "<div class='alert alert-success'>
						<button class='close' data-dismiss='alert'>&times;</button>
						Parooli vahetamine oli edukas.
						</div>";
				header("refresh:3;login.php");
			}
		}	
	}
	else
	{
		$msg = "<div class='alert alert-success'>
				<button class='close' data-dismiss='alert'>&times;</button>
				Kasutajat ei leitud. Palun proovi uuesti!
				</div>";		
	}
}

?>

  <div class="container">

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

    	<div class='alert alert-success'>
			Hea <?php echo $rows['eesnimi'] ?>, palun vali endale uus parool ning sisesta see kaks korda.
		</div>

        <form class="form-signin" method="post">
        <h2>Uue parooli seadmine</h3>
        <?php
        if(isset($msg))
		{
			echo $msg;
		}
		?>
		<div class="form-group">
        <input type="password" class="form-control" placeholder="Uus parool" name="parool1" required />
        </div>
        <div class="form-group">
        <input type="password" class="form-control" placeholder="Uue parooli kinnitus" name="parool2" required />
        </div>
        <div class="form-group">
        <center>
        <button class="btn btn-large btn-primary" type="submit" name="btn-reset-pass">Salvesta</button>
        </center>
        </div>
      </form>
<hr />
<center>
        <a href="signup.php">Ei ole veel kasutajat? Registreeru siin! </a>
</center>
</div>

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