<?php
/**
 * Migration 4 — Add address columns to wp_ambh_donors.
 *
 * Adds street, city, postal_code, state, country so donor profiles
 * can store a full mailing address collected at donation time.
 *
 * Added in plugin 0.6.0.
 *
 * @package AmbassadorHub\Donors\Migrations
 */

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 address columns to wp_ambh_donors.
 *
 * Each column is guarded by an INFORMATION_SCHEMA existence check so the
 * migration is idempotent and safe to run on already-upgraded installs.
 */
class AddAddressColumns {

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

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

		$columns = array(
			'street'      => "ALTER TABLE `{$table}` ADD COLUMN `street` varchar(255) DEFAULT NULL AFTER `is_anonymous`",
			'city'        => "ALTER TABLE `{$table}` ADD COLUMN `city` varchar(100) DEFAULT NULL AFTER `street`",
			'postal_code' => "ALTER TABLE `{$table}` ADD COLUMN `postal_code` varchar(20) DEFAULT NULL AFTER `city`",
			'state'       => "ALTER TABLE `{$table}` ADD COLUMN `state` varchar(100) DEFAULT NULL AFTER `postal_code`",
			'country'     => "ALTER TABLE `{$table}` ADD COLUMN `country` varchar(2) DEFAULT NULL AFTER `state`",
		);

		foreach ( $columns as $column => $sql ) {
			$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( $sql );
			}
		}
	}
}
