<?php

include 'mailer/vendor/autoload.php';

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

require_once "mailer/PHPMailer.php";
require_once "mailer/SMTP.php";
require_once "mailer/Exception.php";


 function sendMail($email, $subject, $message){
    global $con;

    $smtpHost = "";
    $smtpUser = "";
    $smtpPass = "";
    $smtpPort = 465;
    $smtpEncryption = "ssl";
    $fromEmail = "";
    $fromName = "bluecrest";

    if (isset($con) && $con instanceof mysqli) {
        $colCheck = $con->query("SHOW COLUMNS FROM system_settings LIKE 'smtp_host'");
        if ($colCheck && $colCheck->num_rows > 0) {
            $smtpQuery = $con->query("SELECT smtp_host, smtp_port, smtp_username, smtp_password, smtp_encryption, smtp_from_email, smtp_from_name, bank_name, email FROM system_settings LIMIT 1");
            if ($smtpQuery && $smtpQuery->num_rows > 0) {
                $smtp = $smtpQuery->fetch_assoc();
                $smtpHost = !empty($smtp['smtp_host']) ? $smtp['smtp_host'] : $smtpHost;
                $smtpPort = !empty($smtp['smtp_port']) ? (int) $smtp['smtp_port'] : $smtpPort;
                $smtpUser = !empty($smtp['smtp_username']) ? $smtp['smtp_username'] : $smtpUser;
                $smtpPass = !empty($smtp['smtp_password']) ? $smtp['smtp_password'] : $smtpPass;
                $smtpEncryption = !empty($smtp['smtp_encryption']) ? strtolower($smtp['smtp_encryption']) : $smtpEncryption;
                $fromEmail = !empty($smtp['smtp_from_email']) ? $smtp['smtp_from_email'] : (!empty($smtp['email']) ? $smtp['email'] : $fromEmail);
                $fromName = !empty($smtp['smtp_from_name']) ? $smtp['smtp_from_name'] : (!empty($smtp['bank_name']) ? $smtp['bank_name'] : $fromName);
            }
        }
        if ($colCheck) {
            $colCheck->free();
        }
    }

    if (!in_array($smtpEncryption, ["ssl", "tls", "none"], true)) {
        $smtpEncryption = "ssl";
    }
    if ($smtpHost === "" || $smtpUser === "" || $smtpPass === "" || $fromEmail === "") {
        return false;
    }

    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUser;
        $mail->Password = $smtpPass;
        $mail->Port = $smtpPort > 0 ? $smtpPort : 465;
        if ($smtpEncryption === "none") {
            $mail->SMTPSecure = false;
            $mail->SMTPAutoTLS = false;
        } else {
            $mail->SMTPSecure = $smtpEncryption;
        }

        $mail->isHTML(true);
        $mail->setFrom($fromEmail, $fromName);
        $mail->addAddress($email);
        $mail->addReplyTo($fromEmail, $fromName);
        $mail->Subject = $subject;
        $mail->MsgHTML($message);
        return $mail->send();
    } catch (Exception $e) {
        return false;
    }
}



?>