<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
ignore_user_abort();
class SendMail
{

	public function __construct()
	{
		$this->includes();
	}

	private function includes()
	{
		// Get path
		$phpver = (float) phpversion();
		if ($phpver >= 7.0) {
			$prev_path = dirname(__DIR__, 1);
		}

		require_once($prev_path . '/lib/phpmailer/Exception.php');
		require_once($prev_path . '/lib/phpmailer/PHPMailer.php');
		require_once($prev_path . '/lib/phpmailer/SMTP.php');
	}

	public function scan_done()
	{
		global $db, $log, $filename, $user_id, $count_valid, $count_invalid, $count_catchall, $count_unknown, $count_skipped, $count_syntax_error, $count_disposable, $count_free_account, $count_role_account, $total_email, $scan_time, $site_title, $site_logo, $a_url, $s_url, $sys_smtp, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass, $system_email, $check_mailbox;

		$get_emails_q = 'SELECT `mail_box` FROM evp_email_list WHERE email_status <> "Not Verify" AND csv_file_name = "' . $filename . '" AND user_id = "' . $user_id . '" AND mail_box = "retry"';
		$get_emails_r = $db->select($get_emails_q);
		$result = mysqli_num_rows($get_emails_r);
		$log->system_debug('Total Dummy Email IN QUEUE: ' . $result);
		if (!($result > 0)) {
			$scan_status_q = 'SELECT `scan_status` FROM evp_email_list_metadata WHERE csv_file_name = "' . $filename . '" AND user_id = "' . $user_id . '" AND scan_status = "processing"';
			$scan_status_r = $db->select($scan_status_q);
			$scan_status_c = mysqli_num_rows($scan_status_r);
			if ($scan_status_c > 0) {
				//	$scan_status_r->free();
				$complete_date = date('Y-m-d H:i:s');
				$pid = NULL;
				$csv_file_info = $db->update("UPDATE evp_email_list_metadata SET completed_date = '$complete_date', pid = NULL, scan_status = 'completed' WHERE csv_file_name = '$filename' AND user_id = '$user_id' AND scan_status = 'processing'");
				if ($csv_file_info === true) {
					//	$csv_file_info->free();
					$task_check_q = 'SELECT * FROM evp_task WHERE status != "hold" AND csv_name = "' . $filename . '" AND user_id = "' . $user_id . '"';
					$task_check_r = $db->select($task_check_q);
					$task_check_c = mysqli_num_rows($task_check_r);
					if ($task_check_c > 0) {
						//	$task_check_r->free();
						$task_delete = "DELETE FROM `evp_task` WHERE `csv_name` = '$filename' AND `user_id` = '$user_id' AND `status` != 'hold'";
						if ($db->delete($task_delete) === true) {
							// get evp options	
							$evp_options_sql = "SELECT option_name, option_value FROM evp_options";
							$evp_options_read = $db->select($evp_options_sql);
							if ($evp_options_read) {
								$evp_options_check = mysqli_num_rows($evp_options_read);
								if ($evp_options_check > 0) {
									while ($row = $evp_options_read->fetch_assoc()) {
										$option_name[$row['option_name']] = $row['option_value'];
									}
									$evp_options_read->free();
									$user_name = $option_name['fname'];
									$user_email = $option_name['email'];
								}

								$link = $a_url . "/my_list.php";

								$phpver = (float) phpversion();
								if ($phpver >= 7.0) {
									$prev_path = dirname(__DIR__, 1);
								}

								$msg_var = array();
								$msg_var['csv_name'] = $filename;
								$msg_var['user_name'] = $user_name;
								$msg_var['valid'] = $count_valid;
								$msg_var['invalid'] = $count_invalid;
								$msg_var['catch_all'] = $count_catchall;
								$msg_var['unknown'] = $count_unknown;
								$msg_var['skipped'] = $count_skipped;
								$msg_var['syntax_error'] = $count_syntax_error;
								$msg_var['disposable'] = $count_disposable;
								$msg_var['free_account'] = $count_free_account;
								$msg_var['role_account'] = $count_role_account;
								$msg_var['total_emails'] = $total_email;
								$msg_var['complete_date'] = $complete_date;
								$msg_var['scan_time'] = $scan_time;
								if (!empty($site_logo)) {
									$msg_var['sitelogo'] = '<img src="' . $s_url . '/assets/app-img/' . $site_logo . '" style="border:none;-ms-interpolation-mode:bicubic;max-width:100%;text-align:center;margin:0 auto;display:block;">';
								} else {
									$msg_var['sitelogo'] = $site_title;
								}
								$msg_var['sitetitle'] = $site_title;
								$msg_var['link'] = $link;

								$msg_template = file_get_contents("$prev_path/templates/emails/scan_complete.html");

								foreach ($msg_var as $key => $value) {
									$msg_template = str_replace('{' . $key . '}', $value, $msg_template);
								}
							}


							$mail = new PHPMailer();

							if ($sys_smtp == 'false') {
								$mail->IsMail();
							} else {
								$mail->isSMTP();
							}

							if ($smtp_debug == 'true') {
								$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
								$mail->Debugoutput = function ($str, $level) {
									global $log;
									$log->smtp_debug("\t$level\t$str\n");
								};
							}

							if ($smtp_ssl_verify == 'false') {
								$mail->SMTPOptions = array(
									'ssl' => array(
										'verify_peer' => false,
										'verify_peer_name' => false,
										'allow_self_signed' => true
									)
								);
							}

							$mail->Host = $smtp_host;
							$mail->Port = $smtp_port; // TLS only
							$mail->SMTPSecure = $smtp_security; // ssl is depracated
							$mail->SMTPAuth = $smtp_auth;
							$mail->Username = $smtp_user;
							$mail->Password = $smtp_pass;

							$emailFrom = $system_email;
							$emailFromName = $site_title;
							$emailToName = $user_name;
							$emailTo = $user_email;
							$mail->SetFrom($emailFrom, $emailFromName);
							$mail->AddAddress($emailTo, $emailToName);
							$mail->AddReplyTo($emailFrom, $emailFromName);
							#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

							$mail->IsHTML(true);
							$mail->Subject = "$site_title - Bulk Email Verification Completed";
							$mail->MsgHTML($msg_template);

							if (!$mail->Send()) {
								$log->system_debug('Mail Error: -> ' . $emailTo . ' ' . $mail->ErrorInfo);
								//Reset the connection to abort sending this message
								//The loop will continue trying to send to the rest of the list
								$mail->getSMTPInstance()->reset();
								$log->system_debug('Complete -> EMAIL FAILED TO SENT: ' . $filename);
								//	return false;
							} else {
								$log->system_debug('Scan Complete Email (c_mailsend): ' . $filename);
								//	return true;
							}
							$mail->clearAddresses();
							$mail->clearAttachments();
							$mail->SmtpClose();
							$log->system_debug('SMTP CONNECTION CLOSE!');
						} else {
							exit();
						}
					} else {
						exit();
					}
				}
			}
		}
		$get_emails_r->free();
	}
	public function verify_mailbox($check_mailbox)
	{

		if ($check_mailbox == 'true') {
			global $db, $filename, $user_id, $check_mailbox, $scan_status, $site_title, $log, $smtp_debug, $a_url, $s_url, $ic_send_mail, $ic_smtp, $ic_smtp_host, $ic_smtp_port, $ic_smtp_security, $ic_smtp_auth, $ic_smtp_user, $ic_smtp_pass, $ic_smtp_ssl_verify;

			$task_check_q = 'SELECT * FROM evp_task WHERE status IN ("retry_emailsend","scanning") AND csv_name = "' . $filename . '" AND user_id = "' . $user_id . '"';
			$task_check_r = $db->select($task_check_q);
			$task_check_c = mysqli_num_rows($task_check_r);

			$log->system_debug('Task Found: ' . $filename);

			if ($task_check_c > 0) {
				$task_update_q = 'UPDATE evp_task SET status = "email_send" WHERE status IN ("retry_emailsend","scanning") AND csv_name = "' . $filename . '" AND user_id = "' . $user_id . '"';
				if ($db->update($task_update_q) === true) {
					$log->system_debug('Updating EVP_TASK: ' . $filename);
					$task_check_q = 'SELECT * FROM evp_task WHERE csv_name = "' . $filename . '" AND user_id = "' . $user_id . '" AND status = "email_send"';
					$task_check_r = $db->select($task_check_q);
					$task_check_c = mysqli_num_rows($task_check_r);
					if ($task_check_c > 0) {
						$get_emails_q = 'SELECT `email_name`, `last_update`, `mail_box` FROM evp_email_list WHERE mail_box IN ("pending","retry") AND email_status <> "Not Verify" AND csv_file_name = "' . $filename . '" AND user_id = "' . $user_id . '"';
						$get_emails_r = $db->select($get_emails_q);
						$result = mysqli_num_rows($get_emails_r);
						$log->system_debug('Total Emails Found: ' . $result);
						if ($result > 0) {
							// fetch dummy msg data
							$dummy_emails_q = "SELECT * FROM evp_dummy_emails";
							$result = $db->select($dummy_emails_q);
							$rows = [];
							while ($row = $result->fetch_assoc()) {
								$rows[] = $row;
							}

							// smtp connection data
							$log->system_debug('SMTP CONNECTION OPEN FOR BULK SEND!');
							$mail = new PHPMailer();

							if ($ic_smtp == 'false') {
								$mail->IsMail();
							} else {
								$mail->isSMTP();
								$mail->SMTPKeepAlive = true;
							}

							if ($smtp_debug == 'true') {
								$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
								$mail->Debugoutput = function ($str, $level) {
									global $log;
									$log->smtp_debug("\t$level\t$str\n");
								};
							}

							if ($ic_smtp_ssl_verify == 'false') {
								$mail->SMTPOptions = array(
									'ssl' => array(
										'verify_peer' => false,
										'verify_peer_name' => false,
										'allow_self_signed' => true
									)
								);
							}

							// $msg_template = file_get_contents("../lib/emails/dummy.html");


							$emailFrom = $ic_send_mail;
							$emailFromName = $site_title;

							$mail->Host = $ic_smtp_host;
							$mail->Port = $ic_smtp_port; // TLS only
							$mail->SMTPSecure = $ic_smtp_security; // ssl is depracated

							$mail->SMTPAuth = $ic_smtp_auth;
							$mail->Username = $ic_smtp_user;
							$mail->Password = $ic_smtp_pass;

							$mail->IsHTML(true);



							$mail->SetFrom($emailFrom);
							$mail->addReplyTo($emailFrom);

							foreach ($get_emails_r as $row) {
								//$today_date = date("l jS \of F Y h:i:s A");
								$dateTime = date('Y-m-d H:i:s');
								$dummy = array_rand($rows);
								$sub = $rows[$dummy]['sub'];
								$msg = $rows[$dummy]['msg'];

								$delay_send = $row['mail_box'];
								if ($delay_send == 'retry') {
									$last_update = $row['last_update'];
									$time_now = time();
									$delay_time = strtotime($last_update) + 1800; // Try email queue after 30mins.
									if (!($time_now > ($delay_time))) {
										$log->system_debug('Send Mail Delaying: ' . $filename);
										break;
									}
								}
								$mail->Subject = "$sub";
								$mail->MsgHTML($msg);
								$emailTo = $row['email_name'];
								$log->system_debug('SCAN -> Email FOUND: ' . $emailTo);
								$mail->AddAddress($emailTo);
								// if($valid){
								if (!$mail->Send()) {
									$log->system_debug('Mail Error: -> ' . $emailTo . ' ' . $mail->ErrorInfo);
									$smtp_errors = 'Restricted characters in address';
									if (preg_match("/($smtp_errors)/i", $mail->ErrorInfo, $match)) {
										$update_mailbox = "UPDATE evp_email_list SET mail_box = 'none', last_update = '$dateTime' WHERE mail_box IN ('pending','retry') AND csv_file_name = '$filename' AND email_name = '$emailTo' AND user_id = '$user_id'";
									} else {
										$update_mailbox = "UPDATE evp_email_list SET mail_box = 'retry', last_update = '$dateTime' WHERE mail_box IN ('pending','retry') AND csv_file_name = '$filename' AND email_name = '$emailTo' AND user_id = '$user_id'";
									}
									$db->update($update_mailbox);
									$log->system_debug('SCAN -> EMAIL FAILED TO SENT: ' . $emailTo);
									$mail->getSMTPInstance()->reset();
									//	return false;
								} else {
									$update_mailbox = "UPDATE evp_email_list SET mail_box = 'waiting', last_update = '$dateTime' WHERE mail_box IN ('pending','retry') AND csv_file_name = '$filename' AND email_name = '$emailTo' AND user_id = '$user_id'";
									$db->update($update_mailbox);
									$log->system_debug('SCAN -> EMAIL SENT TO: ' . $emailTo);
									//	return true;
								}
								// }
								//Clear all addresses and attachments for the next iteration
								// $mail->ClearAllRecipients();
								$mail->clearAddresses();
								$mail->clearAttachments();
							}
							$get_emails_r = $db->select($get_emails_q);
							$result = mysqli_num_rows($get_emails_r);
							$log->system_debug('ROWS FOUND: ' . $result);
							if ($result > 0) {
								$task_update_q = 'UPDATE evp_task SET status = "retry_emailsend" WHERE csv_name = "' . $filename . '" AND user_id = "' . $user_id . '" AND status = "email_send"';
								$log->system_debug('TASK SET retry_emailsend');
							} else {
								$task_update_q = 'UPDATE evp_task SET status = "hold" WHERE csv_name = "' . $filename . '" AND user_id = "' . $user_id . '" AND status = "email_send"';
								$log->system_debug('TASK SET hold');
							}
							if ($db->update($task_update_q) === true) {
								$mail->SmtpClose();
								$log->system_debug('SMTP CONNECTION CLOSE!');
							}
						}
					}
				}

			}
		}
	}

	public function campaign_email()
	{
		global $db, $log, $a_url, $unsubscribe_link;

		$mail = new PHPMailer();
		$mail->isSMTP();

		// get evp options
		$evp_options_sql = "SELECT option_name, option_value FROM evp_options";
		$evp_options_read = $db->select($evp_options_sql);
		if ($evp_options_read) {
			$evp_options_check = mysqli_num_rows($evp_options_read);
			if ($evp_options_check > 0) {
				while ($row = $evp_options_read->fetch_assoc()) {
					$option_name[$row['option_name']] = $row['option_value'];
				}
				$evp_options_read->free();
				$smtp_status = $option_name['smtp_status'];
				$smtp_debug = $option_name['smtp_debug'];
				$s_path = $option_name['script_path'];
			}
		}

		if ($smtp_debug == 'true') {
			$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
			$mail->Debugoutput = function ($str, $level) {
				global $log;
				$log->smtp_debug("\t$level\t$str\n");
			};
		}

		$get_smtps_read = $db->select("SELECT * FROM evp_smtp_server_list");


		$smtp_datas = [];
		while ($smtp_row = $get_smtps_read->fetch_assoc()) {
			$smtp_datas[] = $smtp_row;
		}

		// $smtp_row -> free_result();

		foreach ($smtp_datas as $smtp_data) {

			$get_emails = $smtp_data['id'];
			$set_limit = $smtp_data['smtp_limit'];

			$emails_data = $db->select("SELECT e_data.*, e_list.* 
											FROM evp_campaign_list e_data
											LEFT JOIN evp_send_email_list e_list
											ON e_list.list_name = e_data.c_name 
											WHERE e_data.c_status = 'processing' and
											e_list.list_name = e_data.c_name and
											e_list.sent = 'false' and
											e_data.s_id = '$get_emails'
											LIMIT $set_limit");


			foreach ($emails_data as $email) {

				//	var_dump($email);
				//	var_dump($smtp_data);

				$smtp_uid = $smtp_data['user_id'];
				$smtp_limit = $smtp_data['smtp_limit'];
				$smtp_email = $smtp_data['smtp_email'];
				$smtp_host = $smtp_data['smtp_host'];
				$smtp_port = $smtp_data['smtp_port'];
				$smtp_ssl_verify = $smtp_data['smtp_ssl_verify'];
				$smtp_security = $smtp_data['smtp_security'];
				$smtp_auth = $smtp_data['smtp_auth'];
				$smtp_user = $smtp_data['smtp_user'];
				$smtp_pass = $smtp_data['smtp_pass'];
				$total_email = $email['total_amount'];
				$sent_email = $email['total_sent'];
				$unsubscribe_link = $email['c_unsub'];
				$status = $email['c_status'];


				if (($total_email != $sent_email) && ($status == 'processing')) {

					if ($smtp_ssl_verify == 'false') {
						$mail->SMTPOptions = array(
							'ssl' => array(
								'verify_peer' => false,
								'verify_peer_name' => false,
								'allow_self_signed' => true
							)
						);
					}

					//		if($smtp_status == 'TRUE'){
					$mail->Host = $smtp_host; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
					$mail->Port = $smtp_port; // TLS only
					$mail->SMTPSecure = $smtp_security; // ssl is depracated
					//	if($smtp_auth == 'true') {
					$mail->SMTPAuth = $smtp_auth;
					$mail->Username = $smtp_user;
					$mail->Password = $smtp_pass;
					//	}
//		}

					$emailFrom = $email['c_from'];
					$emailFromName = $email['c_fname'];
					$emailTo = $email['email_add'];
					$emailToName = $email['full_name'];
					$email_sub = $email['c_sub'];
					$email_body = htmlspecialchars_decode($email['c_msg']);

					if ($unsubscribe_link == 'true') {
						$email_body .= '<p style="font-size:12px;border-top:1px solid #eee;padding-top:10px;">We would be sorry to see you go, but if you want to, <a href="' . $a_url . '/unsubscribe.php?email=' . $emailTo . '&uid=' . $smtp_uid . '" target="_blank">click here to unsubscribe</a>.</p>';
					}

					$mail->setFrom($emailFrom, $emailFromName);
					$mail->addReplyTo($emailFrom, $emailFromName);

					$mail->addAddress($emailTo, $emailToName);

					$mail->IsHTML(true);
					$mail->Subject = $email_sub;
					$mail->msgHTML($email_body);

					$log->system_debug('Campaign Sending To: ' . $emailTo);

					if (!$mail->send()) {
						$mail->getSMTPInstance()->reset();
						mysqli_query($db->link, "UPDATE evp_campaign_list SET c_status = 'pending' WHERE c_user_id = '" . $email['c_user_id'] . "' AND c_name = '" . $email['c_name'] . "' AND c_status = 'processing'");
						//  return false;
						//  echo 'Message could not be sent.';
						//  echo 'Mailer Error: ' . $mail->ErrorInfo;
					} else {
						//Mark it as sent in the DB

						mysqli_query(
							$db->link,
							"UPDATE evp_send_email_list SET sent = 'true' WHERE email_add = '" .
							mysqli_real_escape_string($db->link, $emailTo) . "' AND list_name = '" .
							mysqli_real_escape_string($db->link, $email['c_name']) . "'"
						);
						mysqli_query(
							$db->link,
							"UPDATE evp_campaign_list SET total_sent = total_sent + 1 WHERE c_name = '" .
							mysqli_real_escape_string($db->link, $email['c_name']) . "'"
						);

						//   return true;
					}

					//Clear all addresses and attachments for the next iteration
					$mail->clearAddresses();
					$mail->clearAttachments();


				} else {
					exit();
				}

			}

		}

		$mark_camp_sql = "SELECT DISTINCT e_data.c_name, e_data.c_status, e_data.c_user_id, e_list.list_name FROM evp_campaign_list e_data LEFT JOIN evp_send_email_list e_list ON e_list.list_name = e_data.c_name WHERE e_data.c_status = 'processing' AND e_data.total_sent = e_data.total_amount";

		$mark_camp_read = $db->select($mark_camp_sql);

		if ($mark_camp_read) {
			$mark_camp_check = mysqli_num_rows($mark_camp_read);
			if ($mark_camp_check > 0) {

				$arr_cname[] = array();
				$check_status = '';
				while ($row = $mark_camp_read->fetch_assoc()) {

					$check_status = $row['c_status'];
					$c_user_id = $row['c_user_id'];
					$arr_cname = $row['c_name'];

					if ($check_status == 'processing') {

						mysqli_query($db->link, "UPDATE evp_campaign_list SET c_status = 'complete' WHERE c_user_id = '$c_user_id' AND c_name = '$arr_cname' AND c_status = 'processing'");

						if ($evp_options_read) {
							$evp_options_check = mysqli_num_rows($evp_options_read);
							if ($evp_options_check > 0) {
								while ($row = $evp_options_read->fetch_assoc()) {
									$option_name[$row['option_name']] = $row['option_value'];
								}
								$evp_options_read->free();
								$user_name = $option_name['fname'];
								$user_email = $option_name['email'];
							}
						}

						if ($check_status = 'complete') {
							global $site_title, $a_url, $sys_smtp, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass, $system_email;

							$mail = new PHPMailer();

							if ($sys_smtp == 'false') {
								$mail->IsMail();
							} else {
								$mail->isSMTP();
							}
							if ($smtp_debug == 'true') {
								$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
								$mail->Debugoutput = function ($str, $level) {
									global $log;
									$log->smtp_debug("\t$level\t$str\n");
								};
							}
							if ($smtp_ssl_verify == 'false') {
								$mail->SMTPOptions = array(
									'ssl' => array(
										'verify_peer' => false,
										'verify_peer_name' => false,
										'allow_self_signed' => true
									)
								);
							}

							$mail->Host = $smtp_host;
							$mail->Port = $smtp_port; // TLS only
							$mail->SMTPSecure = $smtp_security; // ssl is depracated
							$mail->SMTPAuth = $smtp_auth;
							$mail->Username = $smtp_user;
							$mail->Password = $smtp_pass;

							$emailFrom = $system_email;
							$emailFromName = $site_title;
							$emailToName = $user_name;
							$emailTo = $user_email;
							$mail->SetFrom($emailFrom, $emailFromName);
							$mail->AddAddress($emailTo, $emailToName);
							$mail->AddReplyTo($emailFrom, $emailFromName);
							#$mail->AddCC("cc-recipient-email", "cc-recipient-name");
							$msg_template = "<p style='font-size:14px;'>Your Mass Email Campaign Of '<span style='color:#11a683;font-weight:bold;'>$arr_cname</span>' has been completed!</p>";
							$mail->IsHTML(true);
							$mail->Subject = "$site_title - Email Campaign '$arr_cname' Completed";
							$mail->MsgHTML($msg_template);

							if (!$mail->send()) {
								return false;
							} else {
								return true;
							}

						}

					}

				}


			}
		}


	}

	public function user_acc_status_updates($user_name, $user_email, $action)
	{
		global $site_title, $site_logo, $a_url, $s_url, $sys_smtp, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass, $system_email;

		$mail = new PHPMailer(true);

		if ($sys_smtp == 'false') {
			$mail->IsMail();
		} else {
			$mail->isSMTP();
		}
		if ($smtp_debug == 'true') {
			$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
			$mail->Debugoutput = function ($str, $level) {
				global $log;
				$log->smtp_debug("\t$level\t$str\n");
				//file_put_contents("../tmp/logs/smtp_debug.log", gmdate('Y-m-d H:i:s'). "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
			};
		}
		if ($smtp_ssl_verify == 'false') {
			$mail->SMTPOptions = array(
				'ssl' => array(
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true
				)
			);
		}

		$mail->Host = $smtp_host;
		$mail->Port = $smtp_port; // TLS only
		$mail->SMTPSecure = $smtp_security; // ssl is depracated
		$mail->SMTPAuth = $smtp_auth;
		$mail->Username = $smtp_user;
		$mail->Password = $smtp_pass;

		$emailFrom = $system_email;
		$emailFromName = $site_title;
		$emailToName = $user_name;
		$emailTo = $user_email;
		$mail->SetFrom($emailFrom, $emailFromName);
		$mail->AddAddress($emailTo, $emailToName);
		$mail->AddReplyTo($emailFrom, $emailFromName);
		#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

		switch ($action) {
			case "verify":
				$action = "Verified";
				$msgbody = "<p>We are happy to let you know that your account have been manually verified in $site_title!</p><p>You may now access to your account and use our services at <a href='$s_url' target='_blank'>$s_url</a></p>";
				break;
			case "reactive":
				$action = "Reactivated";
				$msgbody = "<p>We are happy to let you know that we have reactivated your $site_title account!</p><p>You can continue using our services at <a href='$s_url' target='_blank'>$s_url</a></p>";
				break;
			case "suspend":
				$action = "Suspended";
				$msgbody = "<p>We are sorry to let you know that we have suspended your $site_title account!</p><p>If you think this was a mistake then please contact with us at <a href='$s_url' target='_blank'>$s_url</a></p>";
				break;
			case "deleted":
				$action = "Deleted";
				$msgbody = "<p>We are sorry to let you know that we have removed your $site_title account and its all data!</p><p>If you think this was a mistake then please contact with us at <a href='$s_url' target='_blank'>$s_url</a></p>";
				break;
			case "promoted":
				$action = "Promoted";
				$msgbody = "<p>We wanted to let you know that your user account in $site_title has been promoted to <b>Moderator</b>!</p>";
				break;
			case "demoted":
				$action = "Demoted";
				$msgbody = "<p>We are sorry to let you know that your user account in $site_title has been demoted to <b>User</b>!</p>";
				break;
		}

		$msg_template = "<html><body><div style='width:100%;text-align:center;'><h3>Hi " . ucfirst($user_name) . "</h3>$msgbody</div></body></html>";

		$mail->IsHTML(true);
		// $mail->Subject = ($action == 'suspend' ) ? "$site_title - Account Suspended!" : "$site_title - Account Reactivated!";
		$mail->Subject = "$site_title - Your Account $action!";
		$mail->MsgHTML($msg_template);

		if (!$mail->Send()) {
			return false;
		} else {
			return true;
		}
	}

	public function notify_user_account_updates($user_name, $user_email, $token, $mstatus)
	{
		global $site_title, $site_logo, $a_url, $s_url, $sys_smtp, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass, $system_email;

		$link = $s_url . "/functions/mail-token-verify.php?verify_token=" . $token . "&" . $mstatus . "=" . $user_email;

		//    $link = $s_url . "/functions/" . $mail_token_func . "?verify_token=" . $resettoken . "&" . $action . "=" . $mail;

		$mail = new PHPMailer(true);

		if ($sys_smtp == 'false') {
			$mail->IsMail();
		} else {
			$mail->isSMTP();
		}
		if ($smtp_debug == 'true') {
			$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
			$mail->Debugoutput = function ($str, $level) {
				global $log;
				$log->smtp_debug("\t$level\t$str\n");
				//file_put_contents("../tmp/logs/smtp_debug.log", gmdate('Y-m-d H:i:s'). "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
			};
		}
		if ($smtp_ssl_verify == 'false') {
			$mail->SMTPOptions = array(
				'ssl' => array(
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true
				)
			);
		}

		$mail->Host = $smtp_host;
		$mail->Port = $smtp_port; // TLS only
		$mail->SMTPSecure = $smtp_security; // ssl is depracated
		$mail->SMTPAuth = $smtp_auth;
		$mail->Username = $smtp_user;
		$mail->Password = $smtp_pass;

		$emailFrom = $system_email;
		$emailFromName = $site_title;
		$emailToName = $user_name;
		$emailTo = $user_email;
		$mail->SetFrom($emailFrom, $emailFromName);
		$mail->AddAddress($emailTo, $emailToName);
		$mail->AddReplyTo($emailFrom, $emailFromName);
		#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

		switch ($mstatus) {
			case "new_signup":
				$sub_str = "New Account Confirmation";
				$msgbody = "<p>$site_title - has received user registration request.</p><p>To confirm this registeration, kindly visit this link</p><div style='border-radius: 10px;cursor:pointer;background:#F7C9C9; display:inline-block;padding:10px;'>" . $link . "</div>";
				break;
			case "email_update":
				$sub_str = "Account Email Change Request";
				$msgbody = "<p>We have received a user email change request to this email address.</p><p>Please, verify your new email address change request by clicking following link</p><div style='border-radius: 10px;cursor:pointer;background:#F7C9C9; display:inline-block;padding:10px;'>" . $link . "</div><p><small>If you think this is a mistake then kindly disregard this email request and inform <strong>$site_title - <a href='$s_url' target='_blank'>$s_url</a></strong> immediately!</small></p>";
				break;
			case "password_reset":
				$link = $a_url . "/forgot-password.php?resettoken=" . $token . "&email=" . $user_email;
				$sub_str = "Account Password Reset Request";
				$msgbody = "<h3>Hi " . $user_name . "</h3><p>$site_title - has received password reset request for this email.</p><p>If you did not request to reset your password, please ignore this email.</p><div style='border-radius: 10px;cursor:pointer;background:#F7C9C9; display:inline-block;padding:10px;'>" . $link . "</div>";
				break;
		}

		$msg_template = "<html><body><div style='width:100%;text-align:center;'>$msgbody</div></body></html>";

		$mail->IsHTML(true);
		$mail->Subject = "$site_title - $sub_str";
		$mail->MsgHTML($msg_template);

		if (!$mail->Send()) {
			return false;
		} else {
			return true;
		}
	}

	public function notify_admin_new_signup($user_name, $user_email, $mstatus)
	{

		global $site_title, $site_logo, $user_ip, $a_url, $s_url, $sys_smtp, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass, $system_email;

		$mail = new PHPMailer(true);

		if ($sys_smtp == 'false') {
			$mail->IsMail();
		} else {
			$mail->isSMTP();
		}
		if ($smtp_debug == 'true') {
			$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
			$mail->Debugoutput = function ($str, $level) {
				global $log;
				$log->smtp_debug("\t$level\t$str\n");
				//file_put_contents("../tmp/logs/smtp_debug.log", gmdate('Y-m-d H:i:s'). "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
			};
		}
		if ($smtp_ssl_verify == 'false') {
			$mail->SMTPOptions = array(
				'ssl' => array(
					'verify_peer' => false,
					'verify_peer_name' => false,
					'allow_self_signed' => true
				)
			);
		}

		$link = $s_url . "/members/user-management.php/";

		$mail->Host = $smtp_host;
		$mail->Port = $smtp_port; // TLS only
		$mail->SMTPSecure = $smtp_security; // ssl is depracated
		$mail->SMTPAuth = $smtp_auth;
		$mail->Username = $smtp_user;
		$mail->Password = $smtp_pass;

		$emailFrom = $system_email;
		$emailFromName = $site_title;
		$emailToName = $user_name;
		$emailTo = $user_email;
		$mail->SetFrom($emailFrom, $emailFromName);
		$mail->AddAddress($emailFrom, $emailFromName);
		$mail->AddReplyTo($emailTo, $emailToName);
		#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

		$msg_template = "<html><body><div style='width:100%;text-align:center;'><p>$site_title - has received a new user registration.</p><p> User details: <br> Name: $user_name <br> Email: $user_email <br> IP: $user_ip </p><div style='border-radius: 10px;cursor:pointer;background:#F7C9C9; display:inline-block;padding:10px;'>" . $link . "</div></div></body></html>";

		$mail->IsHTML(true);
		$mail->Subject = "$site_title - New User Registration";
		$mail->MsgHTML($msg_template);

		if (!$mail->Send()) {
			return false;
		} else {
			return true;
		}

	}

	public function user_csv_import_notify($user_id, $csv_name, $save, $duplicate, $skipped)
	{
		global $db, $log, $site_title, $site_logo, $a_url, $s_url, $sys_smtp, $system_email, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass;

		// Retrieve user email

		// Retrieve user email from evp_options
		$user_email = '';
		$admin_email_query = "SELECT option_value FROM evp_options WHERE option_name = 'email'";
		$admin_email_result = $db->select($admin_email_query);
		if ($admin_email_result && $admin_email_result->num_rows > 0) {
			$user_email = $admin_email_result->fetch_assoc()['option_value'];
		}

		if (!empty($user_email)) {
			$subject = "CSV Import Completed";
			$message = "<p>Your CSV file '$csv_name' has been successfully imported. You can login to your account now to start verifying this list.</p>";
			$message .= "<p>Total stored emails: $save</p>";
			$message .= "<p>Total duplicate emails removed: $duplicate</p>";
			$message .= "<p>Total bad format emails ignored: $skipped</p>";

			$mail = new PHPMailer(true);
			try {
				//Server settings
				if ($sys_smtp == 'false') {
					$mail->IsMail();
				} else {
					$mail->isSMTP();
				}
				if ($smtp_debug == 'true') {
					$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
					$mail->Debugoutput = function ($str, $level) {
						global $log;
						$log->smtp_debug("\t$level\t$str\n");
					};
				}
				if ($smtp_ssl_verify == 'false') {
					$mail->SMTPOptions = array(
						'ssl' => array(
							'verify_peer' => false,
							'verify_peer_name' => false,
							'allow_self_signed' => true
						)
					);
				}
				$mail->Host = $smtp_host;
				$mail->SMTPAuth = $smtp_auth;
				$mail->Username = $smtp_user;
				$mail->Password = $smtp_pass;
				$mail->SMTPSecure = $smtp_security;
				$mail->Port = $smtp_port;

				$emailFrom = $system_email;
				$emailFromName = $site_title;
				$emailToName = $user_email;
				$emailTo = $user_email;
				$mail->SetFrom($emailFrom, $emailFromName);
				$mail->AddAddress($emailTo, $emailToName);
				$mail->AddReplyTo($emailFrom, $emailFromName);
				#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

				$mail->IsHTML(true);
				$mail->Subject = $subject;
				$mail->MsgHTML($message);

				$mail->send();
				$log->system_debug('Email sent successfully to: ' . $emailTo);
			} catch (Exception $e) {
				$log->system_debug('Mail Error: ' . $mail->ErrorInfo);
				if (strpos($mail->ErrorInfo, 'Invalid hostentry') !== false) {
					$log->system_debug('Invalid host entry detected. Please check your SMTP host configuration.');
				}
				$log->system_debug('SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting');
			}
		} else {
			$log->system_debug("Failed to retrieve user email for user ID: $user_id");
		}
	}

	/**
	 * Send an email notification
	 *
	 * @param string $to
	 * @param string $subject
	 * @param string $message
	 * @return bool
	 */
	public function sendMail($user_email, $subject, $message)
	{
		global $db, $log, $site_title, $site_logo, $a_url, $s_url, $sys_smtp, $system_email, $smtp_debug, $smtp_ssl_verify, $smtp_host, $smtp_port, $smtp_security, $smtp_auth, $smtp_user, $smtp_pass;

		$mail = new PHPMailer(true);

		try {
			//Server settings
			if ($sys_smtp == 'false') {
				$mail->IsMail();
			} else {
				$mail->isSMTP();
			}
			if ($smtp_debug == 'true') {
				$mail->SMTPDebug = 3; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
				$mail->Debugoutput = function ($str, $level) {
					global $log;
					$log->smtp_debug("\t$level\t$str\n");
				};
			}
			if ($smtp_ssl_verify == 'false') {
				$mail->SMTPOptions = array(
					'ssl' => array(
						'verify_peer' => false,
						'verify_peer_name' => false,
						'allow_self_signed' => true
					)
				);
			}
			$mail->Host = $smtp_host;
			$mail->SMTPAuth = $smtp_auth;
			$mail->Username = $smtp_user;
			$mail->Password = $smtp_pass;
			$mail->SMTPSecure = $smtp_security;
			$mail->Port = $smtp_port;

			$emailFrom = $system_email;
			$emailFromName = $site_title;
			$user_name = 'noname';
			$emailToName = $user_name;
			$emailTo = $user_email;
			$mail->SetFrom($emailFrom, $emailFromName);
			$mail->AddAddress($emailTo, $emailToName);
			$mail->AddReplyTo($emailFrom, $emailFromName);
			#$mail->AddCC("cc-recipient-email", "cc-recipient-name");

			$mail->IsHTML(true);
			$mail->Subject = $subject;
			$mail->MsgHTML($message);

			$mail->send();
			$log->smtp_debug('Email sent successfully to: ' . $emailTo);
			return true;
		} catch (Exception $e) {
			$log->smtp_debug('Mail Error: ' . $mail->ErrorInfo);
			if (strpos($mail->ErrorInfo, 'Invalid hostentry') !== false) {
				$log->smtp_debug('Invalid host entry detected. Please check your SMTP host configuration.');
			}
			$log->smtp_debug('SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting');
			return false;
		}
	}
}
?>