<?php
/**
 * WordPress Privacy Tools integration for Basic Forms entries.
 *
 * @package BasicForms
 * @since 1.0.0
 */

namespace BasicForms;

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

final class PrivacyService {

	public static function registerHooks(): void {
		add_filter( 'wp_privacy_personal_data_exporters', [ self::class, 'registerExporter' ] );
		add_filter( 'wp_privacy_personal_data_erasers', [ self::class, 'registerEraser' ] );
	}

	/**
	 * @param array<string, array<string, mixed>> $exporters
	 * @return array<string, array<string, mixed>>
	 */
	public static function registerExporter( array $exporters ): array {
		$exporters['wpps-basic-forms'] = [
			'exporter_friendly_name' => __( 'Basic Forms Submissions', 'wp-powersuite' ),
			'callback'               => [ self::class, 'exportPersonalData' ],
		];
		return $exporters;
	}

	/**
	 * @param array<string, array<string, mixed>> $erasers
	 * @return array<string, array<string, mixed>>
	 */
	public static function registerEraser( array $erasers ): array {
		$erasers['wpps-basic-forms'] = [
			'eraser_friendly_name' => __( 'Basic Forms Submissions', 'wp-powersuite' ),
			'callback'             => [ self::class, 'erasePersonalData' ],
		];
		return $erasers;
	}

	/**
	 * @return array{data: list<array<string, mixed>>, done: bool}
	 */
	public static function exportPersonalData( string $email_address, int $page ): array {
		global $wpdb;
		$table = $wpdb->prefix . 'wpps_form_entries';
		$email = sanitize_email( $email_address );
		$page  = max( 1, $page );
		$limit = 50;
		$offset = ( $page - 1 ) * $limit;

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$table} WHERE user_email = %s ORDER BY id ASC LIMIT %d OFFSET %d",
				$email,
				$limit,
				$offset
			)
		);

		$export_items = [];
		foreach ( $rows as $row ) {
			$data = json_decode( $row->payload ?? '{}', true );
			$data = is_array( $data ) ? $data : [];
			$group = [
				'group_id'          => 'wpps-basic-form-entry',
				'group_label'       => __( 'Form Submission', 'wp-powersuite' ),
				'group_description' => __( 'Submission stored by Basic Forms.', 'wp-powersuite' ),
				'item_id'           => 'entry-' . (int) $row->id,
				'data'              => [
					[
						'name'  => __( 'Entry ID', 'wp-powersuite' ),
						'value' => (string) (int) $row->id,
					],
					[
						'name'  => __( 'Date', 'wp-powersuite' ),
						'value' => (string) ( $row->date_created ?? '' ),
					],
					[
						'name'  => __( 'Name', 'wp-powersuite' ),
						'value' => (string) ( $row->user_name ?? '' ),
					],
					[
						'name'  => __( 'Email', 'wp-powersuite' ),
						'value' => (string) ( $row->user_email ?? '' ),
					],
				],
			];

			if ( ! empty( $row->user_ip ) ) {
				$group['data'][] = [
					'name'  => __( 'IP Address', 'wp-powersuite' ),
					'value' => (string) $row->user_ip,
				];
			}

			foreach ( $data as $label => $value ) {
				if ( FormFileStorage::normalizeReferences( $value ) !== [] ) {
					$value = FormFileStorage::formatValuePlain( $value, (int) $row->id );
				} elseif ( is_array( $value ) ) {
					$value = implode( ', ', array_map( 'strval', $value ) );
				}
				$group['data'][] = [
					'name'  => (string) $label,
					'value' => (string) $value,
				];
			}

			$export_items[] = $group;
		}

		return [
			'data' => $export_items,
			'done' => count( $rows ) < $limit,
		];
	}

	/**
	 * @return array{items_removed: bool, items_retained: bool, messages: list<string>, done: bool}
	 */
	public static function erasePersonalData( string $email_address, int $page ): array {
		global $wpdb;
		$table = $wpdb->prefix . 'wpps_form_entries';
		$email = sanitize_email( $email_address );
		$page  = max( 1, $page );
		$limit = 50;
		$offset = ( $page - 1 ) * $limit;

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, payload FROM {$table} WHERE user_email = %s ORDER BY id ASC LIMIT %d OFFSET %d",
				$email,
				$limit,
				$offset
			)
		);

		$removed = 0;
		foreach ( $rows as $row ) {
			$entry_id = (int) ( $row->id ?? 0 );
			if ( $entry_id <= 0 ) {
				continue;
			}
			$payload = json_decode( $row->payload ?? '{}', true );
			if ( is_array( $payload ) ) {
				FormFileStorage::deleteFilesForPayload( $payload );
			}
			if ( $wpdb->delete( $table, [ 'id' => $entry_id ], [ '%d' ] ) ) {
				++$removed;
			}
		}

		return [
			'items_removed'  => $removed > 0,
			'items_retained' => false,
			'messages'       => $removed > 0
				/* translators: 1: number, 2: number. */
				? [ sprintf( _n( 'Removed %d form entry.', 'Removed %d form entries.', $removed, 'wp-powersuite' ), $removed ) ]
				: [],
			'done'           => count( $rows ) < $limit,
		];
	}
}

