<?php
/**
 * Migration 2 — Simplify wp_ambh_donors schema.
 *
 * Drops the middle_name and is_anonymous columns:
 * - middle_name is removed entirely (first + last is sufficient).
 * - is_anonymous is a per-donation display flag and lives on wp_ambh_donations;
 *   it does not belong on the donor profile row.
 *
 * Added in plugin 0.5.0.
 *
 * @package AmbassadorHub\Donors
 */

namespace AmbassadorHub\Donors\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 middle_name and is_anonymous from wp_ambh_donors.
 *
 * Each column is guarded by an INFORMATION_SCHEMA existence check so the
 * migration is safe to run multiple times (idempotent).
 */
class SimplifyColumns {

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

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

		// Whitelist of columns to drop — never interpolated from user input.
		$columns = array( 'middle_name', 'is_anonymous' );

		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}`" ) );
			}
		}
	}
}
