<?php
/**
 * Migration 021: Add Missing Import Frequency Inheritance Flag
 *
 * Adds the inherit_import_frequency column that was missing from Migration 018.
 * This hotfix ensures the Settings page inheritance indicators work correctly.
 *
 * @package Wisewand
 * @since 2.2.1
 * @license GPL-2.0-or-later
 */

namespace Wisewand\Database\Migrations;

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

/**
 * Migration class for adding import frequency inheritance flag
 *
 * @since 2.2.1
 */
class Migration_021_Add_Import_Frequency_Inheritance {

	/**
	 * Run the migration
	 *
	 * @since 2.2.1
	 * @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.
		// 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.
			return true;
		}

		// Check if inherit_import_frequency column already exists.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$column_exists = $wpdb->get_results(
			$wpdb->prepare( "SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'inherit_import_frequency' )
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( ! empty( $column_exists ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'Wisewand: Migration 21 already completed (inherit_import_frequency column exists)' );
			}
			return true;
		}

		// Migration needed.
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Starting Migration 21 - Adding inherit_import_frequency column' );
		}

		// Add inherit_import_frequency column.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$result = $wpdb->query(
			"ALTER TABLE `{$table_name}`
			ADD COLUMN inherit_import_frequency TINYINT(1) DEFAULT 0
			COMMENT 'Inherit import_schedule_type from global settings'
			AFTER import_schedule_type"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

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

		// Set inherit_import_frequency=1 for feeds that already have other inherit flags set.
		// This applies the new inheritance to existing feeds that use global settings.
		// Transaction wraps only DML — ALTER TABLE above causes implicit commit in MySQL.
		$wpdb->query( 'START TRANSACTION' );

		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$wpdb->query(
			"UPDATE `{$table_name}`
			SET inherit_import_frequency = 1
			WHERE inherit_author = 1
			   OR inherit_publish_mode = 1
			   OR inherit_max_articles = 1"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

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

		$wpdb->query( 'COMMIT' );

		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'Wisewand: Migration 21 completed successfully - Import frequency inheritance added' );
			error_log( 'Wisewand: All 6 inheritance flags now available' );
		}

		return $result !== false;
	}

	/**
	 * Rollback the migration
	 *
	 * @since 2.2.1
	 * @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;
		}

		// Drop inherit_import_frequency column if it exists.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter
		$wpdb->query(
			"ALTER TABLE `{$table_name}`
			DROP COLUMN IF EXISTS inherit_import_frequency"
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

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

		return true;
	}
}
