<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

require '../includes/Exception.php';
require '../includes/PHPMailer.php';
//require "PHPMailerAutoload.php";
require '../includes/SMTP.php';

require "../includes/connect.php";

function generateRandomString($length = 10) {
	return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

if (isset($_POST['mail']) && !empty(($_POST['mail']))) {
	$topo = $_POST["mail"];

	$qSelect = $connection->prepare("SELECT count(*) as qta from account_leads WHERE email=?");
	$qSelect->execute(["$topo"]);
	$res = $qSelect->fetch(PDO::FETCH_OBJ);
	$mailExists = $res->qta;

	if ($mailExists) {
		$gatto = generateRandomString();
		$qUpdate = $connection->prepare("UPDATE account_leads SET motto=md5(?) WHERE email=?");
		$qUpdate->execute(["$gatto", "$topo"]);

		$mailHtml = "Dear " . $topo . ",<br>
this is your new password:  " . $gatto . "<br>
Save this e-mail for the future!<br><br>
See you soon, <em>the Staff</em>";
		$altMail = "Dear visitor,<br>
this is your new password:  " . $gatto . "<br>
Save this e-mail for the future!<br><br>
See you soon, <em>the Staff</em>";

		$emailInviatore = 'back@labakeca.eu';

		// $emailBcc = "webmaster@elenchitelefonici.it";
		try {

			// configurazione invio email
			$mail = new PHPMailer(true);

			$mail->isSMTP();
			//$mail->SMTPDebug = 4;
			$mail->Mailer = "smtp";
			$mail->Host = 'mail.labakeca.eu'; // Set the SMTP server to send through
			$mail->SMTPAuth = true; // Enable SMTP authentication
			$mail->SMTPAutoTLS = true;
			$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
			#$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
			$mail->Username = 'back@labakeca.eu'; // SMTP username
			$mail->Password = 'MGX7W7UCFJL'; // SMTP password
			$mail->Port = 587; // or 465                                 // TCP port to connect to

			$mail->setFrom($emailInviatore, 'Password recovery request LaBakeca.eu');
			$mail->addReplyTo($emailInviatore, 'Password recovery request LaBakeca.eu');
			$mail->addAddress($topo);
			$mail->isHTML(true);
			$mail->Subject = "$topo, here is your new password.";
			$mail->Body = $mailHtml;
			$mail->altBody = $altMail;
			// $mail->addBcc($emailBcc);
			$mail->send();
			// echo 'Message has been sent';
			echo "Password recovery mail sent!";
		} catch (Exception $e) {
			//echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
			echo "Nope";

		}

	} else {echo "Nope";}

} else {echo "Nope";}

?>