<?php
/**
 * Migration: Add donor_id to Donations Table
 *
 * Adds a donor_id foreign key column to ambh_donations, linking each
 * donation record to the new ambh_donors table.
 *
 * @package AmbassadorHub\Donations\Migrations
 */

namespace AmbassadorHub\Donations\Migrations;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange

/**
 * Adds donor_id column and index to ambh_donations.
 *
 * Added in plugin 0.4.0.
 */
class AddDonorId {

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

		$table = esc_sql( $wpdb->prefix . 'ambh_donations' );

		// Only add the column if it does not already exist.
		$column_exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s AND COLUMN_NAME = 'donor_id'",
				DB_NAME,
				$table
			)
		);

		if ( ! $column_exists ) {
			$wpdb->query( "ALTER TABLE {$table} ADD COLUMN donor_id bigint(20) unsigned DEFAULT NULL AFTER fundraiser_id" );
			$wpdb->query( "ALTER TABLE {$table} ADD KEY donor_id (donor_id)" );
		}
	}
}
