<?php
/**
 * File: class-mailsettingscontroller.php
 *
 *
 * @since 2024-07-31
 * @license GPL-3.0-or-later
 *
 * @package mareike/
 */

namespace Bdp\Modules\Mail\Controllers;

class MailSettingsController {
	public static function set_smtp_if_required() {


		$smtp_host = get_option('kompass_smtp_host', null); // SMTP-Host
		$smtp_port = get_option('kompass_smtp_port', null); // SMTP-Port
		$smtp_username = get_option('kompass_smtp_user', null); // SMTP-Benutzername
		$smtp_password = get_option('kompass_smtp_pass', null); // SMTP-Passwort
		$smtp_secure = 'tls'; // Verschlüsselung (tls oder ssl)


		if (false !== (bool)get_option('kompass_use_smtp', false) &&
		null !== $smtp_host &&
		null !== $smtp_port &&
		null !== $smtp_username &&
		null !== $smtp_password) {

			add_action( 'phpmailer_init', function ( $phpmailer ) use ( $smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_secure ) {
				$phpmailer->isSMTP();
				$phpmailer->Host     = $smtp_host;
				$phpmailer->Port     = $smtp_port;
				$phpmailer->SMTPAuth = true;
				$phpmailer->Username = $smtp_username;
				$phpmailer->Password = $smtp_password;

				$sender = get_option('kompass_smtp_sender', null);
				$sender_name = get_option('kompass_smtp_sender-name', null);

				if (null !== $sender && null !== $sender_name)
					$phpmailer->setFrom( $sender, $sender_name );
				#$phpmailer->SMTPSecure = $smtp_secure;
			} );
		}

	}

	public static function settings_form() {
		if (isset($_POST['save'])) {
			update_option('kompass_use_smtp', false);

			if (isset($_POST['use_smtp'])) update_option('kompass_use_smtp', true);
			update_option('kompass_smtp_host', sanitize_text_field(wp_unslash($_POST['smtp-host'])));
			update_option('kompass_smtp_port', sanitize_text_field(wp_unslash($_POST['smtp-port'])));
			update_option('kompass_smtp_user', sanitize_text_field(wp_unslash($_POST['smtp-user'])));
			update_option('kompass_smtp_pass', sanitize_text_field(wp_unslash($_POST['smtp-pass'])));
			update_option('kompass_smtp_sender', sanitize_text_field(wp_unslash($_POST['smtp-sender'])));
			update_option('kompass_smtp_sender-name', sanitize_text_field(wp_unslash($_POST['smtp-sender-name'])));

			kompass_print_message_box('Die Einstellungen wurden gespeichert.');
		}


		require BDP_LV_PLUGIN_DIR . '/settings/views/mail-settings.php';


	}

}