<?php

/*if (isset($_POST["UUID"])) {
	$UUID = $_POST["UUID"];
} else {
	header("HTTP/1.1 400 Bad Request");
	die("Es wurde keine UUID empfangen!.");
}

if (isset($_POST["Mails"])) {
        $mails = json_decode($_POST["Mails"], true);
} else {
        header("HTTP/1.1 400 Bad Request");
        die("Es wurde keine Adressen empfangen!.");
}

if (isset($_POST["Body"])) {
        $body = $_POST["Body"];
} else {
        header("HTTP/1.1 400 Bad Request");
        die("Es wurde kein Text empfangen!.");
}

if (isset($_POST["Betreff"])) {
        $betreff = $_POST["Betreff"];
} else {
        header("HTTP/1.1 400 Bad Request");
        die("Es wurde Betreff Daten empfangen!.");
}

*/
require_once "vendor/autoload.php";
//echo $mails;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

$directory = 'upload/'.$UUID."/";

// Get all files in the directory
$files = scandir($directory);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.office365.com'; // SMTP Server ändern
    $mail->SMTPAuth = true;
    $mail->Username = "fotobox@softgewerk.de"; // Benutzername von POST
    $mail->Password = "J*489106494305uf"; // Passwort von POST
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // Empfänger
    $mail->setFrom('fotobox@softgewerk.de', 'Mailer'); // Absender ändern
    $mail->CharSet = 'UTF-8';

    //Recipients
    foreach ($mails as $address) {
    	$mail->addAddress($address);
    }

    // Attachments
    foreach ($files as $file) {
	if ($file != '.' && $file != '..') {
		$mail->addAttachment($directory.$file);
	}
    }
    

    // Content
    $mail->isHTML(true);
    $mail->Subject = $betreff;
    $mail->Body    = $body;
    $mail->addCustomHeader("Reply-To", "do-not-reply@softgewerk.de"); 
    $mail->send();
    if (deleteFolder($directory)) {
    echo "OK";
} else {
    echo "Error";
}

} catch (Exception $e) {
	if (deleteFolder($directory)) {
    		echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}, ".$e;
	} else {
    		echo "Files could not be deleted. Message could not be sent. Mailer Error: {$mail->ErrorInfo}, ".$e;
	}
}


function deleteFolder($folderPath) {
    // Check if folder exists
    if (!is_dir($folderPath)) {
        return false;
    }

    // Get list of files and subdirectories in the folder
    $files = glob($folderPath . '/*');

    // Loop through each file or subdirectory
    foreach ($files as $file) {
        // If it's a directory, recursively delete it
        if (is_dir($file)) {
            deleteFolder($file);
        } else {
            // If it's a file, delete it
            unlink($file);
        }
    }

    // After deleting all files and subdirectories,
    // remove the folder itself
    return rmdir($folderPath);
}
