<?php
/**
 * Logger privacy utilities.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use MailDoctor\Helpers\Settings;

trait Logger_Privacy_Trait {

	/**
	 * Remove personal data for matching recipient.
	 *
	 * @param string $email Email address.
	 * @return int Number of records updated.
	 */
	public static function anonymize_recipient( string $email ): int {
		$email = strtolower( sanitize_email( $email ) );

		if ( '' === $email ) {
			return 0;
		}

		global $wpdb;

		$updated = 0;
		$page    = 1;
		$batch   = 100;

		do {
			$result = self::find_logs_by_recipient( $email, $page, $batch );
			$items  = $result['items'];

			foreach ( (array) $items as $row ) {
				$payload = json_decode( $row['payload'] ?? '', true );

				if ( is_array( $payload ) ) {
					if ( isset( $payload['meta'] ) && is_array( $payload['meta'] ) ) {
						$payload['meta']['recipients_plain'] = array();
						$payload['meta']['recipients_hash']  = array();
					}

					if ( isset( $payload['mail_args'] ) && is_array( $payload['mail_args'] ) ) {
						$payload['mail_args']['to'] = array();
					}

					$row['payload'] = wp_json_encode( $payload );
				}

				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Privacy erasure update.
				$wpdb->update(
					self::table_name(),
					array(
						'to_email' => __( '[erased]', 'mail-doctor' ),
						'payload'  => $row['payload'] ?? null,
					),
					array( 'id' => (int) $row['id'] ),
					array( '%s', '%s' ),
					array( '%d' )
				);

				++$updated;
			}

			++$page;
		} while ( ! empty( $items ) && count( $items ) === $batch );

		return $updated;
	}
}
