<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
    
defined('_MAILING') or die('Restricted access');

if (DEMO_MODE) {
    echo "Not available in DEMO mode";
    exit();
}

$app->checkToken();


$templateid = (int)$_POST['templateid'];
$smtpid = (int)$_POST['smtpid'];
$mailTo = $_POST['mailTo'];

// in case of header double end of line problems when email is sending thru different servers
$eol = $app->getSystemEOL();

// get template data
$stmt = $db->query(" SELECT * from ".PREF."_template WHERE id = '".$templateid."' ");
$stmt->execute();
$row = $stmt->fetchAll();
$email_subject = $row[0]['subject'];
$doctype	= $row[0]['doctype'];
$email_html_header	= $row[0]['html_header'];
$body_attribs	= $row[0]['body_attribs'];
$email_content_html	= $row[0]['content_html'];
$email_content_txt	= $row[0]['content_txt'];

// get template attachments
$filenames = Array();
$dir = $_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['SCRIPT_NAME']).'/uploads/';
$files = $db->query("
    SELECT 
        filename
    from 
        ".PREF."_template_att_conn as tac 
        left join ".PREF."_template_att as ta on(ta.id = tac.id_att)
    WHERE 
        tac.id_template = '".$templateid."' 
");
foreach ($files as $file) {
    if (file_exists($dir.$file['filename'])) {
        array_push($filenames, $file['filename']);
    }
}





$num = md5(time());
$sender_name = 'E-mailer - template';
$sender_email = Settings::$adminMail;
$message_html = $email_content_html;
$email_tracker = '';
$message_txt = $email_content_txt;
$recipient_email = $mailTo;
$subject = $email_subject;


if ($sender_email == '') {
    echo NO_ADMIN_MAIL;
    exit();
}


// use PHP mail native
if (! $smtpid) {
    
    // Define the main headers.
    $header = "From: ".$sender_name." <".$sender_email.">".$eol;
    $header .= "MIME-Version: 1.0".$eol;
    $header .= "Content-Type: multipart/mixed; ";
    $header .= "boundary=$num".$eol;
    
    $message = "--$num".$eol;
    $message .= "Content-type:text/html;charset=UTF-8".$eol;
    $message .= "Content-Transfer-Encoding:8bit".$eol.$eol;
    $message .= "<".stripslashes($doctype)."><html><head>".stripslashes($email_html_header)."</head><body ".stripslashes($body_attribs).">".stripslashes($message_html).$email_tracker."</body></html>".$eol;
    $message .= "--$num".$eol;

    // attachments
    foreach ($filenames as $file) {
        $message .= "Content-Type: application/octet-stream; name=\"".$file."\"".$eol;
        $message .= "Content-ID: <".$file.">".$eol;
        $message .= "Content-Transfer-Encoding: base64".$eol;
        $message .= "Content-Disposition: attachment; filename=\"".$file."\"".$eol.$eol;
        $message .= chunk_split(base64_encode(file_get_contents($dir.$file))).$eol.$eol;
        $message .= "--$num".$eol;
    }

    $message .= "--$num--";

    try {
        mail($recipient_email, $subject, $message, $header);
        echo SMTP_TEST_OK;
    } catch (Exception $e) {
        echo 'ERROR: ',  $e->getMessage(), "\n";
    }
    
}


// use SMTP server
if ($smtpid) {
    
    // get SMTP server id
    $smtpid = (int)($_POST['smtpid']);
    
    $stmt = $db->prepare(" select * from ".PREF."_smtp where id=? ");
    $stmt->bindParam(1, $smtpid, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetchAll();
    @$data = $row[0];

    $host = $data['host'];
    $smtpauth = $data['smtpauth'] == '1' ? true : false ;
    $forcesmtp = $data['forcesmtp'] == '1' ? true : false ;
    $verifypeer = $data['verifypeer'] == '1' ? true : false ;
    $username = $data['username'];
    $login = $data['login'];
    $password = $data['password'];
    $replytomail = $data['replytomail'];
    $replytoname = $data['replytoname'];
    $smtpsecure = $data['smtpsecure'];
    $port = $data['port'];
    $maxlimit = $data['maxlimit'];

    //use DKIM
    $usedkim = $data['usedkim'];
    $DKIM_domain = $data['dkim_domain'];
    $DKIM_private = $data['dkim_private'];
    $DKIM_selector = $data['dkim_selector'];
    $DKIM_passphrase = $data['dkim_passphrase'];
    $DKIM_identity = $data['dkim_identity'];
    
    //require 'php/PHPMailerAutoload.php';


    require_once 'php/class/PHPMailer/src/Exception.php';
    require_once 'php/class/PHPMailer/src/PHPMailer.php';
    require_once 'php/class/PHPMailer/src/SMTP.php';

    $mail = new PHPMailer;
    $mail->CharSet = "UTF-8";
    //$mail->SMTPDebug = 3;
    if (!$verifypeer) {
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
    }
    if ($forcesmtp) {
        $mail->isSMTP();
    }
    $mail->Host = $host;
    $mail->Port = $port;
    $mail->SMTPAuth = $smtpauth;
    $mail->Username = $login;
    $mail->Password = $password;
    
    $mail->SMTPSecure = $smtpsecure;
    $mail->setFrom($username); // bounce to
    
    $mail->ClearReplyTos();
    $mail->AddReplyTo($replytomail, $replytoname);
    $mail->From = $sender_email;
    $mail->FromName = $sender_name;
    $mail->addAddress($recipient_email);
    
    if ($usedkim == '1') {
        $mail->DKIM_domain = $DKIM_domain;
        $mail->DKIM_private = $DKIM_private;
        $mail->DKIM_selector = $DKIM_selector;
        $mail->DKIM_passphrase = $DKIM_passphrase;
        $mail->DKIM_identity = $DKIM_identity;
    }
    

    
    // attachments
    foreach ($filenames as $file) {
        $mail->addAttachment($dir.$file, $file);
        //$mail->AddEmbeddedImage($dir.$file, $file);
    }

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = "<".stripslashes($doctype)."><html><head>".stripslashes($email_html_header)."</head><body ".stripslashes($body_attribs).">".stripslashes($message_html).$email_tracker."</body></html>";
    $mail->AltBody = $message_txt;

    if (! $mail->send()) {
        echo 'Error: ' . $mail->ErrorInfo;
        $update = false;
    } else {
        echo $data['name']." (".$host."). ".SMTP_TEST_OK;
    }

}