<?php
	namespace Main\Services;
	
	use Main\Libs\Payment\Order;
	use PHPMailer\PHPMailer\Exception;
	use PHPMailer\PHPMailer\PHPMailer;
	
	class EmailService
	{
		/**
		 * @throws Exception
		 */
		public static function send($to, $title, $content)
		{
			$mail = new PHPMailer(true);
			$mail->IsSMTP();
			$mail->SMTPAuth = true;
			$mail->Host = settings('smtpServer');
			$mail->Port = settings('smtpPort');
			$mail->SMTPSecure = ((settings('smtpSecure') == 1) ? PHPMailer::ENCRYPTION_SMTPS : ((settings('smtpSecure') == 2) ? PHPMailer::ENCRYPTION_STARTTLS : PHPMailer::ENCRYPTION_SMTPS));
			$mail->Username = settings('smtpUsername');
			$mail->Password = settings('smtpPassword');
			$mail->SetFrom(settings('smtpSenderEmail'), settings('serverName'));
			$mail->AddAddress($to);
			$mail->isHTML(true);
			$mail->CharSet = 'UTF-8';
			$mail->Subject = $title;
			$mail->Body = $content;
			$mail->send();
		}
		
		public static function processPurchaseEmailContent($username, Order $order)
		{
			$itemsHtml = "";
			$loopPattern = '/<tbody[^>]*data-loop="products"[^>]*>(.*?)<\/tbody>/is';
			$loopItem = "";
			if (preg_match($loopPattern, modules('store')->settings('purchaseEmailTemplate'), $matches)) {
				$loopItem = $matches[1];
			}
			foreach ($order->products as $item) {
				$loopItemClone = $loopItem;
				$loopItemClone = str_replace(
					[
						"%product.name%",
						"%product.quantity%",
						"%product.total%"
					],
					[
						$item->name,
						$item->quantity,
						money()->format($item->total, false)
					],
					$loopItemClone
				);
				$itemsHtml .= $loopItemClone;
			}
			$search = array("%username%", "%url%", "%total%", "%subtotal%", "%discount%", $loopItem);
			$replace = array($username, website_url(url('orders.show', ['id' => $order->id])), money()->format($order->total, false), money()->format($order->subtotal, false), money()->format($order->discount, false), $itemsHtml);
			return str_replace($search, $replace, modules('store')->settings('purchaseEmailTemplate'));
		}
	}