<?php
/**
 * Costudio_Standalone_Migrator
 *
 * Handles data migration between standalone Contentosapp Studio and the shared core.
 * NOTE: For the initial global launch, ContentOS Core is hidden, so this
 * migrator is disabled to prevent user confusion.
 *
 * @package Contentosapp_Studio
 * @since   3.0.0
 */

defined( 'ABSPATH' ) || exit;

class Costudio_Standalone_Migrator {

    private const DISMISSED_OPTION = 'costudio_core_migration_dismissed';

    /** @var self|null Singleton instance. */
    private static ?self $instance = null;

    /** @return self */
    public static function get_instance(): self {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Entry point for migration logic.
     * Disabled for current global launch.
     */
    public function init(): void {
        // Migration logic is hidden to focus on Contentosapp Studio Standalone.
    }

    /**
     * Hook target used when ContentOS Core is active.
     *
     * The actual migration is intentionally disabled for the current standalone
     * launch, but this method must exist because contentosapp-studio.php registers it in
     * Migration Mode. Keeping it as a safe no-op prevents fatal errors on sites
     * where ContentOS Core is installed.
     */
    public static function maybe_import_to_core(): void {
        self::get_instance()->init();
    }

    /**
     * Admin POST target for the disabled import flow.
     */
    public static function import_to_core(): void {
        self::assert_admin();
        self::verify_admin_post();
        self::redirect_with_status( 'disabled' );
    }

    /**
     * Dismiss the migration notice/page for the current standalone launch.
     */
    public static function dismiss_import(): void {
        self::assert_admin();
        self::verify_admin_post();
        update_option( self::DISMISSED_OPTION, 1, false );
        self::redirect_with_status( 'dismissed' );
    }

    /**
     * Reset the local dismissal flag.
     */
    public static function reset_migration(): void {
        self::assert_admin();
        self::verify_admin_post();
        delete_option( self::DISMISSED_OPTION );
        self::redirect_with_status( 'reset' );
    }

    /**
     * Render a safe migration screen instead of exposing an incomplete import.
     */
    public static function render_migration_page(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'contentosapp-studio' ) );
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin notice state; state changes use admin-post nonces.
        $status    = isset( $_GET['costudio_migration_status'] ) ? sanitize_key( wp_unslash( $_GET['costudio_migration_status'] ) ) : '';
        $dismissed = (bool) get_option( self::DISMISSED_OPTION, false );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Contentosapp Studio Migration', 'contentosapp-studio' ); ?></h1>

            <?php if ( $status === 'disabled' ) : ?>
                <div class="notice notice-info is-dismissible">
                    <p><?php esc_html_e( 'Contentosapp Studio migration to ContentOS Core is disabled for the current standalone launch.', 'contentosapp-studio' ); ?></p>
                </div>
            <?php elseif ( $status === 'dismissed' ) : ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php esc_html_e( 'Migration notice dismissed.', 'contentosapp-studio' ); ?></p>
                </div>
            <?php elseif ( $status === 'reset' ) : ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php esc_html_e( 'Migration notice reset.', 'contentosapp-studio' ); ?></p>
                </div>
            <?php endif; ?>

            <div class="card" style="max-width: 760px;">
                <h2><?php esc_html_e( 'Standalone mode is active', 'contentosapp-studio' ); ?></h2>
                <p>
                    <?php esc_html_e( 'ContentOS Core was detected, so Contentosapp Studio entered its migration-safe mode. The import workflow is intentionally unavailable in this release to avoid moving data through an incomplete migration path.', 'contentosapp-studio' ); ?>
                </p>
                <p>
                    <?php esc_html_e( 'Your existing Contentosapp Studio data remains in place. When the Core migration is ready, this screen can be replaced with the real importer.', 'contentosapp-studio' ); ?>
                </p>

                <p>
                    <a class="button button-primary" href="<?php echo esc_url( self::admin_post_url( 'costudio_import_to_core' ) ); ?>">
                        <?php esc_html_e( 'Check migration availability', 'contentosapp-studio' ); ?>
                    </a>

                    <?php if ( $dismissed ) : ?>
                        <a class="button" href="<?php echo esc_url( self::admin_post_url( 'costudio_reset_migration' ) ); ?>">
                            <?php esc_html_e( 'Reset dismissal', 'contentosapp-studio' ); ?>
                        </a>
                    <?php else : ?>
                        <a class="button" href="<?php echo esc_url( self::admin_post_url( 'costudio_dismiss_import' ) ); ?>">
                            <?php esc_html_e( 'Dismiss for now', 'contentosapp-studio' ); ?>
                        </a>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <?php
    }

    private static function assert_admin(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to perform this action.', 'contentosapp-studio' ) );
        }
    }

    private static function admin_post_url( string $action ): string {
        return wp_nonce_url(
            admin_url( 'admin-post.php?action=' . rawurlencode( $action ) ),
            $action
        );
    }

    private static function verify_admin_post(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The action determines the matching admin-post nonce checked immediately below.
        $action = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : '';
        if ( $action !== '' ) {
            check_admin_referer( $action );
        }
    }

    private static function redirect_with_status( string $status ): void {
        wp_safe_redirect(
            add_query_arg(
                [
                    'page'                       => 'contentos-costudio-migration',
                    'costudio_migration_status' => sanitize_key( $status ),
                ],
                admin_url( 'admin.php' )
            )
        );
        exit;
    }
}
