<?php
/**
 * @package Hafenstudios\Leadlotse
 */

namespace Hafenstudios\Leadlotse\Privacy;

use Hafenstudios\Core\Events\EventBus;
use Hafenstudios\Leadlotse\Db\EntryRepository;

defined( 'ABSPATH' ) || exit;

/**
 * Haengt die Leadlotse-Entries an die Privacy-Werkzeuge des Core
 * (WP-Exporter/-Eraser laufen ueber die Flotten-Filter `privacy_export`
 * und `privacy_erase`, siehe Core PrivacyManager).
 */
final class PrivacyBridge {

	private EntryRepository $entries;

	/**
	 * @param EntryRepository $entries Entry-Repository.
	 */
	public function __construct( EntryRepository $entries ) {
		$this->entries = $entries;
	}

	/**
	 * Registriert die Filter.
	 *
	 * @return void
	 */
	public function register(): void {
		EventBus::add_filter( 'privacy_export', array( $this, 'export' ), 10, 2 );
		EventBus::add_filter( 'privacy_erase', array( $this, 'erase' ), 10, 2 );
	}

	/**
	 * Export-Items fuer eine E-Mail.
	 *
	 * @param array<int, array<string, mixed>> $items Bisherige Items.
	 * @param string                           $email E-Mail.
	 * @return array<int, array<string, mixed>>
	 */
	public function export( array $items, string $email ): array {
		foreach ( $this->entries->find_by_email( $email ) as $entry ) {
			$data = array(
				array(
					'name'  => __( 'Eingegangen am', 'leadlotse' ),
					'value' => (string) $entry['created_at'],
				),
				array(
					'name'  => __( 'Status', 'leadlotse' ),
					'value' => (string) $entry['status'],
				),
			);
			foreach ( (array) $entry['field_values'] as $key => $value ) {
				$data[] = array(
					'name'  => (string) $key,
					'value' => is_array( $value ) ? implode( ', ', $value ) : (string) $value,
				);
			}

			$items[] = array(
				'group_id'    => 'hs_entries',
				'group_label' => __( 'Formular-Anfragen (Leadlotse)', 'leadlotse' ),
				'item_id'     => 'entry-' . $entry['id'],
				'data'        => $data,
			);
		}
		return $items;
	}

	/**
	 * Loescht die Entries zu einer E-Mail.
	 *
	 * @param array<string, mixed> $result Bisheriges Loeschergebnis.
	 * @param string               $email  E-Mail.
	 * @return array<string, mixed>
	 */
	public function erase( array $result, string $email ): array {
		$removed = $this->entries->delete_by_email( $email );
		if ( $removed > 0 ) {
			$result['items_removed'] = true;
		}
		return $result;
	}
}
