<?php
/**
 * One Click Demo Import plugin integration.
 *
 * @package ComRepair
 */

add_filter( 'pt-ocdi/import_files', 'comrepair_import_config' );
add_filter( 'pt-ocdi/timeout_for_downloading_import_file', 'comrepair_import_file_download_timeout' );

add_action( 'wp_import_insert_term', 'comrepair_import_add_menu_to_mapping', 10, 2 );
add_action( 'wp_import_insert_post', 'comrepair_import_add_post_to_mapping', 10, 2 );

add_action( 'pt-ocdi/after_import', 'comrepair_import_replace_urls' );
add_action( 'pt-ocdi/after_import', 'comrepair_import_replace_nav_menus_atts' );
add_action( 'pt-ocdi/after_import', 'comrepair_import_delete_mappings' );

add_action( 'pt-ocdi/after_import', 'comrepair_import_set_nav_menu_locations' );
add_action( 'pt-ocdi/after_import', 'comrepair_import_set_static_homepage' );
add_action( 'pt-ocdi/after_import', 'comrepair_import_update_revslider_settings' );
add_action( 'pt-ocdi/after_import', 'comrepair_import_revslider_all' );

function comrepair_import_config() {
	$demo_source = 'https://dl.brothersthemes.com/import/comrepair/';
	$upload_dir = wp_upload_dir();
	return array(
		array(
			'import_file_name'           => esc_html__( 'ComRepair Demo Content', 'comrepair' ),
			'import_file_url'            => $demo_source . '/demo-content.xml',
			'import_customizer_file_url' => $demo_source . '/demo-customizer.dat',
			'import_widget_file_url'     => $demo_source . '/demo-widgets.wie',
			'import_revslider_file_urls' => array(
				'home-slider-1' => $demo_source . '/home-slider-1.zip',
				'home-slider-2' => $demo_source . '/home-slider-2.zip',
				'home-slider-3' => $demo_source . '/home-slider-3.zip',
				'home-slider-4' => $demo_source . '/home-slider-4.zip',
			),
			'import_nav_menu_locations'  => array(
				'primary-menu'   => array( 'primary' ),
				'secondary-menu' => array( 'secondary' ),
				'social-menu'    => array( 'top-bar-social', 'footer-social' ),
			),
			'import_replace_urls'        => array(
				'https://demo.brothersthemes.com/comrepair/wp-content/uploads/sites/2/' => trailingslashit( $upload_dir['baseurl'] ),
				'https://demo.brothersthemes.com/comrepair/'                            => home_url( '/' ),
			),
		),
	);
}

function comrepair_import_file_download_timeout() {
	return 120; // seconds
}

function comrepair_import_get_mappings() {
	$mappings = get_transient( 'comrepair_import_mappings' );
	if ( ! is_array( $mappings ) ) {
		$mappings = array(
			'post_id'     => array(),
			'nav_menu_id' => array(),
		);
	}
	return $mappings;
}

function comrepair_import_save_mappings( $mappings ) {
	set_transient( 'comrepair_import_mappings', $mappings, 0.1 * HOUR_IN_SECONDS );
}

function comrepair_import_delete_mappings() {
	delete_transient( 'comrepair_import_mappings' );
}

function comrepair_import_add_menu_to_mapping( $term_id, $data ) {
	if ( 'nav_menu' !== $data['taxonomy'] || ! isset( $data['id'] ) ) {
		return;
	}

	$original_id = $data['id'];
	$new_id = $term_id;
	$mappings = comrepair_import_get_mappings();
	$mappings['nav_menu_id'][ $original_id ] = $new_id;
	comrepair_import_save_mappings( $mappings );
}

function comrepair_import_add_post_to_mapping( $post_id, $original_id ) {
	$mappings = comrepair_import_get_mappings();
	$mappings['post_id'][ $original_id ] = $post_id;
	comrepair_import_save_mappings( $mappings );
}

function comrepair_import_replace_urls( $import_config ) {
	$search = array_keys( $import_config['import_replace_urls'] );
	$search = array_merge( $search, array_map( 'rawurlencode', $search ) );
	$replace = array_values( $import_config['import_replace_urls'] );
	$replace = array_merge( $replace, array_map( 'rawurlencode', $replace ) );

	// Replace in imported posts content
	$mappings = comrepair_import_get_mappings();
	foreach ( $mappings['post_id'] as $post_id ) {
		$post = get_post( $post_id );
		$content = $post->post_content;
		$new_content = str_replace( $search, $replace, $content );
		if ( $new_content !== $content ) {
			wp_update_post( array( 'ID' => $post_id, 'post_content' => $new_content ) );
		}
	}

	// Replace in text widgets content
	$widget_text = get_option( 'widget_text' );
	$widget_text = comrepair_recursive_replace( $search, $replace, $widget_text );
	update_option( 'widget_text', $widget_text );
}

function comrepair_import_replace_nav_menus_atts() {
	$mappings = comrepair_import_get_mappings();
	if ( empty( $mappings['nav_menu_id'] ) || empty( $mappings['post_id'] ) ) {
		return;
	}

	$old_atts = array();
	$new_atts = array();
	foreach ( $mappings['nav_menu_id'] as $old_id => $new_id ) {
		$old_atts[] = " nav_menu=\"$old_id\"";
		$new_atts[] = " nav_menu=\"$new_id\"";
	}

	foreach ( $mappings['post_id'] as $post_id ) {
		$post = get_post( $post_id );
		$content = $post->post_content;
		$new_content = str_replace( $old_atts, $new_atts, $content );
		if ( $new_content !== $content ) {
			wp_update_post( array( 'ID' => $post_id, 'post_content' => $new_content ) );
		}
	}
}

function comrepair_import_set_nav_menu_locations( $import_config ) {
	if ( ! isset( $import_config['import_nav_menu_locations'] ) ) {
		return;
	}

	$menu_locations = array();
	foreach ( $import_config['import_nav_menu_locations'] as $slug => $locations ) {
		if ( $menu_term = get_term_by( 'slug', $slug, 'nav_menu' ) ) {
			foreach ( $locations as $location ) {
				$menu_locations[ $location ] = $menu_term->term_id;
			}
		}
	}
	set_theme_mod( 'nav_menu_locations', $menu_locations );
}

function comrepair_import_set_static_homepage() {
	$front_page = get_page_by_title( 'Home 1' );
	$blog_page  = get_page_by_title( 'Blog' );
	update_option( 'show_on_front', 'page' );
	update_option( 'page_on_front', $front_page->ID );
	update_option( 'page_for_posts', $blog_page->ID );
}

function comrepair_import_update_revslider_settings() {
	// Check if Revolution Slider plugin is active
	if ( ! class_exists( 'RevSlider' ) || ! class_exists( 'RevSliderOperations' ) ) {
		return;
	}

	// Check that the required API is available
	$operations = new RevSliderOperations();
	if ( ! method_exists( $operations, 'getGeneralSettingsValues' ) || ! method_exists( $operations, 'updateGeneralSettings' ) ) {
		return;
	}

	$responsive_widths = array(
		'width'          => 1400,
		'width_notebook' => 1200,
		'width_tablet'   => 992,
		'width_mobile'   => 768,
	);

	$global_settings = $operations->getGeneralSettingsValues();
	if ( ! is_array( $global_settings ) ) {
		$global_settings = array();
	}
	$global_settings = array_merge( $global_settings, $responsive_widths );
	$operations->updateGeneralSettings( $global_settings );
}

function comrepair_import_revslider_all( $import_config ) {
	if ( ! isset( $import_config['import_revslider_file_urls'] ) ) {
		return;
	}

	foreach ( $import_config['import_revslider_file_urls'] as $alias => $url ) {
		comrepair_import_revslider_single( $alias, $url );
	}
}

function comrepair_import_revslider_single( $alias, $file_url ) {
	if ( empty( $file_url ) || ! class_exists( 'RevSlider' ) || RevSlider::isAliasExists( $alias ) ) {
		return;
	}

	if ( strpos( $file_url, 'http://' ) === false && strpos( $file_url, 'https://' ) === false ) {
		$revslider = new RevSlider();
		$revslider->importSliderFromPost( true, true, $file_url );
		return;
	}

	$wp_filesystem = comrepair_init_wp_filesystem();
	if ( ! $wp_filesystem ) {
		return;
	}

	// Fetch the import zip file for this slider.
	$response = wp_remote_get( $file_url, array( 'timeout' => 20 ) );
	if ( is_wp_error( $response ) || 200 !== $response['response']['code'] ) {
		return;
	}

	// Save the fetched file into a temporary location.
	$upload_dir = wp_upload_dir();
	$upload_path = trailingslashit( $upload_dir['path'] );
	$timestamp = date( 'Y-m-d__H-i-s' );
	$file_path = $upload_path . 'demo-revslider-import-file_' . $timestamp . '.zip';
	$file_content = wp_remote_retrieve_body( $response );
	if ( ! $wp_filesystem->put_contents( $file_path, $file_content ) ) {
		return;
	}

	// Run the Revolution Slider importer with the fetched file.
	$revslider = new RevSlider();
	$revslider->importSliderFromPost( true, true, $file_path );

	// Delete the temporary file.
	wp_delete_file( $file_path );
}
