<?php
/**
 * One-off migration flags (non-autoloaded).
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class Migrations {

	public static function has_run( string $migration ): bool {
		$run = get_option( 'cartcue_migrations_completed', [] );
		return is_array( $run ) && in_array( $migration, $run, true );
	}

	public static function mark_run( string $migration ): void {
		$run = (array) get_option( 'cartcue_migrations_completed', [] );
		if ( in_array( $migration, $run, true ) ) {
			return;
		}
		$run[] = $migration;
		update_option( 'cartcue_migrations_completed', $run, false );
	}

	/**
	 * Import legacy per-flag options into the consolidated list, then delete them.
	 */
	public static function import_legacy_flags(): void {
		if ( self::has_run( 'legacy_flags_imported' ) ) {
			return;
		}

		if ( get_option( 'cartcue_legacy_card_cron_cleared' ) ) {
			self::mark_run( 'legacy_card_cron_cleared' );
			delete_option( 'cartcue_legacy_card_cron_cleared' );
		}

		$rewrite_v = get_option( 'cartcue_rewrite_flushed_v' );
		if ( is_string( $rewrite_v ) && '' !== $rewrite_v ) {
			self::mark_run( 'rewrite_flushed_' . $rewrite_v );
			delete_option( 'cartcue_rewrite_flushed_v' );
		}

		self::mark_run( 'legacy_flags_imported' );
	}

	/**
	 * Reset audience rules that were overwritten by branch-step save bug (Pro plays with sequences).
	 */
	public static function repair_corrupted_branch_audience_rules(): void {
		if ( self::has_run( 'branch_audience_rules_repaired' ) ) {
			return;
		}
		if ( ! defined( 'CARTCUE_PRO_VERSION' ) ) {
			self::mark_run( 'branch_audience_rules_repaired' );
			return;
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				'SELECT id, rules, sequence FROM %i WHERE sequence IS NOT NULL AND sequence != %s AND sequence != %s',
				DB::workflows(),
				'',
				'[]'
			),
			ARRAY_A
		) ?: [];

		foreach ( $rows as $row ) {
			$sequence = json_decode( (string) ( $row['sequence'] ?? '' ), true );
			if ( ! is_array( $sequence ) || empty( $sequence ) ) {
				continue;
			}

			$last_branch_rules = null;
			foreach ( $sequence as $step ) {
				if ( ! is_array( $step ) || 'branch' !== ( $step['step_type'] ?? '' ) ) {
					continue;
				}
				if ( ! empty( $step['rules'] ) && is_array( $step['rules'] ) ) {
					$last_branch_rules = $step['rules'];
				}
			}
			if ( null === $last_branch_rules ) {
				continue;
			}

			$saved_rules = json_decode( (string) ( $row['rules'] ?? '' ), true );
			if ( ! is_array( $saved_rules ) || empty( $saved_rules ) ) {
				continue;
			}
			if ( wp_json_encode( $saved_rules ) !== wp_json_encode( $last_branch_rules ) ) {
				continue;
			}

			// phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->update(
				DB::workflows(),
				[ 'rules' => '[]', 'updated_at' => current_time( 'mysql' ) ],
				[ 'id' => (int) $row['id'] ],
				[ '%s', '%s' ],
				[ '%d' ]
			);
		}

		self::mark_run( 'branch_audience_rules_repaired' );
	}
}
