<?php
/**
 * Privacy Data Eraser
 *
 * Implements WordPress privacy tools for data erasure (GDPR Article 17).
 *
 * @package DonorCore\Privacy
 */

namespace DonorCore\Privacy;

defined( 'ABSPATH' ) || exit;

/**
 * Privacy Eraser Class
 */
class Privacy_Eraser {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_erasers' ) );
	}

	/**
	 * Register data erasers.
	 *
	 * @param array $erasers Existing erasers.
	 * @return array
	 */
	public function register_erasers( $erasers ) {
		$erasers['donor-core-analytics'] = array(
			'eraser_friendly_name' => __( 'DonorCore Analytics', 'donorcore-donations' ),
			'callback'             => array( $this, 'analytics_eraser' ),
		);

		$erasers['donor-core-receipts'] = array(
			'eraser_friendly_name' => __( 'DonorCore PDF Receipts', 'donorcore-donations' ),
			'callback'             => array( $this, 'receipts_eraser' ),
		);

		return $erasers;
	}

	/**
	 * Erase donor analytics data.
	 *
	 * Note: Donation logs are retained for financial/legal compliance but anonymized.
	 *
	 * @param string $email_address Email address to erase data for.
	 * @param int    $page          Page number.
	 * @return array Erasure results.
	 */
	public function analytics_eraser( $email_address, $page = 1 ) {
		global $wpdb;

		$items_removed  = false;
		$items_retained = false;
		$messages       = array();

		// Delete donor analytics record
		$table   = $wpdb->prefix . 'donorcore_donor_analytics';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct deletion required
		$deleted = $wpdb->delete(
			$table,
			array( 'donor_email' => $email_address ),
			array( '%s' )
		);

		if ( $deleted ) {
			$items_removed = true;
			$messages[]    = __( 'Donor analytics data removed.', 'donorcore-donations' );
		}

		// Anonymize donation logs (retain for financial records but remove personal identifier)
		// Get donor IDs associated with this email
		$donation_repo = new \DonorCore\Database\Donation_Log_Repository();
		$donor_ids     = $donation_repo->get_donor_ids_by_email( $email_address );

		if ( ! empty( $donor_ids ) ) {
			$logs_table = $wpdb->prefix . 'donorcore_donation_logs';
			
			// Set donor_id to 0 (anonymize) for all donations from this email
			foreach ( $donor_ids as $donor_id ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct update required
				$wpdb->update(
					$logs_table,
					array( 'donor_id' => 0 ),
					array( 'donor_id' => $donor_id ),
					array( '%d' ),
					array( '%d' )
				);
			}

			$items_retained = true;
			$messages[]     = __( 'Donation transaction records retained for legal compliance but anonymized (donor ID removed).', 'donorcore-donations' );
		}

		return array(
			'items_removed'  => $items_removed,
			'items_retained' => $items_retained,
			'messages'       => $messages,
			'done'           => true,
		);
	}

	/**
	 * Erase PDF receipts for a donor.
	 *
	 * @param string $email_address Email address to erase receipts for.
	 * @param int    $page          Page number.
	 * @return array Erasure results.
	 */
	public function receipts_eraser( $email_address, $page = 1 ) {
		$items_removed  = false;
		$items_retained = false;
		$messages       = array();

		// Get all orders for this email
		$orders = wc_get_orders(
			array(
				'billing_email' => $email_address,
				'limit'         => -1,
				'return'        => 'ids',
			)
		);

		$files_deleted = 0;

		foreach ( $orders as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				continue;
			}

			// Get receipt file path
			$file_path = $order->get_meta( '_donorcore_receipt_path', true );

			if ( $file_path && file_exists( $file_path ) ) {
				// Delete the PDF file
				if ( wp_delete_file( $file_path ) ) {
					$files_deleted++;
					
					// Remove metadata
					$order->delete_meta_data( '_donorcore_receipt_path' );
					$order->delete_meta_data( '_donorcore_receipt_generated_at' );
					$order->save();
				}
			}
		}

		if ( $files_deleted > 0 ) {
			$items_removed = true;
			/* translators: %d: number of files */
			$messages[] = sprintf( __( '%d PDF receipt(s) deleted.', 'donorcore-donations' ), $files_deleted );
		} else {
			$messages[] = __( 'No PDF receipts found for this email address.', 'donorcore-donations' );
		}

		return array(
			'items_removed'  => $items_removed,
			'items_retained' => $items_retained,
			'messages'       => $messages,
			'done'           => true,
		);
	}
}
