<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-30.php
 *
 * Migration 4.30 -- Session 186: UX-EDIT-002 -- Remove stale section-order
 * rows (social-share, suggested-reading-order) from global default and all
 * per-book rows, then re-seed the global default to ensure all 12 canonical
 * keys are present.
 *
 * Idempotency: DELETE WHERE exact match is safe to re-run; seed is additive-only.
 *
 * @package MyBookShowroom
 * @since   1.5.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- DAO/migration: table names via $wpdb->prefix are trusted server-controlled values, not user input
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter -- same reason: $wpdb->prefix table names are safe; $where_sql is built from sanitized server-controlled inputs
class MBS_Migration_4_30 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 '4.30'; }
	public function up(): void {
		global $wpdb;
		$table = $wpdb->prefix . 'mbs_section_order';
		$stale = array( 'social-share', 'suggested-reading-order' );
		foreach ( $stale as $key ) {
			$wpdb->delete( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- DAO layer -- direct DB access is intentional per MBS architecture
				$table,
				array( 'post_id' => 0, 'section_key' => sanitize_key( $key ) ),
				array( '%d', '%s' )
			);
			$wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- DAO layer -- direct DB access is intentional per MBS architecture
				"DELETE FROM {$table} WHERE section_key = %s AND post_id > 0",
				sanitize_key( $key )
			) );
		}
		if ( class_exists( 'MBS_DB_Installer' ) ) {
			MBS_DB_Installer::seed_default_section_order();
		}
	}
}
