<?php
/**
 * Database Migration Manager
 *
 * Handles database schema migrations between plugin versions.
 *
 * @package DonorCore\Database
 */

namespace DonorCore\Database;

defined( 'ABSPATH' ) || exit;

/**
 * Migration Manager Class
 */
class Migration_Manager {

	/**
	 * Schema installer instance.
	 *
	 * @var Schema_Installer
	 */
	private $installer;

	/**
	 * Constructor.
	 *
	 * @param Schema_Installer $installer Schema installer instance.
	 */
	public function __construct( Schema_Installer $installer = null ) {
		$this->installer = $installer ?? new Schema_Installer();
	}

	/**
	 * Run all pending migrations.
	 */
	public function run_migrations() {
		$current_version = get_option( Schema_Installer::DB_VERSION_KEY, '0' );
		$target_version  = Schema_Installer::DB_VERSION;

		// Already up to date.
		if ( version_compare( $current_version, $target_version, '>=' ) ) {
			return;
		}

		// Run migrations in order.
		$this->migrate_to_1_0_0( $current_version );

		// Future migrations would go here:
		// $this->migrate_to_1_1_0( $current_version );
		// $this->migrate_to_1_2_0( $current_version );

		// Update version.
		update_option( Schema_Installer::DB_VERSION_KEY, $target_version );
	}

	/**
	 * Migrate to version 1.0.0 (initial install).
	 *
	 * @param string $from_version Current version.
	 */
	private function migrate_to_1_0_0( $from_version ) {
		// Only run if migrating from pre-1.0.0.
		if ( version_compare( $from_version, '1.0.0', '>=' ) ) {
			return;
		}

		// Install all tables.
		$this->installer->install();

		// Log migration.
		$this->log_migration( '1.0.0', 'Initial database schema created' );
	}

	/**
	 * Example: Future migration to 1.1.0
	 *
	 * This is a template for future schema changes.
	 *
	 * @param string $from_version Current version.
	 */
	private function migrate_to_1_1_0( $from_version ) {
		// Only run if migrating from pre-1.1.0.
		if ( version_compare( $from_version, '1.1.0', '>=' ) ) {
			return;
		}

		global $wpdb;

		// Example: Add a new column to existing table.
		$table = $wpdb->prefix . 'donorcore_donation_logs';

		// Check if column exists first.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Schema check requires direct query
		$column_exists = $wpdb->get_results(
			$wpdb->prepare(
				'SHOW COLUMNS FROM %i LIKE %s',
				$table,
				'notes'
			)
		);

		if ( empty( $column_exists ) ) {
			// ALTER TABLE - Example future migration (template for reference)
			// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->query(
				// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.DirectDatabaseQuery.SchemaChange
				$wpdb->prepare(
					// phpcs:ignore PluginCheck.Security.DirectDB.SchemaChange, WordPress.DB.DirectDatabaseQuery.SchemaChange
					'ALTER TABLE %i ADD COLUMN notes TEXT DEFAULT NULL AFTER gateway',
					$table
				)
			);
		}

		$this->log_migration( '1.1.0', 'Added notes column to donation logs' );
	}

	/**
	 * Log migration to WordPress options.
	 *
	 * @param string $version Version migrated to.
	 * @param string $message Migration description.
	 */
	private function log_migration( $version, $message ) {
		$log = get_option( 'donor_core_migration_log', array() );

		$log[] = array(
			'version'   => $version,
			'message'   => $message,
			'timestamp' => current_time( 'mysql' ),
		);

		update_option( 'donor_core_migration_log', $log );
	}

	/**
	 * Get migration history.
	 *
	 * @return array
	 */
	public function get_migration_log() {
		return get_option( 'donor_core_migration_log', array() );
	}

	/**
	 * Rollback to a specific version (use with extreme caution).
	 *
	 * @param string $version Target version.
	 * @return bool Success status.
	 */
	public function rollback_to_version( $version ) {
		// This is a placeholder for future rollback functionality.
		// Rollbacks should be carefully designed per migration.
		
		// For now, just update the version marker.
		update_option( Schema_Installer::DB_VERSION_KEY, $version );

		return true;
	}
}
