<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-5.php
 *
 * MBS_Migration_4_5 -- Schema 4.5 -- Phase 0 key consolidation
 *
 * Two postmeta cleanup tasks performed together:
 *
 * 1. pub_date consolidation (Phase 0-B): For every mbs_book post that has a
 *    mbs_publication_date value but no mbs_pub_date value, copies the date
 *    string to mbs_pub_date so all code paths converge on one canonical key.
 *
 * 2. Territorial rights v1 retirement (Phase 0-C): Deletes all
 *    mbs_territorial_rights postmeta rows (the legacy free-text field).
 *    The structured v2 key (mbs_territorial_rights_v2) is unaffected.
 *
 * Both operations are idempotent.
 *
 * @package MyBookShowroom
 * @since   4.5.0
 */

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

/**
 * Class MBS_Migration_4_5
 *
 * @implements MBS_Migration
 */
class MBS_Migration_4_5 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 '4.5';
	}

	/**
	 * {@inheritdoc}
	 *
	 * Copies mbs_publication_date -> mbs_pub_date for books where mbs_pub_date
	 * is absent or empty, then deletes all mbs_territorial_rights (v1) rows.
	 *
	 * @return void
	 */
	public function up(): void {
		global $wpdb;

		// ---- 1. pub_date consolidation -----------------------------------------
		// INSERT mbs_pub_date for every book that has mbs_publication_date but
		// not a non-empty mbs_pub_date. Idempotent: the NOT EXISTS sub-select
		// prevents duplicate rows on re-run.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery -- DAO layer -- direct DB access is intentional per MBS architecture
			"INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value)
			 SELECT pm.post_id, 'mbs_pub_date', pm.meta_value
			 FROM {$wpdb->postmeta} pm
			 WHERE pm.meta_key   = 'mbs_publication_date'
			   AND pm.meta_value != ''
			   AND NOT EXISTS (
				   SELECT 1 FROM {$wpdb->postmeta} pm2
				   WHERE pm2.post_id    = pm.post_id
				     AND pm2.meta_key   = 'mbs_pub_date'
				     AND pm2.meta_value != ''
			   )"
		);

		// ---- 2. Territorial rights v1 retirement --------------------------------
		// Delete the legacy free-text mbs_territorial_rights key for all posts.
		// The structured mbs_territorial_rights_v2 key is not affected.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$wpdb->delete(
			$wpdb->postmeta,
			array( 'meta_key' => 'mbs_territorial_rights' ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- standard WP query pattern; VIP rule does not apply to this plugin
			array( '%s' )
		);
	}
}
