<?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();

if (isset($_SESSION['us_name']) AND isset($_SESSION['us_password'])){
	require_once("db_connect.php");
	


	$old_password=md5(htmlspecialchars($_POST["old_password"]));
	$new_password=htmlspecialchars($_POST["new_password"]);
	$new_password2=htmlspecialchars($_POST["new_password2"]);

	if($new_password!=$new_password2){
		$_SESSION['error']="Hesla se neshodují";
		header("Location: change_pswd.php");
	}else{
		if(strlen($new_password)<=6){
			$_SESSION['error']="Heslo musí obsahovat minimálně 6 znaků";
			header("Location: change_pswd.php");
		}else{
			if($old_password!=$_SESSION['us_password']){
				$_SESSION['error']="Špatné heslo";
				header("Location: change_pswd.php");
			}else{
				$us_name=$_SESSION['us_name'];
				$us_password=$_SESSION['us_password'];
				$new_password=md5($new_password);
				$sql="UPDATE users SET us_password='$new_password' WHERE us_name='$us_name' AND us_password='$us_password'";
				if ($conn->query($sql) === TRUE) {
					
					$_SESSION['us_password']=$new_password;

					$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($_SESSION['us_mail']);
		                 

		            $mail->Subject = "Heslo změněno";      
		            $mail->Body = "Vaše heslo bylo změněno";

		            if($mail->send()){
		                header("Location: change_pswd.php");
		                $_SESSION['error']="Heslo změněno";
		            }else{
		                header("Location: change_pswd.php");
		                $_SESSION['error']=$mail->ErrorInfo;
		            }                                                           //mail end


				   

				} else {
				    $_SESSION['error']="Chyba";
				    header("Location: change_pswd.php");
				  
				}
			}

		}
	}

}else{
  header ("Location: index.php"); 

}
ob_end_flush();
?>