<?php

// ===========
// Email Class
// ===========

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

class Email extends Base {

    // Variables.

    private $current_user_name = "";
    private $current_user_email = "";

    // ==================
    // Class Constructor.
    // ==================

    public function __construct() {

        set_error_handler(array($this, "displayError"));

        date_default_timezone_set(self::TIMEZONE);

        $this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
        $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
    }

    // =============================
    // Email a new users credentials
    // =============================

    public function emailNewUserCredentials($user, $password) {

        if (!$user instanceof SimpleXMLElement) {
            return;
        }

        // Prepare the email

        $to = (string) $user->record->user_email;

        $XSLParms['USER-TEMP-PASSWORD'] = $password;

        $subject = "New User Credentials";
        $message = $this->applyXSL($user, $this->getXSL("emailNewUserCredentials"), $XSLParms);

        // Send the Email
        $this->sendEmail($to, $subject, $message);
    }

    // =================================
    // Email a users Password Reset Link
    // =================================

    public function emailUserPasswordResetLink($user, $password) {

        if (!$user instanceof SimpleXMLElement) {
            return;
        }

        // Prepare the email.

        $XSLParms['USER-TEMP-PASSWORD'] = $password;

        $to = (string) $user->record->user_email;
        $subject = "Password Reset Request";
        $message = $this->applyXSL($user, $this->getXSL("emailPasswordResetLink"), $XSLParms);

        // Send the Email
        $this->sendEmail($to, $subject, $message);
    }

    // =======================================
    // Send an email with optional attachments
    // =======================================

    public function sendEmail($to = "", $subject = "", $message = "", $attachments = "", $attachment_names = "unknown") {

        if (empty($to) or empty($subject) or empty($message)) {

            return false;
        }

        $settings = $this->getSettings();

        $SmtpHost = $settings->SmtpServer;
        $SmtpUsername = $settings->SmtpUserName;
        $SmtpPassword = $settings->SmtpPassword;
        $SmtpPort = $settings->SmtpPort;

        $email = new PHPMailer(true);

        // Only for development

        $message = "<span style='font-family: Calibri, Arial, sans-serif;'>" . $message . "</span>";

        try {

            //Server settings
            $email->isSMTP();
            $email->Host = $SmtpHost;
            $email->SMTPAuth = true;
            $email->Username = $SmtpUsername; // Your Gmail address
            $email->Password = $SmtpPassword;    // App password from Google
//            $email->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // or 'tls'
            $email->Port = $SmtpPort;

            $email->isHTML(true);
            $email->SetFrom("info@onesourceits.com", "OneSource IT Solutions LLC");

            if (is_array($to)) {
                foreach ($to as $address) {
                    $address = trim(str_replace(" ", "", $address));
                    if (empty($address)) {
                        continue;
                    }
                    $email->addAddress($address);
                }
            } else {
                $email->addAddress($to);
            }

            $email->Subject = $subject;
            $email->Body = $message;

            if (is_array($attachments)) {
                foreach ($attachments as $index => $item) {
                    if (!empty($item)) {
                        $email->addStringAttachment($item, ($attachment_names[$index] ?? "unknown"));
                    }
                }
            } else {
                if (!empty($attachments)) {
                    $email->addStringAttachment($attachments, $attachment_names);
                }
            }

            $success = $email->Send();
        } catch (phpMailerException $e) {

            (new Journal())->journalEntry($e->errorMessage());
            $success = false;
        } catch (Exception $e) {

            (new Journal())->journalEntry($e->getMessage());
            $success = false;
        }

        return $success;
    }

    // ==============================
    // Send an Error Email to Support
    // ==============================

    public function sendErrorEmail($error_message = "", $error_file = "", $error_line = "") {

        $settings = $this->getSettings();

        $Environment = (string) $settings->Environment;
        $SupportEmail = (string) $settings->SupportEmail;

        if ($Environment == "Development") {
            return;
        }

        $application_name = self::APPLICATION_NAME;

        $message = "";

        $message .= "<p>An application error has occurred in the {$application_name} application.<br/><br/></p>";
        $message .= "<p>File:  {$error_file}</p>";
        $message .= "<p>Line:  {$error_line}</p>";
        $message .= "<p>Error: {$error_message}</p>";

        $to = $SupportEmail;
        $subject = "{$application_name} Application Error";

        $this->sendEmail($to, $subject, $message);
    }
}

?>
