<?php

/**
 * Plugin Name:       Minimal Demo Importer (Flat Structure)
 * Plugin URI:        https://example.com/
 * Description:       A minimal plugin to import demo content from a specific XML file with a single click. All files in root.
 * Version:           1.1.0
 * Author:            Your Name
 * Author URI:        https://example.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       minimal-demo-importer
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
	die;
}

/**
 * Adds the importer page to the admin menu.
 */
function mdi_add_admin_menu()
{
	add_menu_page(
		'Demo Importer',          // Page Title
		'Demo Importer',          // Menu Title
		'manage_options',         // Capability
		'minimal_demo_importer',  // Menu Slug
		'mdi_render_importer_page', // Callback function to render the page
		'dashicons-download',     // Icon
		80                        // Position
	);
}
add_action('admin_menu', 'mdi_add_admin_menu');

/**
 * Renders the importer page content.
 */
function mdi_render_importer_page()
{
?>
	<div class="wrap">
		<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
		<p>Click the button below to import the demo content. This process may take a few minutes. Please do not close this window.</p>

		<button id="mdi-import-button" class="button button-primary">Import Demo Content</button>

		<div id="mdi-feedback" style="margin-top: 20px; padding: 10px; background-color: #f7f7f7; border: 1px solid #ccc; display: none; max-height: 400px; overflow-y: auto;">
			<!-- Feedback will be shown here -->
		</div>
	</div>
<?php
}

/**
 * Enqueues the necessary JavaScript for the importer page.
 *
 * @param string $hook The current admin page hook.
 */
function mdi_enqueue_scripts($hook)
{
	// Only load our script on our plugin's page.
	if ('toplevel_page_minimal_demo_importer' !== $hook) {
		return;
	}

	wp_enqueue_script(
		'mdi-importer-script',
		plugin_dir_url(__FILE__) . 'cardealer-importer.js', // This is correct for a root file.
		['jquery'],
		'1.1.0',
		true
	);

	wp_localize_script(
		'mdi-importer-script',
		'mdi_ajax_obj',
		[
			'ajax_url'    => admin_url('admin-ajax.php'),
			'nonce'       => wp_create_nonce('mdi_import_nonce'),
		]
	);
}
add_action('admin_enqueue_scripts', 'mdi_enqueue_scripts');


/**
 * Handles the AJAX request to perform the import.
 */
function mdi_handle_ajax_import_old()
{
	// 1. Security Check
	check_ajax_referer('mdi_import_nonce', '_ajax_nonce');

	if (!current_user_can('import')) {
		wp_send_json_error('Error: You do not have permission to import content.', 403);
		return;
	}

	// 2. Define path to the XML file.
	// CORRECTED: Removed the leading slash from the filename.
	$xml_file_path = plugin_dir_path(__FILE__) . 'car-dealer-demo-data.xml';

	if (!file_exists($xml_file_path)) {
		wp_send_json_error('Error: The demo data file (car-dealer-demo-data.xml) could not be found in the plugin root directory.');
		return;
	}

	// 3. Load the importer classes.
	if (!defined('WP_LOAD_IMPORTERS')) {
		define('WP_LOAD_IMPORTERS', true);
	}

	if (!class_exists('WP_Importer')) {
		$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
		if (file_exists($class_wp_importer)) {
			require $class_wp_importer;
		} else {
			wp_send_json_error('Error: WP_Importer class not found.');
			return;
		}
	}

	if (!class_exists('WP_Import')) {
		// Path is correct for a file in the plugin root.
		$class_wp_import = plugin_dir_path(__FILE__) . 'wordpress-importer.php';
		if (file_exists($class_wp_import)) {
			require $class_wp_import;
		} else {
			wp_send_json_error('Error: WP_Import class not found in the plugin root directory.');
			return;
		}
	}

	// Path is correct for a file in the plugin root.
	$parsers_file = plugin_dir_path(__FILE__) . 'parsers.php';
	if (file_exists($parsers_file)) {
		require_once $parsers_file;
	}


	try {
		ob_start();

		// 4. Run the importer
		$importer = new WP_Import();
		$importer->fetch_attachments = true;
		$importer->import($xml_file_path);

		$output = ob_get_clean();

		// 5. Send success response.
		wp_send_json_success('Import process finished. <br><br><strong>Log:</strong><pre>' . esc_html($output) . '</pre>');
	} catch (Exception $e) {
		ob_end_clean();
		wp_send_json_error('An error occurred during import: ' . $e->getMessage());
	}

	wp_die();
}
//add_action('wp_ajax_mdi_do_import', 'mdi_handle_ajax_import');

/**
 * Handles the AJAX request to perform the import.
 */
function mdi_handle_ajax_import()
{
	// ... (passos 1, 2 e 3 permanecem exatamente os mesmos) ...

	// 1. Security Check
	check_ajax_referer('mdi_import_nonce', '_ajax_nonce');

	if (!current_user_can('import')) {
		wp_send_json_error('Error: You do not have permission to import content.', 403);
		return;
	}

	// 2. Define path to the XML file.
	$xml_file_path = plugin_dir_path(__FILE__) . 'car-dealer-demo-data.xml';

	if (!file_exists($xml_file_path)) {
		wp_send_json_error('Error: The demo data file (car-dealer-demo-data.xml) could not be found in the plugin root directory.');
		return;
	}

	// 3. Load the importer classes.
	if (!defined('WP_LOAD_IMPORTERS')) {
		define('WP_LOAD_IMPORTERS', true);
	}

	if (!class_exists('WP_Importer')) {
		$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
		if (file_exists($class_wp_importer)) {
			require $class_wp_importer;
		} else {
			wp_send_json_error('Error: WP_Importer class not found.');
			return;
		}
	}

	if (!class_exists('WP_Import')) {
		$class_wp_import = plugin_dir_path(__FILE__) . 'wordpress-importer.php';
		if (file_exists($class_wp_import)) {
			require $class_wp_import;
		} else {
			wp_send_json_error('Error: WP_Import class not found in the plugin root directory.');
			return;
		}
	}

	$parsers_file = plugin_dir_path(__FILE__) . 'parsers.php';
	if (file_exists($parsers_file)) {
		require_once $parsers_file;
	}


	try {
		ob_start();

		// 4. Run the importer
		$importer = new WP_Import();
		$importer->fetch_attachments = true;
		$importer->import($xml_file_path);

		$output = ob_get_clean();

		// 5. Filter the output and send the success response.
		// =======================================================
		//  AQUI ESTÁ A MUDANÇA
		// =======================================================

		// Remove any line that contains the "already exists" message.
		$filtered_output = preg_replace('/^.* already exists\..*$/m', '', $output);

		// Trim any resulting empty lines for a cleaner look.
		$filtered_output = trim($filtered_output);

		// Prepare a user-friendly message
		$success_message = '<strong>Import process finished successfully!</strong>';

		// If there's any other relevant output from the importer, show it.
		if (!empty($filtered_output)) {
			$success_message .= '<br><br><strong>Log:</strong><pre>' . esc_html($filtered_output) . '</pre>';
		}

		wp_send_json_success($success_message);
	} catch (Exception $e) {
		ob_end_clean();
		wp_send_json_error('An error occurred during import: ' . $e->getMessage());
	}

	wp_die();
}
add_action('wp_ajax_mdi_do_import', 'mdi_handle_ajax_import');
