<?php
/**
 * File Path: includes/migrations/class-mbs-migration-4-24.php
 *
 * Migration 4.24 -- Migrate brand feed URLs from wp_options JSON blob
 * to the mbs_brand_feed_urls table (RF-012).
 *
 * Source option: mbs_setting_brand_feed_urls.
 * Value is a JSON-encoded array of URL strings.
 *
 * sort_order is assigned by array position (0-indexed).
 * created_at / updated_at set to current UTC time on insert.
 *
 * Idempotency: skips if mbs_brand_feed_urls already contains rows.
 *
 * @package MyBookShowroom
 * @since   1.3.0
 */

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

/**
 * Migration 4.24: Brand feed URLs wp_options -> mbs_brand_feed_urls table.
 */
// 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_24 implements MBS_Migration { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix

	/**
	 * Return the migration version string.
	 *
	 * @return string
	 * @since 1.3.0
	 */
	public function version(): string {
		return '4.24';
	}

	/**
	 * Run the migration.
	 *
	 * Reads the mbs_setting_brand_feed_urls option (JSON array of URL strings)
	 * and inserts each URL into the mbs_brand_feed_urls table.
	 * Skips if the table already has rows.
	 *
	 * @return void
	 * @since 1.3.0
	 */
	public function up(): void {
		global $wpdb;
		$table = $wpdb->prefix . 'mbs_brand_feed_urls';

		// Idempotency guard.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$existing = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- DAO layer -- direct DB access is intentional per MBS architecture
		if ( $existing > 0 ) {
			return;
		}

		$raw  = get_option( 'mbs_setting_brand_feed_urls', array() );
		$urls = is_array( $raw ) ? $raw : json_decode( $raw, true );
		if ( ! is_array( $urls ) || empty( $urls ) ) {
			return;
		}

		$now = current_time( 'mysql', true ); // UTC (A-005).

		foreach ( $urls as $i => $url ) {
			$url = esc_url_raw( (string) $url );
			if ( '' === $url ) {
				continue;
			}

			$wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- DAO layer -- direct DB access is intentional per MBS architecture
				$table,
				array(
					'feed_url'   => $url,
					'sort_order' => $i,
					'created_at' => $now,
					'updated_at' => $now,
				),
				array( '%s', '%d', '%s', '%s' )
			);
		}
	}
}
