<?php
/**
 * One-click demo importer and theme onboarding.
 *
 * The top-level WordPress admin menu is intentionally named "Import".
 *
 * @package HaPantheon
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register the required top-level Import menu.
 */
function hapantheon_register_import_menu() {
	add_menu_page(
		__( 'HaPantheon Import', 'hapantheon' ),
		__( 'Import', 'hapantheon' ),
		'manage_options',
		'hapantheon-import',
		'hapantheon_render_import_page',
		'dashicons-building',
		59
	);
}
add_action( 'admin_menu', 'hapantheon_register_import_menu' );

/**
 * Load importer-only admin styling.
 *
 * @param string $hook_suffix Current admin hook.
 */
function hapantheon_import_admin_assets( $hook_suffix ) {
	if ( 'toplevel_page_hapantheon-import' !== $hook_suffix ) {
		return;
	}
	wp_enqueue_style(
		'hapantheon-admin-import',
		HAPANTHEON_URI . '/assets/css/admin-import.css',
		array(),
		HAPANTHEON_VERSION
	);
}
add_action( 'admin_enqueue_scripts', 'hapantheon_import_admin_assets' );

/**
 * Show an activation notice with a direct path to Import.
 */
function hapantheon_mark_theme_activated() {
	set_transient( 'hapantheon_activation_notice', 1, DAY_IN_SECONDS );
}
add_action( 'after_switch_theme', 'hapantheon_mark_theme_activated' );

/**
 * Render the one-time activation notice.
 */
function hapantheon_activation_notice() {
	if ( ! current_user_can( 'manage_options' ) || ! get_transient( 'hapantheon_activation_notice' ) ) {
		return;
	}
	delete_transient( 'hapantheon_activation_notice' );
	?>
	<div class="notice notice-info is-dismissible">
		<p>
			<strong><?php esc_html_e( 'HaPantheon is active.', 'hapantheon' ); ?></strong>
			<?php esc_html_e( 'Create the complete demo website, pages, posts and editable menus from the Import screen.', 'hapantheon' ); ?>
			<a class="button button-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=hapantheon-import' ) ); ?>"><?php esc_html_e( 'Open Import', 'hapantheon' ); ?></a>
		</p>
	</div>
	<?php
}
add_action( 'admin_notices', 'hapantheon_activation_notice' );

/**
 * Read one of the bundled Gutenberg content files.
 *
 * @param string $filename File basename.
 * @return string
 */
function hapantheon_import_read_content( $filename, $replacements = array() ) {
	$path = HAPANTHEON_DIR . '/demo/content/' . basename( $filename );
	if ( ! is_readable( $path ) ) {
		return '';
	}

	$content = file_get_contents( $path );
	if ( false === $content ) {
		return '';
	}

	$replacements = array_merge(
		array(
			'{{theme_uri}}' => HAPANTHEON_URI,
		),
		(array) $replacements
	);

	return str_replace( array_keys( $replacements ), array_values( $replacements ), $content );
}

/**
 * Copy one bundled demo image into the WordPress Media Library.
 *
 * @param string $filename Bundled image basename.
 * @param string $title    Attachment title.
 * @return int|WP_Error
 */
function hapantheon_import_demo_image( $filename, $title ) {
	$filename = basename( $filename );
	$source   = HAPANTHEON_DIR . '/assets/images/demo/' . $filename;
	if ( ! is_readable( $source ) ) {
		return new WP_Error( 'hapantheon_missing_demo_image', sprintf( __( 'The bundled demo image “%s” could not be read.', 'hapantheon' ), $filename ) );
	}

	$existing = get_posts(
		array(
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'posts_per_page' => 1,
			'fields'         => 'ids',
			'meta_key'       => '_hapantheon_demo_asset',
			'meta_value'     => $filename,
		)
	);
	if ( $existing ) {
		return (int) $existing[0];
	}

	$contents = file_get_contents( $source );
	if ( false === $contents ) {
		return new WP_Error( 'hapantheon_demo_image_read_failed', sprintf( __( 'The bundled demo image “%s” could not be loaded.', 'hapantheon' ), $filename ) );
	}

	$upload = wp_upload_bits( $filename, null, $contents );
	if ( ! empty( $upload['error'] ) ) {
		return new WP_Error( 'hapantheon_demo_image_upload_failed', $upload['error'] );
	}

	$filetype      = wp_check_filetype( $upload['file'], null );
	$attachment_id = wp_insert_attachment(
		array(
			'post_mime_type' => $filetype['type'],
			'post_title'     => sanitize_text_field( $title ),
			'post_content'   => '',
			'post_status'    => 'inherit',
		),
		$upload['file']
	);
	if ( is_wp_error( $attachment_id ) ) {
		return $attachment_id;
	}

	require_once ABSPATH . 'wp-admin/includes/image.php';
	$metadata = wp_generate_attachment_metadata( $attachment_id, $upload['file'] );
	if ( ! is_wp_error( $metadata ) && $metadata ) {
		wp_update_attachment_metadata( $attachment_id, $metadata );
	}
	update_post_meta( $attachment_id, '_hapantheon_demo_asset', $filename );

	return (int) $attachment_id;
}

/**
 * Insert or update a page/post identified by type and slug.
 *
 * @param array $args    wp_insert_post arguments.
 * @param bool  $replace Replace an existing imported object.
 * @return int|WP_Error
 */
function hapantheon_import_upsert_post( $args, $replace ) {
	$post_type = isset( $args['post_type'] ) ? $args['post_type'] : 'post';
	$slug      = isset( $args['post_name'] ) ? $args['post_name'] : sanitize_title( $args['post_title'] );
	$existing  = get_page_by_path( $slug, OBJECT, $post_type );

	if ( $existing ) {
		if ( ! $replace ) {
			return (int) $existing->ID;
		}
		$args['ID'] = (int) $existing->ID;
		return wp_update_post( wp_slash( $args ), true );
	}

	return wp_insert_post( wp_slash( $args ), true );
}

/**
 * Insert or retrieve a category.
 *
 * @param array $data Category definition.
 * @return int|WP_Error
 */
function hapantheon_import_category( $data ) {
	$existing = get_term_by( 'slug', $data['slug'], 'category' );
	if ( $existing ) {
		return (int) $existing->term_id;
	}
	$result = wp_insert_term(
		$data['name'],
		'category',
		array(
			'slug'        => $data['slug'],
			'description' => $data['description'],
		)
	);

	return is_wp_error( $result ) ? $result : (int) $result['term_id'];
}

/**
 * Generic native-block body used by the additional archive posts.
 *
 * @param array $paragraphs Paragraph strings.
 * @return string
 */
function hapantheon_import_paragraph_blocks( $paragraphs ) {
	$output = '';
	foreach ( $paragraphs as $index => $paragraph ) {
		if ( 1 === $index ) {
			$output .= "<!-- wp:heading {\"level\":2} -->\n<h2>" . esc_html__( 'What the archive kept', 'hapantheon' ) . "</h2>\n<!-- /wp:heading -->\n\n";
		}
		$output .= "<!-- wp:paragraph -->\n<p>" . esc_html( $paragraph ) . "</p>\n<!-- /wp:paragraph -->\n\n";
	}
	return $output;
}

/**
 * Replace links to static prototype files with their WordPress permalinks.
 *
 * @param string $content  Imported content.
 * @param array  $object_ids Imported object IDs.
 * @param array  $category_ids Category IDs.
 * @return string
 */
function hapantheon_import_rewrite_links( $content, $object_ids, $category_ids ) {
	$map = array();

	// Point cards and rankings at the matching imported post whenever its title is present.
	$post_title_map = array(
		'אספרסו קר ביחס הזהב: 1:15'       => 'recipe',
		'מחמצת בת ארבע שנים: פרוטוקול מלא' => 'sourdough',
		'הלילה שבו נגמר לי הדלק בערבה'      => 'article-standard',
		'המכתב שמצאתי בספר יד שנייה'         => 'article-sidebar',
		'שבוע בקאפאדוקיה בלי מפה'            => 'article-hero',
		'הרכבת הלילית לפלובדיב'               => 'night-train',
		'שולחן אלון בלי בורג אחד'             => 'oak-table',
		'מנורת פליז ממצבר ישן'                => 'brass-lamp',
		'על ההבדל שבין אוסף לארכיון'          => 'collection-archive',
		'סנקה על הזמן - ועל הפיד שלכם'         => 'seneca-time',
	);

	$content = preg_replace_callback(
		'~<a\b(?P<before>[^>]*?)\bhref=(?P<quote>["\'])(?P<file>(?:article(?:-sidebar|-hero)?|recipe|oracle)\.html)(?P=quote)(?P<after>[^>]*)>(?P<body>.*?)</a>~isu',
		function ( $matches ) use ( $post_title_map, $object_ids ) {
			$label = wp_strip_all_tags( $matches['body'] );
			foreach ( $post_title_map as $title => $object_key ) {
				if ( false !== strpos( $label, $title ) && ! empty( $object_ids[ $object_key ] ) ) {
					return '<a' . $matches['before'] . 'href=' . $matches['quote'] . esc_url( get_permalink( $object_ids[ $object_key ] ) ) . $matches['quote'] . $matches['after'] . '>' . $matches['body'] . '</a>';
				}
			}

			return $matches[0];
		},
		$content
	);

	// The featured-scroll call to action does not repeat its article title inside the link.
	if ( ! empty( $object_ids['article-standard'] ) ) {
		$content = str_replace(
			'href="article.html">לקריאת המגילה',
			'href="' . esc_url( get_permalink( $object_ids['article-standard'] ) ) . '">לקריאת המגילה',
			$content
		);
	}

	foreach ( $category_ids as $slug => $term_id ) {
		$category_url = get_category_link( $term_id );
		if ( ! is_wp_error( $category_url ) ) {
			$map[ 'archive.html?cat=' . $slug ] = $category_url;
		}
	}

	$search_base = home_url( '/?s=' );
	$map        += array(
		'index.html'           => get_permalink( $object_ids['home'] ),
		'archive.html?q='      => $search_base,
		'archive.html'         => get_permalink( $object_ids['archive'] ),
		'about.html'           => get_permalink( $object_ids['about'] ),
		'oracle.html'          => get_permalink( $object_ids['oracle'] ),
		'faq.html'             => get_permalink( $object_ids['faq'] ),
		'contact.html'         => get_permalink( $object_ids['contact'] ),
		'article.html'         => get_permalink( $object_ids['article-standard'] ),
		'article-sidebar.html' => get_permalink( $object_ids['article-sidebar'] ),
		'article-hero.html'    => get_permalink( $object_ids['article-hero'] ),
		'recipe.html'          => get_permalink( $object_ids['recipe'] ),
		'404.html'             => home_url( '/' ),
	);

	// Longest keys first so query-string mappings are not consumed by their base filename.
	uksort(
		$map,
		function ( $a, $b ) {
			return strlen( $b ) <=> strlen( $a );
		}
	);

	return str_replace( array_keys( $map ), array_values( $map ), $content );
}

/**
 * Set imported post metadata.
 *
 * @param int   $post_id Post ID.
 * @param array $meta    Key/value map.
 */
function hapantheon_import_post_meta( $post_id, $meta ) {
	foreach ( $meta as $key => $value ) {
		if ( '' !== $value && null !== $value ) {
			update_post_meta( $post_id, $key, $value );
		}
	}
}

/**
 * Create one menu and populate it when needed.
 *
 * @param string $name       Menu name.
 * @param array  $items      Menu item definitions.
 * @param bool   $replace    Replace existing menu items.
 * @return int|WP_Error
 */
function hapantheon_import_menu( $name, $items, $replace ) {
	$menu = wp_get_nav_menu_object( $name );
	if ( $menu ) {
		$menu_id = (int) $menu->term_id;
	} else {
		$menu_id = wp_create_nav_menu( $name );
		if ( is_wp_error( $menu_id ) ) {
			return $menu_id;
		}
	}

	$existing_items = wp_get_nav_menu_items( $menu_id );
	if ( $existing_items && ! $replace ) {
		return $menu_id;
	}

	if ( $existing_items && $replace ) {
		foreach ( $existing_items as $existing_item ) {
			wp_delete_post( $existing_item->ID, true );
		}
	}

	foreach ( $items as $position => $item ) {
		$args = array(
			'menu-item-title'    => $item['title'],
			'menu-item-status'   => 'publish',
			'menu-item-position' => $position + 1,
		);
		if ( 'category' === $item['kind'] ) {
			$args += array(
				'menu-item-object'    => 'category',
				'menu-item-object-id' => $item['id'],
				'menu-item-type'      => 'taxonomy',
			);
		} else {
			$args += array(
				'menu-item-object'    => 'page',
				'menu-item-object-id' => $item['id'],
				'menu-item-type'      => 'post_type',
			);
		}
		wp_update_nav_menu_item( $menu_id, 0, $args );
	}

	return $menu_id;
}

/**
 * Create and assign all editable theme menus.
 *
 * @param array $ids          Imported page IDs.
 * @param array $category_ids Imported category IDs.
 * @param bool  $replace      Replace existing menu contents.
 * @return array|WP_Error
 */
function hapantheon_import_menus( $ids, $category_ids, $replace ) {
	$page_item = function ( $title, $key ) use ( $ids ) {
		return array(
			'title' => $title,
			'kind'  => 'page',
			'id'    => $ids[ $key ],
		);
	};
	$cat_item = function ( $title, $key ) use ( $category_ids ) {
		return array(
			'title' => $title,
			'kind'  => 'category',
			'id'    => $category_ids[ $key ],
		);
	};

	$primary_items = array(
		$page_item( 'דף הבית', 'home' ),
		$page_item( 'הארכיון', 'archive' ),
		$page_item( 'האורקל', 'oracle' ),
		$page_item( 'אודות', 'about' ),
		$page_item( 'שו״ת', 'faq' ),
		$page_item( 'צור קשר', 'contact' ),
	);
	$hall_items = array(
		$cat_item( 'אולם המתכונים', 'recipes' ),
		$cat_item( 'אולם הסיפורים', 'stories' ),
		$cat_item( 'אולם הטיולים', 'travel' ),
		$cat_item( 'אולם המלאכה', 'diy' ),
		$cat_item( 'האורקל', 'oracle' ),
	);
	$info_items = array(
		$page_item( 'תנאי שימוש', 'terms' ),
		$page_item( 'מדיניות פרטיות', 'privacy-policy' ),
		$page_item( 'הצהרת נגישות', 'accessibility' ),
		$page_item( 'צור קשר', 'contact' ),
	);
	$legal_items = array(
		$page_item( 'תנאי שימוש', 'terms' ),
		$page_item( 'פרטיות', 'privacy-policy' ),
		$page_item( 'נגישות', 'accessibility' ),
	);

	$menus = array(
		'primary'            => hapantheon_import_menu( 'HaPantheon — Primary', $primary_items, $replace ),
		'footer_navigation'  => hapantheon_import_menu( 'HaPantheon — Footer Navigation', $primary_items, $replace ),
		'footer_halls'       => hapantheon_import_menu( 'HaPantheon — Footer Halls', $hall_items, $replace ),
		'footer_information' => hapantheon_import_menu( 'HaPantheon — Footer Information', $info_items, $replace ),
		'footer_legal'       => hapantheon_import_menu( 'HaPantheon — Footer Legal', $legal_items, $replace ),
	);
	foreach ( $menus as $menu ) {
		if ( is_wp_error( $menu ) ) {
			return $menu;
		}
	}

	$locations = get_theme_mod( 'nav_menu_locations', array() );
	foreach ( $menus as $location => $menu_id ) {
		$locations[ $location ] = (int) $menu_id;
	}
	set_theme_mod( 'nav_menu_locations', $locations );

	return $menus;
}

/**
 * Import the bundled favicon as the WordPress Site Icon.
 *
 * @param bool $replace Replace an existing site icon.
 * @return int|WP_Error
 */
function hapantheon_import_site_icon( $replace ) {
	$current = absint( get_option( 'site_icon' ) );
	if ( $current && ! $replace ) {
		return $current;
	}

	$file = HAPANTHEON_DIR . '/assets/images/favicon-512.png';
	if ( ! is_readable( $file ) ) {
		return new WP_Error( 'hapantheon_icon_missing', __( 'The bundled favicon could not be read.', 'hapantheon' ) );
	}

	$upload = wp_upload_bits( 'hapantheon-site-icon.png', null, file_get_contents( $file ) );
	if ( ! empty( $upload['error'] ) ) {
		return new WP_Error( 'hapantheon_icon_upload', $upload['error'] );
	}

	$filetype   = wp_check_filetype( basename( $upload['file'] ), null );
	$attachment = array(
		'post_mime_type' => $filetype['type'],
		'post_title'     => __( 'HaPantheon Site Icon', 'hapantheon' ),
		'post_content'   => '',
		'post_status'    => 'inherit',
	);
	$attach_id  = wp_insert_attachment( $attachment, $upload['file'], 0, true );
	if ( is_wp_error( $attach_id ) ) {
		return $attach_id;
	}

	require_once ABSPATH . 'wp-admin/includes/image.php';
	$metadata = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
	wp_update_attachment_metadata( $attach_id, $metadata );
	update_option( 'site_icon', $attach_id );

	return (int) $attach_id;
}

/**
 * Execute the complete import.
 *
 * @param bool $replace Replace the imported pages, posts, menu items and site icon.
 * @return array|WP_Error
 */
function hapantheon_import_demo( $replace = false ) {
	$previous_import = get_option( 'hapantheon_imported_objects', array() );
	$is_first_import = empty( $previous_import['imported'] );

	$categories = array(
		'recipes' => array(
			'name'        => 'מתכונים',
			'slug'        => 'recipes',
			'description' => 'יחסים מדויקים, שיטות שנבדקו ומתכונים ששווה לשמר.',
		),
		'stories' => array(
			'name'        => 'סיפורים',
			'slug'        => 'stories',
			'description' => 'כתיבה ארוכה, זיכרונות ומפגשים שנשארים.',
		),
		'travel'  => array(
			'name'        => 'טיולים',
			'slug'        => 'travel',
			'description' => 'מסעות איטיים, מסלולים והערות מהדרך.',
		),
		'diy'     => array(
			'name'        => 'מלאכה',
			'slug'        => 'diy',
			'description' => 'עץ, מתכת ועבודה ידנית המתועדת בלי קיצורי דרך.',
		),
		'oracle'  => array(
			'name'        => 'האורקל',
			'slug'        => 'oracle',
			'description' => 'מסות ותשובות לשאלות שראויות ליותר מתגובה קצרה.',
		),
	);
	$category_ids = array();
	foreach ( $categories as $key => $category ) {
		$term_id = hapantheon_import_category( $category );
		if ( is_wp_error( $term_id ) ) {
			return $term_id;
		}
		$category_ids[ $key ] = $term_id;
	}

	$pages = array(
		'home' => array(
			'post_title'   => 'הַפַּנְתֵּאוֹן',
			'post_name'    => 'home',
			'post_excerpt' => 'ארכיון חי של דברים שראויים להישאר.',
			'post_content' => hapantheon_import_read_content( 'index.blocks.html' ),
			'template'     => '',
		),
		'archive' => array(
			'post_title'   => 'הארכיון',
			'post_name'    => 'archive',
			'post_excerpt' => 'כל המגילות, המחקרים והסיפורים במקום אחד.',
			'post_content' => '<!-- wp:paragraph --><p>עמוד זה מציג אוטומטית את כל הפוסטים והקטגוריות. ערכו את הכותרת והתקציר במסך עריכת העמוד.</p><!-- /wp:paragraph -->',
			'template'     => '',
		),
		'about' => array(
			'post_title'   => 'אודות',
			'post_name'    => 'about',
			'post_excerpt' => 'למה קיים הפנתאון ומה ראוי להיכנס אליו.',
			'post_content' => hapantheon_import_read_content( 'about.blocks.html' ),
			'template'     => 'templates/page-full-layout.php',
		),
		'oracle' => array(
			'post_title'   => 'האורקל',
			'post_name'    => 'oracle',
			'post_excerpt' => 'שאלה אחת בכל חודש. תשובה אחת שלא נכתבה בחיפזון.',
			'post_content' => hapantheon_import_read_content( 'oracle.blocks.html', array( '{{oracle_category_id}}' => (string) $category_ids['oracle'] ) ),
			'template'     => 'templates/page-full-layout.php',
		),
		'faq' => array(
			'post_title'   => 'שאלות ותשובות',
			'post_name'    => 'faq',
			'post_excerpt' => 'תשובות על הארכיון, תהליך העריכה והאורקל.',
			'post_content' => hapantheon_import_read_content( 'faq.blocks.html' ),
			'template'     => 'templates/page-full-layout.php',
		),
		'contact' => array(
			'post_title'   => 'צור קשר',
			'post_name'    => 'contact',
			'post_excerpt' => 'שאלות, הצעות, תיקונים ופניות לאורקל.',
			'post_content' => hapantheon_import_read_content( 'contact.blocks.html' ),
			'template'     => 'templates/page-full-layout.php',
		),
		'terms' => array(
			'post_title'   => 'תנאי שימוש',
			'post_name'    => 'terms',
			'post_excerpt' => 'תנאי השימוש באתר.',
			'post_content' => "<!-- wp:heading {\"level\":2} --><h2>שימוש בתוכן</h2><!-- /wp:heading -->\n<!-- wp:paragraph --><p>זהו תוכן דוגמה שנועד לעריכה. החליפו אותו בתנאים המשפטיים המתאימים לאתר שלכם לפני הפרסום.</p><!-- /wp:paragraph -->",
			'template'     => '',
		),
		'privacy-policy' => array(
			'post_title'   => 'מדיניות פרטיות',
			'post_name'    => 'privacy-policy',
			'post_excerpt' => 'כיצד האתר מטפל בפרטים שנמסרים בטפסים.',
			'post_content' => "<!-- wp:heading {\"level\":2} --><h2>פרטים שנמסרים בטפסים</h2><!-- /wp:heading -->\n<!-- wp:paragraph --><p>טופס יצירת הקשר שולח הודעה לכתובת מנהל האתר. טופס הניוזלטר שומר כתובת דוא״ל, מועד ומקור הרשמה במסד הנתונים של WordPress. ערכו מדיניות זו בהתאם לשירותי האחסון והדיוור שלכם.</p><!-- /wp:paragraph -->",
			'template'     => '',
		),
		'accessibility' => array(
			'post_title'   => 'הצהרת נגישות',
			'post_name'    => 'accessibility',
			'post_excerpt' => 'מידע על כלי הנגישות המובנים באתר.',
			'post_content' => "<!-- wp:heading {\"level\":2} --><h2>כלי נגישות</h2><!-- /wp:heading -->\n<!-- wp:paragraph --><p>התבנית כוללת דילוג לתוכן, ניווט מקלדת, תמיכה בהעדפת תנועה מופחתת, הגדלת טקסט, ניגודיות גבוהה והדגשת קישורים. בדקו והשלימו הצהרה זו בהתאם לתוכן ולתוספים שתתקינו.</p><!-- /wp:paragraph -->",
			'template'     => '',
		),
	);

	$ids           = array();
	$changed_pages = array();
	foreach ( $pages as $key => $page ) {
		$template      = $page['template'];
		$existing_page = get_page_by_path( $page['post_name'], OBJECT, 'page' );
		$apply_bundled = ! $existing_page || $replace;
		unset( $page['template'] );
		$page += array(
			'post_type'   => 'page',
			'post_status' => 'publish',
		);
		$page_id = hapantheon_import_upsert_post( $page, $replace );
		if ( is_wp_error( $page_id ) ) {
			return $page_id;
		}
		$ids[ $key ]           = (int) $page_id;
		$changed_pages[ $key ] = $apply_bundled;
		if ( $apply_bundled ) {
			if ( $template ) {
				update_post_meta( $page_id, '_wp_page_template', $template );
			} else {
				delete_post_meta( $page_id, '_wp_page_template' );
			}
		}
	}

	$article_body = hapantheon_import_read_content( 'article-body.blocks.html' );
	$recipe_body  = hapantheon_import_read_content( 'recipe-body.blocks.html' );
	$additional_body = hapantheon_import_paragraph_blocks(
		array(
			'העבודה התחילה מתוך סקרנות ונמשכה מפני שכל ניסיון חשף פרט נוסף שלא הופיע במדריך.',
			'תיעדנו את היחסים, הזמנים והטעויות. המטרה איננה להציג תוצאה מושלמת, אלא להשאיר שיטה שאפשר לחזור אליה.',
			'אחרי כמה שבועות נשארו שלושה עקרונות: למדוד לפני שמשנים, לשנות משתנה אחד בכל פעם, ולכתוב גם את הכישלונות.',
			'זו הגרסה שנכנסה לארכיון. היא פתוחה לעריכה, לתמונות שלכם ולהרחבה דרך עורך הבלוקים.',
		)
	);

	$posts = array(
		'recipe' => array(
			'title'    => 'אספרסו קר ביחס הזהב: 1:15',
			'slug'     => 'golden-ratio-cold-espresso',
			'excerpt'  => 'שלוש שנים של ניסויים, יחס אחד מנצח, ו-18 שעות של סבלנות.',
			'content'  => $recipe_body,
			'category' => 'recipes',
			'template' => 'templates/post-recipe.php',
			'image'    => 'espresso.jpg',
			'date'     => '2026-07-24 09:00:00',
			'meta'     => array(
				'_hapantheon_eyebrow'            => 'ALPHA · מתכונים · מגילה מס׳ 7',
				'_hapantheon_reading_time'        => 7,
				'_hapantheon_archive_number'      => 7,
				'_hapantheon_recipe_prep'         => '10 דקות',
				'_hapantheon_recipe_wait'         => '18 שעות',
				'_hapantheon_recipe_yield'        => '4 כוסות',
				'_hapantheon_recipe_difficulty'   => 'קל',
				'_hapantheon_recipe_tests'        => 'נבדק 23 פעמים',
				'_hapantheon_recipe_video_id'     => 'ScMzIvxBSi4',
			),
		),
		'article-standard' => array(
			'title'    => 'הלילה שבו נגמר לי הדלק בערבה',
			'slug'     => 'the-night-the-fuel-ran-out',
			'excerpt'  => 'עצירה לא מתוכננת, שמיים בלתי נשכחים, ושיחה אחת עם זר.',
			'content'  => $article_body,
			'category' => 'stories',
			'template' => '',
			'image'    => 'reflection.jpg',
			'date'     => '2026-07-18 20:30:00',
			'meta'     => array(
				'_hapantheon_eyebrow'       => 'BETA · סיפורים אישיים',
				'_hapantheon_location'      => 'קילומטר 141, הערבה',
				'_hapantheon_reading_time'  => 8,
				'_hapantheon_archive_number'=> 18,
			),
		),
		'article-sidebar' => array(
			'title'    => 'המכתב שמצאתי בספר יד שנייה',
			'slug'     => 'the-letter-inside-a-used-book',
			'excerpt'  => 'קניתי ספר בשקל. קיבלתי משימה שלא ביקשתי.',
			'content'  => $article_body,
			'category' => 'stories',
			'template' => 'templates/post-sidebar.php',
			'image'    => 'writing.jpg',
			'date'     => '2026-07-11 10:00:00',
			'meta'     => array(
				'_hapantheon_eyebrow'       => 'BETA · סיפורים · תבנית עם סרגל צד',
				'_hapantheon_location'      => 'חנות ספרים, חיפה',
				'_hapantheon_reading_time'  => 9,
				'_hapantheon_archive_number'=> 17,
			),
		),
		'article-hero' => array(
			'title'    => 'שבוע בקאפאדוקיה בלי מפה',
			'slug'     => 'cappadocia-without-a-map',
			'excerpt'  => 'ניסוי במסע: לוותר על הניווט ולסמוך על אנשים.',
			'content'  => $article_body,
			'category' => 'travel',
			'template' => 'templates/post-hero.php',
			'image'    => 'travel.jpg',
			'date'     => '2026-07-02 07:30:00',
			'meta'     => array(
				'_hapantheon_eyebrow'       => 'GAMMA · מסעות · תבנית מגזין',
				'_hapantheon_location'      => 'קאפאדוקיה, טורקיה',
				'_hapantheon_reading_time'  => 12,
				'_hapantheon_archive_number'=> 11,
			),
		),
		'sourdough' => array(
			'title'    => 'מחמצת בת ארבע שנים: פרוטוקול מלא',
			'slug'     => 'four-year-sourdough-protocol',
			'excerpt'  => 'היחסים, הטמפרטורות ולוח הזמנים - מתוך מאות אפיות.',
			'content'  => $additional_body,
			'category' => 'recipes',
			'template' => '',
			'image'    => 'food.jpg',
			'date'     => '2026-06-25 08:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'ALPHA · מתכונים', '_hapantheon_reading_time' => 11 ),
		),
		'night-train' => array(
			'title'    => 'הרכבת הלילית לפלובדיב',
			'slug'     => 'night-train-to-plovdiv',
			'excerpt'  => 'מסלול הבלקן שאף אחד לא ממליץ עליו - ולכן הוא שווה הכול.',
			'content'  => $additional_body,
			'category' => 'travel',
			'template' => '',
			'image'    => 'travel.jpg',
			'date'     => '2026-06-14 22:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'GAMMA · טיולים', '_hapantheon_reading_time' => 10, '_hapantheon_location' => 'הבלקן' ),
		),
		'oak-table' => array(
			'title'    => 'שולחן אלון בלי בורג אחד',
			'slug'     => 'oak-table-without-screws',
			'excerpt'  => 'שישה שבועות בנגרייה, מהקורה הגולמית עד שכבת השמן.',
			'content'  => $additional_body,
			'category' => 'diy',
			'template' => '',
			'image'    => 'craft.jpg',
			'date'     => '2026-06-03 16:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'DELTA · מלאכה', '_hapantheon_reading_time' => 14 ),
		),
		'brass-lamp' => array(
			'title'    => 'מנורת פליז ממצבר ישן',
			'slug'     => 'brass-lamp-from-an-old-battery',
			'excerpt'  => 'פרויקט מתכת ראשון, מתועד ביושר - כולל מה שנשרף.',
			'content'  => $additional_body,
			'category' => 'diy',
			'template' => '',
			'image'    => 'technology.jpg',
			'date'     => '2026-05-26 14:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'DELTA · מלאכה', '_hapantheon_reading_time' => 9 ),
		),
		'collection-archive' => array(
			'title'    => 'על ההבדל שבין אוסף לארכיון',
			'slug'     => 'collection-versus-archive',
			'excerpt'  => 'אוסף שואל “כמה”. ארכיון שואל “מה ראוי להישאר”.',
			'content'  => $additional_body,
			'category' => 'oracle',
			'template' => '',
			'image'    => 'temple.jpg',
			'date'     => '2026-05-15 12:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'OMEGA · האורקל', '_hapantheon_reading_time' => 8 ),
		),
		'seneca-time' => array(
			'title'    => 'סנקה על הזמן - ועל הפיד שלכם',
			'slug'     => 'seneca-time-and-your-feed',
			'excerpt'  => 'קריאה מחודשת ב“על קוצר החיים” מול מסך אינסופי.',
			'content'  => $additional_body,
			'category' => 'oracle',
			'template' => '',
			'image'    => 'reflection.jpg',
			'date'     => '2026-05-02 11:00:00',
			'meta'     => array( '_hapantheon_eyebrow' => 'OMEGA · האורקל', '_hapantheon_reading_time' => 7 ),
		),
	);

	$media_ids = array();
	foreach ( $posts as $key => $post ) {
		$existing_post = get_page_by_path( $post['slug'], OBJECT, 'post' );
		$apply_bundled = ! $existing_post || $replace;
		$args = array(
			'post_type'     => 'post',
			'post_status'   => 'publish',
			'post_title'    => $post['title'],
			'post_name'     => $post['slug'],
			'post_excerpt'  => $post['excerpt'],
			'post_content'  => $post['content'],
			'post_date'     => $post['date'],
			'post_category' => array( $category_ids[ $post['category'] ] ),
		);
		$post_id = hapantheon_import_upsert_post( $args, $replace );
		if ( is_wp_error( $post_id ) ) {
			return $post_id;
		}
		$ids[ $key ] = (int) $post_id;
		if ( $apply_bundled ) {
			$attachment_id = hapantheon_import_demo_image( $post['image'], $post['title'] );
			if ( is_wp_error( $attachment_id ) ) {
				return $attachment_id;
			}
			$media_ids[ $post['image'] ] = (int) $attachment_id;
			set_post_thumbnail( $post_id, $attachment_id );
			$featured_url = wp_get_attachment_image_url( $attachment_id, 'full' );
			update_post_meta(
				$post_id,
				'_hapantheon_featured_url',
				esc_url_raw( $featured_url ? $featured_url : HAPANTHEON_URI . '/assets/images/demo/' . $post['image'] )
			);
			hapantheon_import_post_meta( $post_id, $post['meta'] );
			if ( $post['template'] ) {
				update_post_meta( $post_id, '_wp_page_template', $post['template'] );
			} else {
				delete_post_meta( $post_id, '_wp_page_template' );
			}
		}
	}

	// Rewrite prototype links only after all destination IDs are known.
	foreach ( array( 'home', 'about', 'oracle', 'faq', 'contact' ) as $page_key ) {
		if ( empty( $changed_pages[ $page_key ] ) ) {
			continue;
		}
		$content = get_post_field( 'post_content', $ids[ $page_key ] );
		$content = hapantheon_import_rewrite_links( $content, $ids, $category_ids );
		wp_update_post(
			wp_slash(
				array(
					'ID'           => $ids[ $page_key ],
					'post_content' => $content,
				)
			)
		);
	}

	$menus = hapantheon_import_menus( $ids, $category_ids, $replace );
	if ( is_wp_error( $menus ) ) {
		return $menus;
	}

	update_option( 'show_on_front', 'page' );
	update_option( 'page_on_front', $ids['home'] );
	update_option( 'page_for_posts', $ids['archive'] );
	update_option( 'wp_page_for_privacy_policy', $ids['privacy-policy'] );
	if ( $is_first_import || $replace ) {
		update_option( 'blogname', 'הַפַּנְתֵּאוֹן' );
		update_option( 'blogdescription', 'ארכיון חי של דברים שראויים להישאר' );
	}

	$icon_id = hapantheon_import_site_icon( $replace );
	if ( is_wp_error( $icon_id ) ) {
		return $icon_id;
	}

	update_option(
		'hapantheon_imported_objects',
		array(
			'version'    => HAPANTHEON_VERSION,
			'imported'   => current_time( 'mysql' ),
			'objects'    => $ids,
			'categories' => $category_ids,
			'menus'      => $menus,
			'site_icon'  => $icon_id,
			'media'      => $media_ids,
		),
		false
	);

	flush_rewrite_rules();

	return array(
		'pages'     => count( $pages ),
		'posts'     => count( $posts ),
		'categories'=> count( $categories ),
		'menus'     => count( $menus ),
		'media'     => count( $media_ids ),
		'objects'   => $ids,
	);
}

/**
 * Receive the Import screen form.
 */
function hapantheon_handle_import_request() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have permission to import this website.', 'hapantheon' ) );
	}
	check_admin_referer( 'hapantheon_run_import' );

	$replace = ! empty( $_POST['replace_existing'] );
	$result  = hapantheon_import_demo( $replace );
	if ( is_wp_error( $result ) ) {
		set_transient( 'hapantheon_import_error_' . get_current_user_id(), $result->get_error_message(), MINUTE_IN_SECONDS );
		wp_safe_redirect( admin_url( 'admin.php?page=hapantheon-import&hapantheon_import=error' ) );
		exit;
	}

	set_transient( 'hapantheon_import_result_' . get_current_user_id(), $result, MINUTE_IN_SECONDS );
	wp_safe_redirect( admin_url( 'admin.php?page=hapantheon-import&hapantheon_import=success' ) );
	exit;
}
add_action( 'admin_post_hapantheon_run_import', 'hapantheon_handle_import_request' );

/**
 * Render the Import admin screen.
 */
function hapantheon_render_import_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$status = isset( $_GET['hapantheon_import'] ) ? sanitize_key( wp_unslash( $_GET['hapantheon_import'] ) ) : '';
	$result = get_transient( 'hapantheon_import_result_' . get_current_user_id() );
	$error  = get_transient( 'hapantheon_import_error_' . get_current_user_id() );
	if ( $result ) {
		delete_transient( 'hapantheon_import_result_' . get_current_user_id() );
	}
	if ( $error ) {
		delete_transient( 'hapantheon_import_error_' . get_current_user_id() );
	}

	$imported    = get_option( 'hapantheon_imported_objects', array() );
	$subscribers = get_option( 'hapantheon_newsletter_subscribers', array() );
	?>
	<div class="wrap hapantheon-import">
		<div class="hapantheon-import__hero">
			<div class="hapantheon-import__mark"><?php echo hapantheon_icon( 'temple' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div>
			<div>
				<h1><?php esc_html_e( 'HaPantheon Import', 'hapantheon' ); ?></h1>
				<p><?php esc_html_e( 'Turn the supplied multi-page design into a complete Gutenberg-native WordPress website.', 'hapantheon' ); ?></p>
			</div>
		</div>

		<?php if ( 'success' === $status && is_array( $result ) ) : ?>
			<div class="notice notice-success inline"><p>
				<?php
				printf(
					/* translators: 1: pages, 2: posts, 3: categories, 4: menus. */
					esc_html__( 'Import complete: %1$d pages, %2$d posts, %3$d categories and %4$d editable menus are ready.', 'hapantheon' ),
					(int) $result['pages'],
					(int) $result['posts'],
					(int) $result['categories'],
					(int) $result['menus']
				);
				?>
				<a href="<?php echo esc_url( home_url( '/' ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'View website', 'hapantheon' ); ?></a>
			</p></div>
		<?php elseif ( 'error' === $status ) : ?>
			<div class="notice notice-error inline"><p><?php echo esc_html( $error ? $error : __( 'The import stopped because of an unknown error.', 'hapantheon' ) ); ?></p></div>
		<?php endif; ?>

		<div class="hapantheon-import__grid">
			<section class="hapantheon-import__card">
				<h2><?php esc_html_e( '1. Import the complete website', 'hapantheon' ); ?></h2>
					<p><?php esc_html_e( 'This creates the homepage, archive, about, oracle, FAQ, contact and legal pages; standard, sidebar, magazine and recipe article layouts; local demo media, sample posts, categories, all menu locations and the favicon.', 'hapantheon' ); ?></p>
				<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
					<input type="hidden" name="action" value="hapantheon_run_import">
					<?php wp_nonce_field( 'hapantheon_run_import' ); ?>
					<label class="hapantheon-import__check">
						<input type="checkbox" name="replace_existing" value="1">
						<span>
							<strong><?php esc_html_e( 'Replace existing imported content', 'hapantheon' ); ?></strong>
							<small><?php esc_html_e( 'Leave unchecked to preserve edits and only create missing items. Check it to restore the bundled page/post content and rebuild the five imported menus.', 'hapantheon' ); ?></small>
						</span>
					</label>
					<?php submit_button( __( 'Import demo website', 'hapantheon' ), 'primary large', 'submit', false ); ?>
				</form>
			</section>

			<section class="hapantheon-import__card">
				<h2><?php esc_html_e( '2. Edit content and design', 'hapantheon' ); ?></h2>
				<ul class="hapantheon-import__links">
					<li><a href="<?php echo esc_url( admin_url( 'edit.php?post_type=page' ) ); ?>"><?php esc_html_e( 'Pages — edit every homepage and static-page section', 'hapantheon' ); ?></a></li>
					<li><a href="<?php echo esc_url( admin_url( 'edit.php' ) ); ?>"><?php esc_html_e( 'Posts — edit articles, templates, metadata and featured images', 'hapantheon' ); ?></a></li>
					<li><a href="<?php echo esc_url( admin_url( 'nav-menus.php' ) ); ?>"><?php esc_html_e( 'Appearance → Menus — edit header and all footer menus', 'hapantheon' ); ?></a></li>
					<li><a href="<?php echo esc_url( admin_url( 'customize.php' ) ); ?>"><?php esc_html_e( 'Appearance → Customize — edit colors, logo, typography and footer details', 'hapantheon' ); ?></a></li>
					<li><a href="<?php echo esc_url( admin_url( 'customize.php?autofocus[control]=site_icon' ) ); ?>"><?php esc_html_e( 'Site Icon — replace the generated favicon', 'hapantheon' ); ?></a></li>
				</ul>
			</section>

			<section class="hapantheon-import__card">
				<h2><?php esc_html_e( 'Newsletter subscribers', 'hapantheon' ); ?></h2>
				<p class="hapantheon-import__metric"><?php echo esc_html( is_array( $subscribers ) ? count( $subscribers ) : 0 ); ?></p>
				<p><?php esc_html_e( 'The built-in signup form stores email, date and source in WordPress. Export the list for your email platform.', 'hapantheon' ); ?></p>
				<a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=hapantheon_export_subscribers' ), 'hapantheon_export_subscribers' ) ); ?>"><?php esc_html_e( 'Export CSV', 'hapantheon' ); ?></a>
			</section>

			<section class="hapantheon-import__card">
				<h2><?php esc_html_e( 'Import status', 'hapantheon' ); ?></h2>
				<?php if ( ! empty( $imported['imported'] ) ) : ?>
					<p><strong><?php esc_html_e( 'Last import:', 'hapantheon' ); ?></strong> <?php echo esc_html( $imported['imported'] ); ?></p>
					<p><strong><?php esc_html_e( 'Theme version:', 'hapantheon' ); ?></strong> <?php echo esc_html( isset( $imported['version'] ) ? $imported['version'] : HAPANTHEON_VERSION ); ?></p>
				<?php else : ?>
					<p><?php esc_html_e( 'The bundled website has not been imported yet.', 'hapantheon' ); ?></p>
				<?php endif; ?>
				<p><?php esc_html_e( 'No page-builder plugin is required. Imported sections use named source-preserving Gutenberg blocks with WordPress-native post/category queries and secure native forms—never generic layout replacements or a page-sized Custom HTML block.', 'hapantheon' ); ?></p>
			</section>
		</div>
	</div>
	<?php
}
