<?php

namespace PWH_DCFH\App\Admin\Controllers;

use PWH_DCFH\App\Frontend\Controllers\PWH_DCFH_Email_Handler;

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('init', [$this, 'maybe_init'], 10);
                add_action('phpmailer_init', [$this, 'maybe_setup_phpmailer'], 10);
            }
        }

        /**
         * Set From Name and From Email
         * @return void
         */
        public function maybe_init()
        {
            $email_handler = PWH_DCFH_Email_Handler::instance();
            $from_email = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_from_email');
            $from_name = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_from_name');
            $email_handler->set_mail_from($from_email);
            $email_handler->set_mail_from_name($from_name);
        }

        /**
         * Filter PHPMAILER
         *
         * @param $php_mailer
         */
        public function maybe_setup_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;
            }
            //$post_repository = PWH_DCFH_Post_Repository::instance();
            //$email_handler = PWH_DCFH_Email_Handler::instance();
            //$php_mailer->From = 'ali@yahoo.com';
            //$php_mailer->FromName = pwh_dcfh_db()::get_setting('pwh_dcfh_smtp_from_name');
            //pwh_dcfh_log([$post_repository->is_admin_email_from_submitter_email, $post_repository->admin_email_from_name], true);
        }
    }
}