<?php
/**
 * File Path: includes/migrations/class-mbs-migration-2-7.php
 *
 * MBS_Migration_2_7 — Sprint F-NAMES-1 — Pre-compute mbs_name_key
 *
 * Populate mbs_name_key termmeta fallback for existing mbs_author and
 * mbs_contributor terms that have no structured name data. Idempotent.
 *
 * @package MyBookShowroom
 * @since   3.2.0
 */

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

/**
 * Class MBS_Migration_2_7
 *
 * Populate mbs_name_key termmeta fallback for existing mbs_author and
 * mbs_contributor terms that have no structured name data. Idempotent.
 *
 * @implements MBS_Migration
 */
class MBS_Migration_2_7 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * {@inheritdoc}
	 *
	 * @return string
	 */
	public function version(): string {
		return '2.7';
	}

	/**
	 * {@inheritdoc}
	 *
	 * Populate mbs_name_key termmeta fallback for existing mbs_author and
 * mbs_contributor terms that have no structured name data. Idempotent.
	 *
	 * @return void
	 */
	public function up(): void {
		global $wpdb;
		foreach ( array( 'mbs_author', 'mbs_contributor' ) as $tax ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			$wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- DAO layer -- direct DB access is intentional per MBS architecture
				"INSERT INTO {$wpdb->termmeta} (term_id, meta_key, meta_value)
				 SELECT tt.term_id, 'mbs_name_key',
				        SUBSTRING_INDEX( TRIM( t.name ), ' ', -1 )
				 FROM {$wpdb->term_taxonomy} tt
				 JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
				 WHERE tt.taxonomy = %s
				   AND LOCATE( ' ', TRIM( t.name ) ) > 0
				   AND NOT EXISTS (
				       SELECT 1 FROM {$wpdb->termmeta}
				       WHERE term_id = tt.term_id AND meta_key = 'mbs_name_key'
				   )
				   AND NOT EXISTS (
				       SELECT 1 FROM {$wpdb->termmeta}
				       WHERE term_id = tt.term_id
				         AND meta_key = 'mbs_is_corporate' AND meta_value = '1'
				   )",
				$tax
			) );
		}
	}
}
