<?php
/**
 * Disable Auto-Update Emails Module
 *
 * @package DisableAutoUpdateEmails
 * @since 1.0.0
 */

namespace DisableAutoUpdateEmails;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'disable-auto-update-emails';
	private const MODULE_VERSION = '1.2.0';

	private ?array $settings_cache = null;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Disable Auto-Update Emails', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Turns off WordPress update notification emails after core, plugin, or theme changes.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'cron' ];
	}

	public function getDefaultSettings(): array {
		return [
			'disable_all_update_emails' => false,
			'disable_core_updates'      => true,
			'disable_plugin_updates'    => true,
			'disable_theme_updates'     => true,
		];
	}

	protected function registerHooks(): void {
		$settings = $this->getSettings();

		if ( ! empty( $settings['disable_all_update_emails'] ) ) {
			$this->disableAllUpdateEmails();
			return;
		}

		if ( ! empty( $settings['disable_core_updates'] ) ) {
			$this->disableCoreUpdateEmails();
		}

		if ( ! empty( $settings['disable_plugin_updates'] ) ) {
			add_filter( 'auto_plugin_update_send_email', '__return_false', 999 );
		}

		if ( ! empty( $settings['disable_theme_updates'] ) ) {
			add_filter( 'auto_theme_update_send_email', '__return_false', 999 );
		}
	}

	private function disableAllUpdateEmails(): void {
		$this->disableCoreUpdateEmails();
		add_filter( 'auto_plugin_update_send_email', '__return_false', 999 );
		add_filter( 'auto_theme_update_send_email', '__return_false', 999 );
	}

	private function disableCoreUpdateEmails(): void {
		add_filter( 'auto_core_update_send_email', '__return_false', 999 );
		add_filter( 'send_core_update_notification_email', '__return_false', 999 );
		add_filter( 'automatic_updates_send_debug_email', '__return_false', 999 );
	}

	private function getSettings(): array {
		if ( $this->settings_cache !== null ) {
			return $this->settings_cache;
		}

		$saved = $this->moduleSettings()->all( [] );
		if ( ! is_array( $saved ) ) {
			$saved = [];
		}

		// Back-compat: older saves used disable_all_updates for this module.
		if ( ! isset( $saved['disable_all_update_emails'] ) && ! empty( $saved['disable_all_updates'] ) ) {
			$saved['disable_all_update_emails'] = true;
		}

		$this->settings_cache = array_merge( $this->getDefaultSettings(), $saved );

		return $this->settings_cache;
	}
}
