<?php
/*
    *****************************************************************************
    * MEGA Digital Space - by MEGA Digital Studio                               *
    * ------------------------------------------------------------------------- *
    * CMS Website:  https://megadigital.space                                   *
    * License:  https://megadigital.space/license                               *
    * Owner:  Giorgi Basharuli                                                  *
    * Contact:  online@megadigital.studio                                       *
    * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
    * Website:  https://megadigital.studio                                      *
    * ------------------------------------------------------------------------- *
    * Description: This file is a part of the MEGA Digital Space CMS system.    *
    * Unauthorized distribution, modification, or commercial use is strictly -  *
    * prohibited without prior written permission.                              *
    * ------------------------------------------------------------------------- *
    * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
    * All rights reserved.                                                      *
    *****************************************************************************
*/

require 'vendor/autoload.php';

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

function sendEmail($toEmail, $emailTemplateCategory, $subject, $templateData = [], $activeTemplate = false)
{
    global $config, $smarty, $db_connect;

    $html = "";
    $isAuto = false;
    if (!$activeTemplate) {
        foreach ($config["email_template_settings"][$emailTemplateCategory] as $templateName => $statusTemplate) {
            if ($statusTemplate === true) {
                $activeTemplate = $templateName;
                $isAuto = true;
            }
        }
    }

    if(!empty($_SESSION["user_id"])) {
        $user = $db_connect->get("users", "*", ["id" => $_SESSION["user_id"]]);
    }

    if (!empty($config["email_template_settings"][$emailTemplateCategory]) && $isAuto) {
        if ($config["email_template_settings"][$emailTemplateCategory][$activeTemplate] === true) {
            $smarty->assign("receiverName", $user["name"]);
            $smarty->assign("senderName", "Mega Digital Studio");
            $smarty->assign("user", $user);

            if (!empty($templateData)) {
                foreach ($templateData as $key => $value) {
                    $smarty->assign($key, $value);
                }
            }

            $paymentData = $db_connect->get("transactions", "*", ["transaction_id" => $_GET["session_id"]]);
            $smarty->assign("paymentSum", convertAmount($paymentData["sum"], $paymentData["currency"], getCurrentCurrency())." ". getCurrentCurrency());
            $html = $smarty->fetch("email/$activeTemplate/main.tpl");
        }
    } else if (!$isAuto) {
        if (!empty($templateData)) {
            foreach ($templateData as $key => $value) {
                $smarty->assign($key, $value);
            }
        }

        if (!empty($_GET["session_id"])) {
            $paymentData = $db_connect->get("transactions", "*", ["transaction_id" => $_GET["session_id"]]);
            $smarty->assign("paymentSum", convertAmount($paymentData["sum"], $paymentData["currency"], getCurrentCurrency())." ". getCurrentCurrency());
        }

        $html = $smarty->fetch("email/$activeTemplate/main.tpl");
    }

    try {
        $mail = new PHPMailer(true);

        // Настройки сервера
        $mail->isSMTP();                                            // Использовать SMTP
        $mail->Host       = $config["email_settings"]["host"];                     // Укажите ваш SMTP сервер
        $mail->SMTPAuth   = $config["email_settings"]["smtp_auth"];                                   // Включить аутентификацию SMTP
        $mail->Username   = $config["email_settings"]["username"];                     // SMTP username
        $mail->Password   = $config["email_settings"]["password"];                               // SMTP password
        $mail->SMTPSecure = $config["email_settings"]["smtp_secure"];         // Включить шифрование TLS
        $mail->Port       = $config["email_settings"]["port"];                                    // TCP port для подключения

        // Отправитель и получатель
        $mail->setFrom($config["email_settings"]["username"], 'Mega Digital Studio');
        $mail->addAddress($toEmail, $toEmail);            // Добавить получателя
        //  $mail->addReplyTo('info@example.com', 'Information');       // Укажите адрес для ответа

        // Вложения
        // $mail->addAttachment('/var/tmp/file.tar.gz');            // Добавить вложение
        // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');       // Опционально: изменить имя файла

        // Содержимое письма
        $mail->isHTML(true);                                        // Установить формат письма в HTML
        $mail->Subject = $subject;
        $mail->Body    = $html;
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
        return true;
    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
