<?php
/**
 * Migration 3 — Re-add is_anonymous to wp_ambh_donors.
 *
 * The column was dropped in migration 2 (SimplifyColumns) on the assumption
 * that anonymisation state only lived on wp_ambh_donations. In practice the
 * donor row itself needs this flag so the admin UI can detect already-
 * anonymised donors without scanning their donation rows.
 *
 * Added in plugin 0.5.1.
 *
 * @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;
}

/**
 * Adds is_anonymous (tinyint, default 0) back to wp_ambh_donors.
 */
class AddIsAnonymous {

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

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

		$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,
				'is_anonymous'
			)
		);

		if ( ! $exists ) {
			$wpdb->query( $wpdb->prepare( "ALTER TABLE `{$table}` ADD COLUMN `is_anonymous` tinyint(1) NOT NULL DEFAULT 0 AFTER `email`" ) );
		}
	}
}
