<?php
/**
 * @copyright Gmed srl
 * @author Mirko Giulianini
 *
 * funzione per inviare una mail
 */

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


require '../include/mail/PHPMailer.php';
require '../include/mail/SMTP.php';
require '../include/mail/Exception.php';

/**
 * 
 * @param string[]  $mail_to
 * @param string    $mail_subject
 * @param string    $mail_body
 * @param type      $attach
 * @return boolean
 */
function SendMail(array $mail_to, $mail_subject, $mail_body, $attach = []) {
    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
    try {
        //Server settings
        $mail->SMTPDebug = 0;                                 // Enable verbose debug output
        if (email_server_smtp === true) {
            $mail->isSMTP();                                  // Set mailer to use SMTP
        }
        $mail->Host = email_server_host;                    // Specify main and backup SMTP servers
        $mail->SMTPAuth = email_server_auth;                               // Enable SMTP authentication
        $mail->Username = email_username;                 // SMTP username
        $mail->Password = email_userpassword;                           // SMTP password
        $mail->SMTPSecure = email_server_ssl;                  // Enable TLS encryption, `ssl` also accepted
        $mail->Port = email_server_port;                       // TCP port to connect to
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        //Recipients

        foreach ($mail_to as $ingle_mail) {

            switch ($ingle_mail[0]) {
                case "to":
                    $mail->addAddress($ingle_mail[1], $ingle_mail[2]);

                    break;

                case "cc":
                    $mail->addCC($ingle_mail[1], $ingle_mail[2]);
                    break;
            }
        }

        $mail->setFrom(email_from, email_from_name);
        // Add a recipient
        $mail->addReplyTo(email_from, email_from_name);
        //$mail->addCC('cc@example.com');
        //$mail->addBCC('bcc@example.com');
        //Attachments

        foreach ($attach as $sa) {
            $mail->addAttachment($sa['path'], $sa['name']);
        }

        //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
        //Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = $mail_subject;
        $mail->Body = $mail_body;
        $mail->AltBody = '';


        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log($e);
        return false;
    }
}