<?php
error_reporting(E_ALL);
require_once("../config.inc.php");
#require('../phpmailer/class.phpmailer.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../PHPMailer6/src/Exception.php';
require '../PHPMailer6/src/PHPMailer.php';
require '../PHPMailer6/src/SMTP.php';

$empfaenger = $_POST['empfaenger'];
#    $empfaenger   = "S-1";
$mail_bcc   = array();

for ($i = 0; $i < sizeof($empfaenger); $i++) {
    $trenner = explode("-", $empfaenger[$i]);
    
    
    if ($trenner[0] == 'S') {
        $query = "select mail
                    from jumi_admin a, jumi_admin_rollen_user_zuord b
                   where a.uid=b.uid
                   and b.rid=$trenner[1]";
        
        $result = $db->query($query) or die("Cannot execute query");
        
        while ($row = $result->fetch_array()) {
            array_push($mail_bcc, "$row[mail]");
        }
    }
    
    if ($trenner[0] == 'C') {
        $query1 = "select mail
                    from jumi_chor_saenger";
        
        $result1 = $db->query($query1) or die("Cannot execute query1");
        
        while ($row1 = $result1->fetch_array()) {
            array_push($mail_bcc, "$row1[mail]");
        }
    }
    
    if ($trenner[0] == 'V') {
        $query2 = "select mail
                     from jumi_mailverteiler a, jumi_mailverteiler_entries b
                    where a.mvid=b.mvid
                      and b.mvid=$trenner[1]";
        
        $result2 = $db->query($query2) or die("Cannot execute query");
        
        while ($row2 = $result2->fetch_array()) {
            array_push($mail_bcc, "$row2[mail]");
        }
    }
}



# Doppelte Mailadressen entfernen. Fall jemand in mehreren Gruppen aktiv ist.
$mail_bcc = array_unique($mail_bcc);


function save_mail($mail)
{
    // Mails in IMAP Gesendete schieben
    #####################################################
    ## Wegen dieser Funktion, wurde PHP Version aktiviert. Siehe ../Hinweise_zu_php8.txt
    #####################################################
    

    // # Script um sich $path anzeigen zu lassen:
    // $mbox = imap_open("{imap.ionos.de:993/imap/ssl}", "info@ju-and-mi.de", "passwort", OP_HALFOPEN)
    // or die("can't connect: " . imap_last_error());
    // if($mbox){
    // echo "connect";
    // }else{
    // echo "fail";
    // }
    // $list = imap_getmailboxes($mbox, "{imap.ionos.de:993/imap/ssl}", "*");
    // if (is_array($list)) {
    // foreach ($list as $key => $val) {
    // echo "($key) ";
    // echo imap_utf7_decode($val->name) . ",";
    // echo "'" . $val->delimiter . "',";
    // echo $val->attributes . "<br />\n";
    // }
    // } else {
    // echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
    // }
    // 
    // imap_close($mbox);
    
    $path       = "{imap.ionos.de:993/imap/ssl}Gesendete Objekte";
    $imapStream = imap_open($path, $mail->Username, $mail->Password);
    # Letzter Flag Seen, damit die Mail bereits als gelesen in gesendete Objekte eingestellt wird
    $result     = imap_append($imapStream, $path, $mail->getSentMIMEMessage(),"\Seen");
    imap_close($imapStream);
    return true;
}

$mail = new PHPMailer();

try {
    //Server settings
    $mail->isSMTP(); //Send using SMTP
    $mail->CharSet    = 'UTF-8';
    $mail->Encoding   = 'base64';
    $mail->SMTPDebug  = 0;
    $mail->Host       = 'smtp.ionos.de'; //Set the SMTP server to send through
    $mail->SMTPAuth   = true; //Enable SMTP authentication
    $mail->Username   = 'info@ju-and-mi.de'; //SMTP username
    $mail->Password   = "!S3ge1gP"; //SMTP password
    $mail->Port       = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    # Priority: Options: null (default), 1 = High, 3 = Normal, 5 = low
#    $mail->Priority   = 1;
    
    //Recipients
    //$mail->SetFrom($_POST["userEmail"], $_POST["userName"]);
    //$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
    $mail->SetFrom("info@ju-and-mi.de", "Info JU & MI");
#    $mail->AddAddress("info@ju-and-mi.de", "Info JU & MI");
    $mail->AddReplyTo("info@ju-and-mi.de", "Info JU & MI");
    //$mail->addCC('cc@example.com');
    foreach ($mail_bcc as $empfbcc) {
        $mail->addBCC("$empfbcc");
    }
    
    
    //Attachments
    if (sizeof($_FILES["attachment"]["name"]) > 0) {
        foreach ($_FILES["attachment"]["name"] as $k => $v) {
            $mail->AddAttachment($_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k]);
        }
    }
    
    //Content
    $mail->isHTML(true); //Set email format to HTML
    $mail->Subject = $_POST["subject"];
    $mail->Body    = $_POST["content"];
    //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
    $mail->send();
    if (save_mail($mail)) {
        #echo "Message saved!";
    }
    echo '<div class="alert alert-success"><i class="fa fa-fw fa-thumbs-up"></i> Mail wurde versendet!</div>|***|success';
}
catch (Exception $e) {
    echo "<div class='alert alert-danger'><i class='fa fa-fw fa-thumbs-down'></i> Es konnte <b>keine Mail</b> verschickt werden! Mailer Error: {$mail->ErrorInfo}</div>|***|error";
}

?>