<?php
/**
 * Starter Products — installs/removes 217 ready-to-use clearance products.
 *
 * @package SimplyBuy
 */

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

add_action( 'admin_menu', 'sbuy_register_starter_products_page', 20 );
add_action( 'plugins_loaded', 'sbuy_maybe_repair_starter_newlines', 20 );

function sbuy_register_starter_products_page(): void {
	add_submenu_page(
		'simply-buy',
		esc_html__( 'Starter Products', 'simply-buy' ),
		esc_html__( 'Starter Products', 'simply-buy' ),
		'manage_options',
		'sbuy-starter-products',
		'sbuy_render_starter_products_page'
	);
}

function sbuy_render_starter_products_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	if ( isset( $_POST['sbuy_install_starter'] ) && check_admin_referer( 'sbuy_starter_action' ) ) {
		sbuy_install_starter_products();
		echo '<div class="notice notice-success"><p>' .
			esc_html__( '217 starter products have been installed. Please adjust the prices before going live. You can find the products under Products in your menu.', 'simply-buy' ) .
			'</p></div>';
	}

	if ( isset( $_POST['sbuy_remove_starter'] ) && check_admin_referer( 'sbuy_starter_action' ) ) {
		sbuy_remove_starter_products();
		echo '<div class="notice notice-success"><p>' .
			esc_html__( 'All starter products have been removed. Your own products remain untouched.', 'simply-buy' ) .
			'</p></div>';
	}

	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Starter Products', 'simply-buy' ); ?></h1>

		<p><?php esc_html_e( '217 ready-to-use clearance products — translated in German and English, with example prices and search terms.', 'simply-buy' ); ?></p>

		<ul>
			<li>✓ <?php esc_html_e( '217 products (DE + EN)', 'simply-buy' ); ?></li>
			<li>✓ <?php esc_html_e( '12 categories (Sofas, Kitchen, Electronics, Beds...)', 'simply-buy' ); ?></li>
			<li>✓ <?php esc_html_e( 'All search tags already included', 'simply-buy' ); ?></li>
			<li>✓ <?php esc_html_e( 'Example prices as a starting point', 'simply-buy' ); ?></li>
		</ul>

		<div class="notice notice-warning inline">
			<p><strong><?php esc_html_e( 'Important:', 'simply-buy' ); ?></strong>
			<?php esc_html_e( 'Please adjust all prices before going live. The example prices are for reference only.', 'simply-buy' ); ?></p>
		</div>

		<form method="post" style="margin-top: 20px;">
			<?php wp_nonce_field( 'sbuy_starter_action' ); ?>
			<button type="submit" name="sbuy_install_starter" class="button button-primary button-large">
				<?php esc_html_e( 'Install Starter Products', 'simply-buy' ); ?>
			</button>
		</form>

		<hr style="margin: 30px 0;">

		<p style="color: #666;">
			<?php esc_html_e( 'Already installed? You can remove all starter products here. Your own products remain untouched.', 'simply-buy' ); ?>
		</p>

		<form method="post">
			<?php wp_nonce_field( 'sbuy_starter_action' ); ?>
			<button type="submit" name="sbuy_remove_starter" class="button button-secondary"
				onclick="return confirm('<?php esc_attr_e( 'Remove all starter products?', 'simply-buy' ); ?>')">
				<?php esc_html_e( 'Remove Starter Products', 'simply-buy' ); ?>
			</button>
		</form>
	</div>
	<?php
}

/**
 * Convert the literal "\n" sequences that ended up in the CSV export into real
 * line breaks. Also trims leading/trailing whitespace.
 */
function sbuy_starter_normalize_text( string $text ): string {
	return trim( str_replace( array( '\n ', '\n' ), array( "\n", "\n" ), $text ) );
}

function sbuy_install_starter_products(): void {
	// Idempotency guard: if any starter products already exist, don't insert
	// another batch. Running this twice otherwise yields 434 posts, three
	// times 651, etc. — that's what bit us during repeated test runs.
	$existing = get_posts( array(
		'post_type'      => 'sbuy_product',
		'posts_per_page' => 1,
		'fields'         => 'ids',
		'meta_key'       => '_sbuy_starter_product',
		'meta_value'     => '1',
		'no_found_rows'  => true,
	) );
	if ( ! empty( $existing ) ) {
		return;
	}

	require SBUY_CORE_PLUGIN_PATH . 'includes/data/starter-products.php';

	if ( ! isset( $sbuy_starter_products ) || ! is_array( $sbuy_starter_products ) ) {
		return;
	}

	$lang = get_locale();
	$is_de = strpos( $lang, 'de' ) !== false;

	foreach ( $sbuy_starter_products as $product ) {
		$title   = sbuy_starter_normalize_text( $is_de ? $product['title_de'] : $product['title_en'] );
		$content = sbuy_starter_normalize_text( $is_de ? $product['content_de'] : $product['content_en'] );
		$tags    = $is_de ? $product['tags_de'] : $product['tags_en'];
		$cat     = $is_de ? $product['category_de'] : $product['category_en'];

		$post_id = wp_insert_post( array(
			'post_title'   => sanitize_text_field( $title ),
			'post_content' => sanitize_textarea_field( $content ),
			'post_status'  => 'publish',
			'post_type'    => 'sbuy_product',
		) );

		if ( is_wp_error( $post_id ) || ! $post_id ) {
			continue;
		}

		update_post_meta( $post_id, '_simplybuy', wp_json_encode( array(
			'price' => $product['price'],
			'sku'   => $product['sku'],
		) ) );

		update_post_meta( $post_id, '_sbuy_starter_product', true );

		if ( ! empty( $tags ) ) {
			$tag_names = array_filter( array_map( 'trim', explode( '|', $tags ) ) );
			if ( ! empty( $tag_names ) ) {
				wp_set_object_terms( $post_id, $tag_names, 'sbuy_product_tag' );
			}
		}

		if ( ! empty( $cat ) ) {
			wp_set_object_terms( $post_id, array( $cat ), 'sbuy_product_category' );
		}
	}
}

/**
 * Run the starter-products newline repair once per plugin version, silently.
 *
 * Stores the plugin version it last ran for in `sbuy_starter_repair_version`;
 * on plugin update the option lags behind SBUY_PLUGIN_VERSION, the repair runs,
 * and the option is bumped. No admin notice, no UI — purely background.
 */
function sbuy_maybe_repair_starter_newlines(): void {
	$ran_for = (string) get_option( 'sbuy_starter_repair_version', '' );
	$current = defined( 'SBUY_PLUGIN_VERSION' ) ? SBUY_PLUGIN_VERSION : '';
	if ( $ran_for === $current && '' !== $current ) {
		return;
	}
	sbuy_repair_starter_products();
	if ( '' !== $current ) {
		update_option( 'sbuy_starter_repair_version', $current );
	}
}

/**
 * Repair already-imported starter products: replace literal "\n" in title/content
 * with real line breaks. Returns the number of posts that were updated.
 */
function sbuy_repair_starter_products(): int {
	$posts = get_posts( array(
		'post_type'      => 'sbuy_product',
		'posts_per_page' => -1,
		'meta_key'       => '_sbuy_starter_product',
		'meta_value'     => '1',
	) );

	$updated = 0;
	foreach ( $posts as $post ) {
		$new_title   = sbuy_starter_normalize_text( (string) $post->post_title );
		$new_content = sbuy_starter_normalize_text( (string) $post->post_content );

		if ( $new_title === $post->post_title && $new_content === $post->post_content ) {
			continue;
		}

		wp_update_post( array(
			'ID'           => $post->ID,
			'post_title'   => $new_title,
			'post_content' => $new_content,
		) );
		$updated++;
	}

	if ( $updated > 0 ) {
		sbuy_add_log( 'starter_repair', 'Repaired ' . $updated . ' starter products' );
	}

	return $updated;
}

function sbuy_remove_starter_products(): void {
	$posts = get_posts( array(
		'post_type'      => 'sbuy_product',
		'posts_per_page' => -1,
		'meta_key'       => '_sbuy_starter_product',
		'meta_value'     => '1',
		'fields'         => 'ids',
	) );

	foreach ( $posts as $post_id ) {
		wp_delete_post( $post_id, true );
	}
}
