<?php
/**
 * Migration 3 — Remove inline donor PII columns from wp_ambh_donations.
 *
 * Donor personal data is stored exclusively in wp_ambh_donors, linked via
 * the donor_id FK. The five inline duplicate columns are no longer needed
 * and are dropped here to remove the duplicated GDPR surface area.
 *
 * Added in plugin 0.5.0.
 *
 * @package AmbassadorHub\Donations
 */

namespace AmbassadorHub\Donations\Migrations;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter

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

/**
 * Drops the five inline PII columns from wp_ambh_donations.
 *
 * Each column is guarded by an INFORMATION_SCHEMA existence check so the
 * migration is safe to run multiple times (idempotent).
 */
class RemoveDonorPiiColumns {

	/**
	 * Run the migration.
	 *
	 * @return void
	 */
	public static function up(): void {
		global $wpdb;

		$table = $wpdb->prefix . 'ambh_donations';

		// Whitelist of columns to drop — never interpolated from user input.
		$columns = array( 'donor_name', 'donor_first_name', 'donor_middle_name', 'donor_last_name', 'donor_email' );

		foreach ( $columns as $column ) {
			$exists = (int) $wpdb->get_var(
				$wpdb->prepare(
					'SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
					 WHERE TABLE_SCHEMA = DATABASE()
					   AND TABLE_NAME   = %s
					   AND COLUMN_NAME  = %s',
					$table,
					$column
				)
			);

			if ( $exists ) {
				$wpdb->query( $wpdb->prepare( "ALTER TABLE `{$table}` DROP COLUMN `{$column}`" ) );
			}
		}
	}
}
