<?php
require 'mailer/src/Exception.php';         //knihovna mail
require 'mailer/src/PHPMailer.php';
require 'mailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
session_start();
ob_start();
require_once("db_connect.php");

$us_mail=htmlspecialchars($_POST["mail"]);
$sql="SELECT * FROM users WHERE us_mail='$us_mail'";
$result=$conn->query($sql);

if ($result->num_rows == 1) {
	$new_password=rand();
	$new_password_hash=md5($new_password);
	$sql="UPDATE users SET us_password='$new_password_hash' WHERE us_mail='$us_mail'";
	if ($conn->query($sql) === TRUE) {
		$mail = new PHPMailer;                                          //mail start
		$mail->isSMTP();    
		$mail->Host = "smtp.gmail.com";
		$mail->SMTPAuth = true;
		$mail->Username = $mailuser;
		$mail->Password = $mailpassword;
		$mail->SMTPSecure = "tls";
		$mail->Port = 587;
		$mail->CharSet = "utf-8"; 
		$mail->isHTML();
		$mail->setFrom($mailuser, "Be secured"); 
		$mail->addAddress($us_mail);
						                 

		$mail->Subject = "Zapomenuté heslo";      
		$mail->Body = "Vaše nové heslo: " . $new_password;
		if($mail->send()){
		 	$_SESSION['error']="Heslo zasláno";
		   	header("Location: forgot-password.php");
		}else{
		    $_SESSION['error']="Problém s odesláním emailu";
		    header("Location: forgot-password.php");
		}      															//mail end
	}else{
		$_SESSION['error']="Chyba";
		header("Location: forgot-password.php");
	}				                                                                 
	

}else{
	$_SESSION['error']="E-mail nenalezen";
	header("Location: forgot-password.php");
}


ob_end_flush();
?>