<?php

declare(strict_types=1);

namespace Australcode\Rewards\Infrastructure\Database\Migrations;

use Australcode\Rewards\Infrastructure\Database\Schema;

defined( 'ABSPATH' ) || exit;

/**
 * Adds is_blocked to wp_acrwd_balances (B6): a per-customer flag that, when set,
 * stops the customer from earning automatic order points and from redeeming.
 * Manual admin adjustments are deliberately NOT blocked. Data-only ALTER,
 * idempotent (the column is added only when missing), so re-running is safe.
 *
 * CORE — NOT @fs_premium_only. Unlike M0006 (which alters the Pro-only tiers
 * table), the balances table exists in every build and the earn/redeem guards
 * read this column, so it must ship in the free WP.org build too. The flag is
 * only ever SET by the Pro customer tools, but is READ everywhere — that is what
 * keeps a customer blocked under Pro blocked even if the Pro license later lapses.
 */
final class M0007AddBalanceBlocked implements Migration {

	public function version(): int {
		return 7;
	}

	public function description(): string {
		return 'Add is_blocked flag to balances';
	}

	public function up(): void {
		global $wpdb;
		$table = Schema::table_name( Schema::TABLE_BALANCES );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- column existence probe; table name from internal Schema constant.
		$exists = $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$table}` LIKE %s", 'is_blocked' ) );
		if ( null !== $exists ) {
			return;
		}

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- table/column/definition from internal constants, not user input.
		$wpdb->query( "ALTER TABLE `{$table}` ADD COLUMN `is_blocked` tinyint(1) NOT NULL DEFAULT 0" );
	}
}
