<?php 
if(file_exists('../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}

//echo '../output/'.$_REQUEST['source_1'].'/'.$_REQUEST['attachment_1'];
//if($_REQUEST['src']=="ext"){$mailExt="auto";}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//echo '../output/'.$_REQUEST['source_1'].'/'.$_REQUEST['attachment_1'];
if($mailExt!="auto"){
require '../packages/mailer/Exception.php';
require '../packages/mailer/PHPMailer.php';
require '../packages/mailer/SMTP.php';
}
else{
require '../../packages/mailer/Exception.php';
require '../../packages/mailer/PHPMailer.php';
require '../../packages/mailer/SMTP.php';
}

function storeImage($n){
$f = $_FILES[$n];
$filename = $f["name"];

move_uploaded_file($_FILES[$n]["tmp_name"],  '../../'.$_REQUEST['tenant'].'/storage/'.$filename);
return($filename);
}

//echo "email:".$_REQUEST['recipient_1'];
if($mailExt!="auto"){
$header=file_get_contents('../includes/email/email_template.php');
}
else{
$header=file_get_contents('../../includes/email/email_template.php');
}
$header=str_replace('[SITE]',getCompanyDetails('web'),$header);
$header=str_replace('[MESSAGE]',nl2br($_REQUEST['message']),$header);
$header=str_replace('[LOGO]',getCompanyDetails('web').'/images/company/logo_thumb.jpg?'.rand(),$header);
$header=str_replace('[ENREP]',getCompanyDetails('web').'/images/logo_border.png?'.rand(),$header);
$header=str_replace('[ADDRESS]',getCompanyDetails('addressLong'),$header);
$header=str_replace('[CONTACT]',getCompanyDetails('contact'),$header);
$header=str_replace('[SUBJECT]',$_REQUEST['subject'],$header);


$mail = new PHPMailer(true);
try {
$mail->SMTPDebug=0;
$mail->isSMTP();
$mail->Host=getEmailSystemSettings('host');
$mail->SMTPAuth=true;
$mail->Username=getEmailSystemSettings('username');
$mail->Password=getEmailSystemSettings('password');
$mail->SMTPSecure='spa';
$mail->Port=587;
$mail->setFrom(getEmailSystemSettings('from'), getEmailSystemSettings('from_name'));

if(!empty($_REQUEST['report_1'])){
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_1'].'/'.$_REQUEST['report_1']);
$attach="|attached 1";
$fstring="with the file(s) ".$_REQUEST['report_1'];
}
if(!empty($_REQUEST['file_1'])){
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_1'].'/'.$_REQUEST['file_1']);
$attach="|attached 1";
$fstring="with the file(s) ".$_REQUEST['file_1'];
}
if(!empty($_REQUEST['file_2'])){
    $mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_2'].'/'.$_REQUEST['file_2']);
    $attach="|attached 1";
    $fstring="with the file(s) ".$_REQUEST['file_2'];
    }
if(!empty($_FILES['attachment_1']['name'])){
$file1=storeImage('attachment_1');
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/storage/'.$file1);
$attach.="|attached 1"; $fstring="with the file(s) ".$_REQUEST['file_1'];
}
if(!empty($_FILES['attachment_2']['name'])){
$file2=storeImage('attachment_2');
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/storage/'.$file2);
$attach.="|attached 2"; $fstring.=",".$file2;
}
if(!empty($_FILES['attachment_3']['name'])){
$file3=storeImage('attachment_3');
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/storage/'.$file3);
$attach.="|attached 3"; $fstring.=",".$file3;
}
if(!empty($_FILES['attachment_4']['name'])){
$file4=storeImage('attachment_4');
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/storage/'.$file4);
$attach.="|attached 4"; $fstring.=",".$file4;
}
$rstring="Sent Email to ";
$recipientCount = 0;
$rstring = "Sent Email to ";
$mail->clearAddresses();
$uniqueEmails = [];
$tracking_id = uniqid('em_', true);
foreach ($_REQUEST as $key => $value) {
    if (preg_match('/^recipient_\d+$/', $key) && !empty($value)) {
        $email = trim(strtolower($value));
        if (!in_array($email, $uniqueEmails)) {
            $mail->addAddress($email);
            $rstring .= ",".$email;
            $uniqueEmails[] = $email;
        }
    }
}

$email_type = $_REQUEST['source_1'] ?? '';
$subject = $_REQUEST['subject'];
$sent_at = date('Y-m-d H:i:s');
$reference = $_REQUEST['reference'];
$header .= '<img src="' . getCompanyDetails('web') . '/track_open.php?id=' . $tracking_id . '" width="1" height="1" style="display:none;" alt="" />';

$mail->addReplyTo(getEmailSystemSettings('from'), getEmailSystemSettings('from_name'));
//$mail->addBCC('keith@daso-interactive.co.uk', 'Keith Fielding');

$mail->isHTML(true);
$mail->Subject = $_REQUEST['subject'];
$mail->Body    = $header;
$mail->AltBody = $_REQUEST['message'];

$mail->send();
    writeLog("email",$rstring." ".$fstring);
    echo json_encode(['status' => 'success', 'message' => 'Email sent successfully.']);

    foreach ($uniqueEmails as $email) {
    $stmt = $con->prepare("INSERT INTO email_tracking (tracking_id, recipient, email_type, subject, reference, sent_at) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('ssssss', $tracking_id, $email, $email_type, $subject, $reference, $sent_at);
    $stmt->execute();
    }

} catch (Exception $e) {
    $errorInfo = $mail->ErrorInfo;
    writeLog("email_error", $errorInfo);
    echo json_encode(['status' => 'error', 'message' => 'Message could not be sent. Mailer Error: ' . $errorInfo]);
}


?>