<?php

namespace PWH_DCFH\App\Admin\Controllers;

if (!defined('ABSPATH')) exit;
if (!class_exists('PWH_DCFH_SMTP')) {
    class PWH_DCFH_SMTP
    {
        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            if (pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_smtp_enabled')) {
                add_action('phpmailer_init', [$this, 'maybe_override_phpmailer']);
                add_filter('wp_mail_from', [$this, 'maybe_filter_mail_from_email']);
                add_filter('wp_mail_from_name', [$this, 'maybe_filter_mail_from_name']);
            }
        }

        /**
         * Filter PHPMAILER
         *
         * @param $php_mailer
         */
        public function maybe_override_phpmailer($php_mailer)
        {
            $php_mailer->isSMTP();
            $smtp_host = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_host');
            $smtp_encryption = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_encryption');
            $smtp_port = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_port');
            $smtp_autotls = pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_smtp_autotls');
            $smtp_auth = pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_smtp_authentication');
            $smtp_username = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_username');
            $smtp_password = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_password');
            $php_mailer->Host = $smtp_host;
            $php_mailer->Port = $smtp_port;
            if ($smtp_auth) {
                $php_mailer->SMTPAuth = true;
                $php_mailer->Username = $smtp_username;
                $php_mailer->Password = $smtp_password;
            }
            if ('none' !== $smtp_encryption) {
                $php_mailer->SMTPSecure = $smtp_encryption;
            }
            if ($smtp_autotls && 'tls' !== $smtp_encryption) {
                $php_mailer->SMTPAutoTLS = true;
            }
        }

        /**
         * Filter WP Mail From
         *
         * @param $from_email
         *
         * @return string|null
         */
        public function maybe_filter_mail_from_email($from_email)
        {
            return pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_from_email', get_bloginfo('admin_email'));
        }

        /**
         * Filter WP Mail From Name
         *
         * @param $from_name
         *
         * @return string|null
         */
        public function maybe_filter_mail_from_name($from_name)
        {
            return pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_from_name', get_bloginfo('name'));
        }
    }
}