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

namespace EasyInvoice\Migration;

/**
 * Migration initialization class.
 *
 * Handles all migration system initialization and setup.
 *
 * @since 2.0.0
 */
class MigrationInit {

    /**
     * Initialize the complete migration system.
     *
     * @since 2.0.0
     * @return void
     */
        public static function init() {
        // Add admin notices and migration page
        add_action('admin_notices', [__CLASS__, 'show_migration_notice']);
        add_action('admin_menu', [__CLASS__, 'add_migration_page'], 20);
        add_action('admin_menu', [__CLASS__, 'hide_migration_menu'], 999);
        add_action('admin_init', [__CLASS__, 'handle_migration_redirect']);
                
        // Only initialize migration loader if needed
        if (self::should_initialize_migration()) {
            MigrationLoader::init();
        }
    }

    /**
     * Check if migration should be initialized.
     *
     * @since 2.0.0
     * @return bool
     */
    private static function should_initialize_migration(): bool {
        // Check if we're in admin area
        if (!is_admin()) {
            return false;
        }

        // Check if migration is needed
        $version_checker = VersionChecker::get_instance();
        return $version_checker->is_migration_needed();
    }

    /**
     * Show migration notice in admin.
     *
     * @since 2.0.0
     * @return void
     */
    public static function show_migration_notice() {
        // Only show in admin area
        if (!is_admin()) {
            return;
        }

        // Check if migration is already completed
        $version_checker = VersionChecker::get_instance();
        if ($version_checker->is_migration_completed()) {
            return;
        }

        // Check if migration is needed
        if (!$version_checker->is_migration_needed()) {
            return;
        }

        // Additional check: if this appears to be a fresh installation,
        // automatically mark it as completed and don't show notice
        if ($version_checker->is_fresh_installation()) {
            $version_checker->mark_fresh_installation_completed();
            return;
        }

        // Get current screen
        $screen = get_current_screen();

        // Determine notice class based on screen
        $notice_class = 'notice-warning';
        if ($screen && property_exists($screen, 'id') && strpos($screen->id, 'easy-invoice') !== false) {
            $notice_class = 'notice-error';
        }

        ?>
        <div class="notice <?php echo esc_attr($notice_class); ?> is-dismissible">
            <p>
                <strong><?php esc_html_e('Easy Invoice Migration Required', 'easy-invoice'); ?></strong>
                <br>
                <?php esc_html_e('Your Easy Invoice plugin needs to be migrated to version 2.0.0. This will update your data structure and ensure compatibility with the new version.', 'easy-invoice'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice-migration')); ?>" class="button button-primary">
                    <?php esc_html_e('Run Migration', 'easy-invoice'); ?>
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=easy-invoice-migration&action=skip')); ?>" class="button button-secondary">
                    <?php esc_html_e('Skip for Now', 'easy-invoice'); ?>
                </a>
            </p>
        </div>
        <?php
    }

        /**
     * Add migration page to admin menu.
     * 
     * @since 2.0.0
     * @return void
     */
    public static function add_migration_page() {
        $version_checker = VersionChecker::get_instance();
        
        if ($version_checker->is_migration_needed()) {
            // Show migration menu when migration is needed
            add_submenu_page(
                'easy-invoice',
                __('Easy Invoice Migration', 'easy-invoice'),
                __('Migration', 'easy-invoice'),
                'manage_options',
                'easy-invoice-migration',
                [__CLASS__, 'render_migration_page_handler']
            );
        } else {
            // Register page without parent menu when migration is not needed
            add_submenu_page(
                'null', // No parent menu
                __('Easy Invoice Migration', 'easy-invoice'),
                __('Migration', 'easy-invoice'),
                'manage_options',
                'easy-invoice-migration',
                [__CLASS__, 'render_migration_page_handler']
            );
        }
    }
    
    /**
     * Hide migration menu if not needed.
     * 
     * @since 2.0.0
     * @return void
     */
    public static function hide_migration_menu() {
        $version_checker = VersionChecker::get_instance();
        if (!$version_checker->is_migration_needed()) {
            //remove_submenu_page('easy-invoice', 'easy-invoice-migration');
        }
    }

        /**
     * Render migration page.
     *
     * @since 2.0.0
     * @return void
     */
    public static function render_migration_page_handler() {
        // Check if user has permissions
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'easy-invoice'));
        }

        // Ensure page is set properly
        if (!isset($_GET['page'])) {
            $_GET['page'] = 'easy-invoice-migration';
        }

        // Set a proper page title to avoid WordPress core issues
        add_filter('admin_title', function($title) {
            return __('Easy Invoice Migration', 'easy-invoice') . ' - ' . get_bloginfo('name');
        });

        // Include the main template with sidebar
        include EASY_INVOICE_PLUGIN_DIR . 'templates/main-template.php';
    }

    /**
     * Handle migration redirect.
     *
     * @since 2.0.0
     * @return void
     */
    public static function handle_migration_redirect() {
        if (isset($_GET['page']) && $_GET['page'] === 'easy-invoice-migration') {
            // Handle skip action
            if (isset($_GET['action']) && $_GET['action'] === 'skip') {
                update_option('easy_invoice_migration_skipped', true);
                wp_redirect(admin_url('admin.php?page=easy-invoice'));
                exit;
            }

            // Enqueue migration assets
            wp_enqueue_style(
                'easy-invoice-migration',
                EASY_INVOICE_PLUGIN_URL . 'includes/Migration/assets/migration.css',
                [],
                EASY_INVOICE_VERSION
            );

            wp_enqueue_script(
                'easy-invoice-migration',
                EASY_INVOICE_PLUGIN_URL . 'includes/Migration/assets/migration.js',
                ['jquery'],
                EASY_INVOICE_VERSION,
                true
            );

            wp_localize_script('easy-invoice-migration', 'easyInvoiceMigration', [
                'nonce' => wp_create_nonce('easy_invoice_migration_nonce'),
                'ajaxurl' => admin_url('admin-ajax.php'),
            ]);
        }
    }
}
