<?php
/**
 * Network administration for Mail Doctor.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use MailDoctor\Helpers\Settings;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles multisite defaults and enforcement.
 */
class Network {

	/**
	 * Hooks for multisite environments.
	 *
	 * @return void
	 */
	public static function init(): void {
		if ( ! is_multisite() ) {
			return;
		}

		add_action( 'network_admin_menu', array( __CLASS__, 'register_menu' ) );
		add_action( 'network_admin_edit_mail_doctor_network', array( __CLASS__, 'handle_save' ) );
	}

	/**
	 * Register network settings page.
	 *
	 * @return void
	 */
	public static function register_menu(): void {
		add_submenu_page(
			'settings.php',
			__( 'Mail Doctor Defaults', 'mail-doctor' ),
			__( 'Mail Doctor Defaults', 'mail-doctor' ),
			'manage_network_options',
			'mail-doctor-network',
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * Render network configuration page.
	 *
	 * @return void
	 */
	public static function render_page(): void {
		if ( ! current_user_can( 'manage_network_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to manage Mail Doctor network settings.', 'mail-doctor' ) );
		}

		$config   = Settings::network_config();
		$mail_doctor_defaults = $config['defaults'];
		$mail_doctor_locks    = $config['locks'];

		include MAIL_DOCTOR_PATH . 'templates/admin/network-settings.php';
	}

	/**
	 * Handle network defaults submission.
	 *
	 * @return void
	 */
	public static function handle_save(): void {
		if ( ! current_user_can( 'manage_network_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to manage Mail Doctor network settings.', 'mail-doctor' ) );
		}

		check_admin_referer( 'mail_doctor_network' );

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Individual keys sanitized below.
		$data = isset( $_POST['network_settings'] ) && is_array( $_POST['network_settings'] ) ? wp_unslash( $_POST['network_settings'] ) : array();
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Individual keys sanitized below.
		$locks_input = isset( $_POST['network_locks'] ) && is_array( $_POST['network_locks'] ) ? wp_unslash( $_POST['network_locks'] ) : array();
		if ( ! is_array( $locks_input ) ) {
			$locks_input = array();
		}

		$defaults = array(
			'smtp_host'                   => isset( $data['smtp_host'] ) ? sanitize_text_field( wp_unslash( $data['smtp_host'] ) ) : '',
			'smtp_port'                   => isset( $data['smtp_port'] ) ? (int) $data['smtp_port'] : '',
			'smtp_encryption'             => isset( $data['smtp_encryption'] ) ? sanitize_text_field( wp_unslash( $data['smtp_encryption'] ) ) : '',
			'smtp_username'               => isset( $data['smtp_username'] ) ? sanitize_text_field( wp_unslash( $data['smtp_username'] ) ) : '',
			'smtp_password'               => isset( $data['smtp_password'] ) && '' !== $data['smtp_password'] ? trim( (string) wp_unslash( $data['smtp_password'] ) ) : '',
			'from_email'                  => isset( $data['from_email'] ) ? sanitize_email( wp_unslash( $data['from_email'] ) ) : '',
			'from_name'                   => isset( $data['from_name'] ) ? sanitize_text_field( wp_unslash( $data['from_name'] ) ) : '',
			'override_scope'              => isset( $data['override_scope'] ) ? sanitize_text_field( wp_unslash( $data['override_scope'] ) ) : '',
			'max_attempts'                => isset( $data['max_attempts'] ) ? (int) $data['max_attempts'] : '',
			'backoff_schedule'            => isset( $data['backoff_schedule'] ) ? array_map( 'intval', array_filter( array_map( 'trim', explode( ',', wp_unslash( $data['backoff_schedule'] ) ) ) ) ) : array(),
			'log_retention'               => isset( $data['log_retention'] ) ? (int) $data['log_retention'] : '',
			'cleanup_on_uninstall'        => isset( $data['cleanup_on_uninstall'] ) ? (bool) $data['cleanup_on_uninstall'] : false,
			'compatibility_mode'          => isset( $data['compatibility_mode'] ) ? (bool) $data['compatibility_mode'] : false,
			'list_unsubscribe'            => isset( $data['list_unsubscribe'] ) ? (bool) $data['list_unsubscribe'] : false,
			'list_unsubscribe_mailto'     => isset( $data['list_unsubscribe_mailto'] ) ? sanitize_email( wp_unslash( $data['list_unsubscribe_mailto'] ) ) : '',
			'list_unsubscribe_url'        => isset( $data['list_unsubscribe_url'] ) ? esc_url_raw( wp_unslash( $data['list_unsubscribe_url'] ) ) : '',

			'structured_logging_enabled'  => isset( $data['structured_logging_enabled'] ) ? (bool) $data['structured_logging_enabled'] : false,
			'structured_logging_endpoint' => isset( $data['structured_logging_endpoint'] ) ? esc_url_raw( wp_unslash( $data['structured_logging_endpoint'] ) ) : '',
			'structured_logging_token'    => isset( $data['structured_logging_token'] ) ? sanitize_text_field( wp_unslash( $data['structured_logging_token'] ) ) : '',
			'privacy_mode'                => isset( $data['privacy_mode'] ) ? (bool) $data['privacy_mode'] : false,
			'hash_recipients'             => isset( $data['hash_recipients'] ) ? (bool) $data['hash_recipients'] : false,
			'retention_sent_days'         => isset( $data['retention_sent_days'] ) ? (int) $data['retention_sent_days'] : '',
			'retention_failed_days'       => isset( $data['retention_failed_days'] ) ? (int) $data['retention_failed_days'] : '',
			'retention_payload_days'      => isset( $data['retention_payload_days'] ) ? (int) $data['retention_payload_days'] : '',
		);

		if ( empty( $defaults['smtp_password'] ) ) {
			unset( $defaults['smtp_password'] );
		}

		if ( empty( $defaults['backoff_schedule'] ) ) {
			unset( $defaults['backoff_schedule'] );
		}

		foreach ( $defaults as $key => $value ) {
			if ( is_string( $value ) && '' === $value ) {
				unset( $defaults[ $key ] );
			}
		}

		$locks = array();
		foreach ( $locks_input as $key => $value ) {
			$locks[ sanitize_key( $key ) ] = (bool) $value;
		}

		Settings::set_network_defaults( $defaults, $locks );

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'mail-doctor-network',
					'updated' => 'true',
				),
				network_admin_url( 'settings.php' )
			)
		);
		exit;
	}
}
