<?php
/**
 * File Path: includes/migrations/class-mbs-migration-3-4.php
 *
 * MBS_Migration_3_4 -- Sprint POS-2 -- Add square_item_id to mbs_format_rows
 *
 * Adds an optional VARCHAR(100) column to store the Square catalog item ID
 * for each format row.  Used by the Square for WooCommerce integration so
 * the author can map each book edition to its Square catalog entry.
 *
 * dbDelta handles the ADD COLUMN idempotently; re-running on an already-
 * updated table is a no-op.
 *
 * @package MyBookShowroom
 * @since   3.4.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MBS_Migration_3_4
 *
 * @implements MBS_Migration
 */
class MBS_Migration_3_4 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	public function version(): string {
		return '3.4';
	}

	public function up(): void {
		global $wpdb;
		$table = $wpdb->prefix . 'mbs_format_rows';

		// AUD-016: guarded ADD COLUMN instead of a fragile single-column dbDelta
		// CREATE stub (which relies on dbDelta diffing a partial schema). Matches
		// the SHOW COLUMNS + ALTER pattern used by migration 4-19.
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- DAO/migration: table name from $wpdb->prefix; fixed column name
		$exists = $wpdb->get_var( "SHOW COLUMNS FROM `{$table}` LIKE 'square_item_id'" );
		if ( ! $exists ) {
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange
			$wpdb->query( "ALTER TABLE `{$table}` ADD COLUMN square_item_id VARCHAR(100) NULL DEFAULT NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- migration: fixed internal column definition
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.SchemaChange
		}
	}
}
