<?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_mail=htmlspecialchars($_POST["old_mail"]);
	$new_mail=htmlspecialchars($_POST["new_mail"]);
	$new_mail2=htmlspecialchars($_POST["new_mail2"]);
	$form_password=md5(htmlspecialchars($_POST["us_password"]));

	if($new_mail!=$new_mail2){
		$_SESSION['error']="E-maily se neshodují";
		header("Location: change_email.php");
	}else{
			if($old_mail!=$_SESSION['us_mail']){
				$_SESSION['error']="Špatný email";
				header("Location: change_email.php");
			}else{
				if($form_password!=$_SESSION['us_password']){
					$_SESSION['error']="Špatné heslo";
					header("Location: change_email.php");
				}else{
					$sql="SELECT us_mail from users WHERE us_mail='$new_mail'";
					$result = $conn->query($sql);
                    if ($result->num_rows > 0) {
                    	$_SESSION['error']="E-mail je jíž zaregistrovaný";
                    	header("Location: change_email.php");
                    }else{     

							$us_name=$_SESSION['us_name'];
							$us_password=$_SESSION['us_password'];
							$sql="UPDATE users SET us_mail='$new_mail' WHERE us_name='$us_name' AND us_password='$us_password'";
							if ($conn->query($sql) === TRUE) {
								
								$_SESSION['us_mail']=$new_mail;
								
								$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($old_mail);
					                 

					            $mail->Subject = "E-mail změněn";      
					            $mail->Body = "Váš E-mail byl změněn";
					            if($mail->send()){
					            	$_SESSION['error']="E-mail změněn";
					              	header("Location: change_email.php");
					            }else{
					                $_SESSION['error']="E-mail změněnm problém s odesláním E-mailu";
					                header("Location: change_email.php");
					            }      
					                                                                 //mail end


							    

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

		
	}

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

}
ob_end_flush();
?>