<?php
/**
 * Data Cleanup Migration for Easy Invoice
 *
 * @package     EasyInvoice
 * @subpackage  Migration
 * @since       2.0.0
 */

namespace EasyInvoice\Migration\Src;

/**
 * Data Cleanup Migration Class
 *
 * Handles post-migration data management.
 *
 * @since 2.0.0
 */
class DataCleanupMigration extends AbstractMigration {

    /**
     * Migration description.
     *
     * @since 2.0.0
     * @var string
     */
    protected $description = 'Finalize migration (preserves old data)';

    /**
     * Check if cleanup is needed.
     *
     * @since 2.0.0
     * @return bool
     */
    public function is_needed(): bool {
        // Always return true as we need to finalize the migration
        return true;
    }

    /**
     * Run the cleanup.
     *
     * @since 2.0.0
     * @param array $options Cleanup options
     * @return array
     */
    public function migrate(array $options = []): array {
        $this->log('Finalizing migration (old data preserved)');

        try {
            // Mark migration as completed
            update_option('easy_invoice_migration_completed', true);
            update_option('easy_invoice_migration_completed_time', current_time('mysql'));

            // Ensure version is bumped to target version when migration finalizes
            if (defined('EASY_INVOICE_VERSION')) {
                update_option('easy_invoice_version', EASY_INVOICE_VERSION);
            }

            // Store migration summary
            $summary = [
                'completed_at' => current_time('mysql'),
                'old_data_preserved' => true,
                'version_migrated_from' => get_option('easy_invoice_version', '1.0.0'),
                'version_migrated_to' => defined('EASY_INVOICE_VERSION') ? EASY_INVOICE_VERSION : '2.0.0'
            ];
            update_option('easy_invoice_migration_summary', $summary);

            $this->log('Migration finalized successfully. Old data has been preserved.');

            return [
                'success' => true,
                'message' => 'Migration finalized successfully. Old data has been preserved.',
                'summary' => $summary
            ];

        } catch (\Exception $e) {
            $this->log('Failed to finalize migration: ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to finalize migration: ' . $e->getMessage()
            ];
        }
    }
}
