<?php
/**
 * Migration 019: Migrate Legacy Global Settings Data
 *
 * Migrates feeds using the legacy use_global_settings=1 flag
 * to the new per-field inheritance system. For each feed with
 * use_global_settings=1, sets appropriate inherit_* flags.
 *
 * Strategy:
 * - Feeds with use_global_settings=1 → Set all inherit_* flags to 1
 * - Feeds with use_global_settings=0 → Keep all inherit_* flags at 0
 * - After migration, use_global_settings becomes deprecated (kept for backward compatibility)
 *
 * @package Wisewand
 * @since 2.1.5
 * @license GPL-2.0-or-later
 */

namespace Wisewand\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Migration class for migrating legacy global settings data
 *
 * @since 2.1.5
 */
class Migration_019_Migrate_Legacy_Data {

	/**
	 * Run the migration
	 *
	 * @since 2.1.5
	 * @global wpdb $wpdb WordPress database abstraction object.
	 * @return bool True if migration ran successfully or already completed.
	 */
	public static function run() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'wisewand_rss_feeds';

		// Check if table exists (upgrade scenario only).
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );

		if ( ! $table_exists ) {
			// Table doesn't exist yet - skip migration (fresh install).
			return true;
		}

		// Check if Migration 18 has run (inherit_author column must exist).
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$inherit_column_exists = $wpdb->get_results(
			$wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'inherit_author' )
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( empty( $inherit_column_exists ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 19 skipped - Migration 18 must run first' );
			}
			return false;
		}

		// Check if migration already completed (look for option marker).
		$migration_completed = get_option( 'wisewand_migration_19_completed', false );
		if ( $migration_completed ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 19 already completed (marker option exists)' );
			}
			return true;
		}

		// Migration needed.
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Starting Migration 19 - Migrating legacy global settings data' );
		}

		// Count feeds to migrate.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$feeds_to_migrate = $wpdb->get_var(
			"SELECT COUNT(*) FROM `{$table_name}` WHERE use_global_settings = 1"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( "Wisewand: Found {$feeds_to_migrate} feeds using global settings to migrate" );
		}

		// Set inherit_* flags for feeds with use_global_settings=1.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$result = $wpdb->query(
			"UPDATE `{$table_name}`
			SET inherit_import_frequency = 1,
			inherit_author = 1,
				inherit_categories = 1,
				inherit_publish_mode = 1,
				inherit_max_articles = 1,
				inherit_ai_categories = 1,
				updated_at = NOW()
			WHERE use_global_settings = 1"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( $wpdb->last_error ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 19 error: ' . $wpdb->last_error );
			}
			return false;
		}

		$rows_affected = $wpdb->rows_affected;

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( "Wisewand: Migration 19 completed - Migrated {$rows_affected} feeds" );
			error_log( 'Wisewand: Feeds with use_global_settings=1 now use per-field inheritance' );
		}

		// Mark migration as completed.
		update_option( 'wisewand_migration_19_completed', current_time( 'mysql' ) );

		return true;
	}

	/**
	 * Rollback the migration
	 *
	 * @since 2.1.5
	 * @global wpdb $wpdb WordPress database abstraction object.
	 * @return bool True if rollback succeeded.
	 */
	public static function rollback() {
		global $wpdb;

		$table_name = $wpdb->prefix . 'wisewand_rss_feeds';

		// Check if table exists.
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );

		if ( ! $table_exists ) {
			return true;
		}

		// Reset inherit_* flags to 0 for feeds that were migrated.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$wpdb->query(
			"UPDATE `{$table_name}`
			SET inherit_author = 0,
				inherit_categories = 0,
				inherit_publish_mode = 0,
				inherit_max_articles = 0,
				inherit_ai_categories = 0,
				updated_at = NOW()
			WHERE use_global_settings = 1"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		// Remove migration marker.
		delete_option( 'wisewand_migration_19_completed' );

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			if ( $wpdb->last_error ) {
				error_log( 'Wisewand: Migration 19 rollback error: ' . $wpdb->last_error );
				return false;
			}
			error_log( 'Wisewand: Migration 19 rolled back successfully' );
		}

		return true;
	}
}
