<?php
/**
 * MW WP Form migration wizard admin page (free + Pro shared).
 *
 * Free: one-click conversion per form. Pro (via cf7mp_mw_bulk_enabled filter
 * and the cf7mp_mw_migration_pro_panel action): bulk conversion + data import.
 *
 * @package CF7MasterPro\Migration
 */

namespace CF7MasterPro\Migration;

defined( 'ABSPATH' ) || exit;

/**
 * Admin page: list MW WP Forms, run one-click conversion, show report.
 */
class MigrationPage {

	const PAGE_SLUG     = 'frontierline-forms-migration';
	const NONCE_ACTION  = 'cf7mp_mw_migrate';
	const MIGRATED_META = '_cf7mp_migrated_from';
	const DISMISS_META  = 'cf7mp_mw_notice_dismissed';

	/**
	 * Register hooks.
	 */
	public function register() {
		add_action( 'admin_menu', array( $this, 'add_menu' ), 20 );
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
		add_action( 'admin_notices', array( $this, 'maybe_detection_notice' ) );
	}

	/**
	 * Parent menu slug ('frontierline-forms' on free build, 'cf7-master' on Pro).
	 *
	 * @return string
	 */
	private function parent_slug() {
		if ( defined( '\CF7MasterPro\Admin\AdminMenu::MENU_SLUG' ) ) {
			return constant( '\CF7MasterPro\Admin\AdminMenu::MENU_SLUG' );
		}
		return 'cf7-master';
	}

	/**
	 * Whether bulk conversion / data import are unlocked (Pro).
	 *
	 * @return bool
	 */
	private function bulk_enabled() {
		return (bool) apply_filters( 'cf7mp_mw_bulk_enabled', false );
	}

	/**
	 * Add submenu under Frontierline Forms.
	 */
	public function add_menu() {
		add_submenu_page(
			$this->parent_slug(),
			__( 'MW WP Form Migration', 'frontierline-forms' ),
			__( 'MW WP Form Migration', 'frontierline-forms' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render' )
		);
	}

	/**
	 * Handle convert actions and notice dismissal.
	 */
	public function handle_actions() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Notice dismiss (plain link, no JS).
		if ( isset( $_GET['cf7mp_mw_dismiss'] ) && check_admin_referer( 'cf7mp_mw_dismiss' ) ) {
			update_user_meta( get_current_user_id(), self::DISMISS_META, 1 );
			wp_safe_redirect( remove_query_arg( array( 'cf7mp_mw_dismiss', '_wpnonce' ) ) );
			exit;
		}

		$single = ! empty( $_POST['cf7mp_mw_convert'] );
		$bulk   = ! empty( $_POST['cf7mp_mw_convert_all'] ) && $this->bulk_enabled();
		if ( ! $single && ! $bulk ) {
			return;
		}
		check_admin_referer( self::NONCE_ACTION );

		$args = array();
		if ( $single ) {
			$result = $this->run_conversion( (int) $_POST['cf7mp_mw_convert'] );
			$args   = is_wp_error( $result )
				? array( 'cf7mp_error' => rawurlencode( $result->get_error_message() ) )
				: array( 'cf7mp_done' => (int) $result );
		} else {
			$count    = 0;
			$migrated = $this->get_migrated_map();
			foreach ( $this->get_mw_forms() as $form ) {
				if ( isset( $migrated[ $form->ID ] ) ) {
					continue;
				}
				if ( ! is_wp_error( $this->run_conversion( $form->ID ) ) ) {
					$count++;
				}
			}
			$args = array( 'cf7mp_bulk_done' => $count );
		}

		wp_safe_redirect(
			add_query_arg( $args, admin_url( 'admin.php?page=' . self::PAGE_SLUG ) )
		);
		exit;
	}

	/**
	 * Convert one MW form and create the CF7 form.
	 *
	 * @param int $mw_id MW form post ID.
	 * @return int|\WP_Error New CF7 form post ID.
	 */
	private function run_conversion( $mw_id ) {
		if ( ! class_exists( '\WPCF7_ContactForm' ) ) {
			return new \WP_Error( 'cf7mp_no_cf7', __( 'Contact Form 7 is not active.', 'frontierline-forms' ) );
		}

		$converter = new MwConverter();
		$result    = $converter->convert( $mw_id );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$contact_form = \WPCF7_ContactForm::get_template(
			array(
				'title' => $result['title'] . ' ' . __( '(migrated)', 'frontierline-forms' ),
			)
		);
		$contact_form->set_properties(
			array(
				'form'   => $result['form'],
				'mail'   => $result['mail'],
				'mail_2' => $result['mail_2'],
			)
		);
		$saved = $contact_form->save();
		if ( ! $saved ) {
			return new \WP_Error( 'cf7mp_save_failed', __( 'Failed to create the Contact Form 7 form.', 'frontierline-forms' ) );
		}
		$cf7_post_id = $contact_form->id();

		update_post_meta( $cf7_post_id, self::MIGRATED_META, $mw_id );
		update_post_meta(
			$cf7_post_id,
			'_cf7mp_migration_report',
			array(
				'notes'     => $result['notes'],
				'renames'   => $result['renames'],
				'total'     => $result['total'],
				'converted' => $result['converted'],
				'time'      => current_time( 'mysql' ),
			)
		);

		$this->apply_plugin_settings( $result['settings'] );

		return $cf7_post_id;
	}

	/**
	 * Turn on the confirmation screen and inherit the complete message.
	 *
	 * @param array $mw_settings Converter settings extract.
	 */
	private function apply_plugin_settings( array $mw_settings ) {
		$settings = (array) get_option( 'cf7mp_settings', array() );

		$settings['enable_confirmation'] = 1;
		if ( empty( $settings['complete_message'] ) && '' !== trim( (string) $mw_settings['complete_message'] ) ) {
			$settings['complete_message'] = sanitize_textarea_field( wp_strip_all_tags( $mw_settings['complete_message'] ) );
		}

		update_option( 'cf7mp_settings', $settings );
	}

	/**
	 * Detection notice on relevant admin screens when MW WP Forms exist.
	 */
	public function maybe_detection_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen ) {
			return;
		}
		$own    = false !== strpos( (string) $screen->id, 'frontierline-forms' ) || false !== strpos( (string) $screen->id, 'cf7-master' );
		$global = in_array( $screen->id, array( 'dashboard', 'plugins' ), true );
		if ( ( ! $own && ! $global ) || false !== strpos( (string) $screen->id, self::PAGE_SLUG ) ) {
			return;
		}
		if ( get_user_meta( get_current_user_id(), self::DISMISS_META, true ) ) {
			return;
		}
		if ( ! $this->get_mw_forms( 1 ) ) {
			return;
		}

		$wizard_url  = admin_url( 'admin.php?page=' . self::PAGE_SLUG );
		$dismiss_url = wp_nonce_url( add_query_arg( 'cf7mp_mw_dismiss', 1 ), 'cf7mp_mw_dismiss' );
		printf(
			'<div class="notice notice-info"><p><strong>%s</strong> %s <a href="%s" class="button button-primary" style="margin-left:8px;">%s</a> <a href="%s" style="margin-left:8px;">%s</a></p></div>',
			esc_html__( 'MW WP Form detected.', 'frontierline-forms' ),
			esc_html__( 'MW WP Form is no longer actively developed. Frontierline Forms can convert your forms to Contact Form 7 with one click (confirmation screen included).', 'frontierline-forms' ),
			esc_url( $wizard_url ),
			esc_html__( 'Open Migration Wizard', 'frontierline-forms' ),
			esc_url( $dismiss_url ),
			esc_html__( 'Dismiss', 'frontierline-forms' )
		);
	}

	/**
	 * Fetch MW WP Form posts (works even when MW WP Form is deactivated).
	 *
	 * @param int $limit Max posts.
	 * @return array
	 */
	private function get_mw_forms( $limit = 200 ) {
		global $wpdb;
		$rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- MW WP Form may be deactivated; its CPT is unregistered so WP_Query cannot be used.
			$wpdb->prepare(
				"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status IN ('publish','draft','pending','private') ORDER BY ID ASC LIMIT %d",
				MwConverter::MW_CPT,
				$limit
			)
		);
		$posts = array();
		foreach ( (array) $rows as $row ) {
			$post = get_post( (int) $row->ID );
			if ( $post ) {
				$posts[] = $post;
			}
		}
		return $posts;
	}

	/**
	 * Already-converted map: mw_id => CF7 post ID.
	 *
	 * @return array
	 */
	public function get_migrated_map() {
		global $wpdb;
		$rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Small meta lookup for the wizard screen.
			$wpdb->prepare(
				"SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s",
				self::MIGRATED_META
			)
		);
		$map = array();
		foreach ( (array) $rows as $row ) {
			if ( 'publish' === get_post_status( (int) $row->post_id ) ) {
				$map[ (int) $row->meta_value ] = (int) $row->post_id;
			}
		}
		return $map;
	}

	/**
	 * Render the wizard.
	 */
	public function render() {
		$forms    = $this->get_mw_forms();
		$migrated = $this->get_migrated_map();

		$rows = array();
		foreach ( $forms as $form ) {
			$rows[] = array(
				'id'         => $form->ID,
				'title'      => '' !== $form->post_title ? $form->post_title : sprintf( '#%d', $form->ID ),
				'data_count' => MwConverter::count_saved_data( $form->ID ),
				'cf7_id'     => $migrated[ $form->ID ] ?? 0,
			);
		}

		$done_id = isset( $_GET['cf7mp_done'] ) ? (int) $_GET['cf7mp_done'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$report  = $done_id ? get_post_meta( $done_id, '_cf7mp_migration_report', true ) : null;

		$upgrade_url = '';
		if ( function_exists( 'cf7mp_fs' ) && cf7mp_fs() ) {
			$upgrade_url = cf7mp_fs()->get_upgrade_url();
		}

		$vars = array(
			'rows'         => $rows,
			'done_id'      => $done_id,
			'done_title'   => $done_id ? get_the_title( $done_id ) : '',
			'report'       => is_array( $report ) ? $report : array(),
			'bulk_done'    => isset( $_GET['cf7mp_bulk_done'] ) ? (int) $_GET['cf7mp_bulk_done'] : -1, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			'imported'     => isset( $_GET['cf7mp_imported'] ) ? (int) $_GET['cf7mp_imported'] : -1, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			'skipped'      => isset( $_GET['cf7mp_skipped'] ) ? (int) $_GET['cf7mp_skipped'] : 0, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			'error'        => isset( $_GET['cf7mp_error'] ) ? sanitize_text_field( rawurldecode( wp_unslash( $_GET['cf7mp_error'] ) ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			'bulk_enabled' => $this->bulk_enabled(),
			'upgrade_url'  => $upgrade_url,
			'nonce_field'  => wp_nonce_field( self::NONCE_ACTION, '_wpnonce', true, false ),
		);

		$file = CF7MP_PLUGIN_DIR . 'templates/admin/migration.php';
		if ( ! file_exists( $file ) ) {
			echo '<div class="notice notice-error"><p>Template not found: migration</p></div>';
			return;
		}
		extract( $vars, EXTR_SKIP ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract
		include $file;
	}
}
