<?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 storeImages($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('[MESSAGE]',$_REQUEST['message'],$header);
$header=str_replace('[LOGO]',getCompanyDetails('web').'/images/company/logo.jpg?'.rand(),$header);
$header=str_replace('[ENREP]',getCompanyDetails('web').'/images/logo_border.png?'.rand(),$header);
$header=str_replace('[ADDRESS]',getCompanyDetails('address'),$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'));

foreach(range(1,50) as $c){
if(!empty($_REQUEST['report_'.$c])){
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_'.$c].'/'.$_REQUEST['report_'.$c]);
$attach="|attached ".$c;
$fstring="with the file(s) ".$_REQUEST['report_'.$c];
}
}

if($_REQUEST['attachSaved']=="on"){
foreach(range(1,100) as $c){
if(!empty($_REQUEST['saved_'.$c])){
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['savedSource_'.$c].'/'.$_REQUEST['saved_'.$c]);
$attach="|attached ".$c;
$fstring="with the file(s) ".$_REQUEST['saved_'.$c];
}
}
}

//$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_1'].'/report_cover.pdf');

foreach(range(1,50) as $c){
if(!empty($_REQUEST['wsreport_'.$c])){
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['wssource_'.$c].'/'.$_REQUEST['wsreport_'.$c]);
$attach="|attached 1";
$fstring="with the file(s) ".$_REQUEST['wsreport_'.$c];
}
}


if(!empty($_FILES['attachment_1']['name'])){
$file1=storeImages('attachment_1');
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/storage/'.$file1);
$attach.="|attached 4"; $fstring.=",".$file1;
}

if(!empty($_FILES['attachment_additional']['name'])){
$file4=storeImages('attachment_additional');
$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 = 'Report Delivery';
$subject = $_REQUEST['subject'];
$sent_at = date('Y-m-d H:i:s');
$reference = 'delivery';
$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]);
}


if(!empty($_REQUEST['hse'])){
$dfl=explode("|",$_REQUEST['defectListItems']);
$header=file_get_contents('../includes/email/email_template.php');
$header=str_replace('[MESSAGE]',"Please find attached the details of the defects at<br>".getClientName($_REQUEST['company'])."<br>".getClientAddress($_REQUEST['company']),$header);
$header=str_replace('[LOGO]',getCompanyDetails('web').'/images/company/logo.jpg?'.rand(),$header);
$header=str_replace('[ENREP]',getCompanyDetails('web').'/images/logo_border.png?'.rand(),$header);
$header=str_replace('[ADDRESS]',getCompanyDetails('address'),$header);
$header=str_replace('[CONTACT]',getCompanyDetails('contact'),$header);
$header=str_replace('[SUBJECT]','Defect Notification',$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'));

$mail->addAddress($_REQUEST['hse']);$rstring="Sent Email to HSE (".$_REQUEST['hse'].")";
$mail->addAttachment('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['source_1'].'/'.$dfl[1]);
$attach="|attached 1";
$fstring="with the file(s) ".$_REQUEST['report_1'];

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

$mail->isHTML(true);
$mail->Subject = "Defect Notification";
$mail->Body = $header;
$mail->AltBody = "Please find attached the details of the defects at ".$_REQUEST['company'];

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


}

if($_REQUEST['attachSaved']=="on"){
$check=mysqli_query($GLOBALS['con'],"SELECT * FROM `delivery_save` WHERE `cid`='".$_REQUEST['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));
$n=mysqli_num_rows($check);
if($n==0){}
else{
while($reps=mysqli_fetch_array($check)){
$items=explode("|",$reps['reps']);
$now=strtotime('now');
foreach($items as $item){
$item=explode("-",$item);
$stmt = $GLOBALS['con']->prepare("UPDATE `reportitems` SET `delivery`='".$now."' WHERE `repnumber`='".$item[0]."' ")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();
}

}

}
$check=mysqli_query($GLOBALS['con'],"DELETE FROM `delivery_save` WHERE `cid`='".$_REQUEST['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));

foreach(range(1,100) as $c){
    if(!empty($_REQUEST['saved_'.$c])){
    unlink('../../'.$_REQUEST['tenant'].'/'.$_REQUEST['savedSource_'.$c].'/'.$_REQUEST['saved_'.$c]);

    }
    }
}