<?php
	require __DIR__.'/../vendor/autoload.php';

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

	function sendFormattedEmail($recipient_email, $recipient_name, $subject, $content, $attachment_path = null) {
		$mail = new PHPMailer(true);

		try {
			$mail->isSMTP();

			$mail->Host = 'localhost';
			$mail->SMTPAuth = false;
			$mail->Port = 25;

			$mail->CharSet = 'UTF-8';
			$mail->setLanguage('hu');

			$mail->XMailer = false;
			unset($mail->Headers['X-Mailer']);
			$mail->Mailer = 'smtp';

			$mail->setFrom('szaturnusz@szatuna.hu', 'Szatuna Kft');
			$mail->addReplyTo('kapcsolat@szatuna.hu', 'Szatuna Kft');


			$templatePath = __DIR__ . '/template/mail.html';
	    if (!file_exists($templatePath)) {
	        return ['success'=>false,'message'=>'Sablon nem található: '.$templatePath];
	    }
	    $html_template = file_get_contents($templatePath);
			$html_body = str_replace('{{SUBJECT}}', $subject, $html_template);

			$localIP = trim(shell_exec('hostname -I | cut -d" " -f1'));
			if ($localIP == '192.168.15.10') {
				$recipient_list = explode(",", $recipient_email);
				for ($i=0; $i < count($recipient_list); $i++) {
					$mail->addBCC(trim($recipient_list[$i]), $recipient_name);
				}

				$html_body = str_replace('{{CONTENT}}', $content, $html_body);
			} else {
				$content .= '<br clear="all"><br><br><p style="color: green;">TEST ENVIROMENT!<br> - Recipient email: '.$recipient_email.'<br> - Recipient name: '.$recipient_name.'</p>';
				$html_body = str_replace('{{CONTENT}}', $content, $html_body);
				$mail->addAddress("sperg.tamas@gmail.com", "Sperg Tamás");
			}

			$mail->isHTML(true);
			$mail->Subject = $subject;

			$imgPath = __DIR__ . '/../img/szatunalogo.png';
			$mail->addEmbeddedImage($imgPath, 'logo_cid', 'szatunalogo.png');

			$mail->Body = $html_body;
			$mail->AltBody = strip_tags($content);

			if ($attachment_path) {
				if (is_array($attachment_path)) {
					foreach ($attachment_path as $file) {
						if (file_exists($file)) {
							$mail->addAttachment($file);
						}
					}
				} elseif (is_string($attachment_path) && file_exists($attachment_path)) {
					$mail->addAttachment($attachment_path);
				}
			}

			$mail->send();
			return ['success' => true, 'message' => 'Levél elküldve.'];
		} catch (Exception $e) {
			return ['success' => false, 'message' => "Nem sikerült elküldeni a levelet. Hiba: {$mail->ErrorInfo}"];
		}
	}

?>
