<?php
/**
 * Optional one-click importer for the bundled KDX service products.
 *
 * @package Fragrance_Trade
 */

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

/** Return every post status that may contain an existing optional seed. */
function fragrance_trade_seed_post_statuses() {
	return array( 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash' );
}

/** Return the product service records available to the optional importer. */
function fragrance_trade_product_service_seeds() {
	return array(
		'kdx-dunjia' => array(
			'title'   => __( 'KDX 盾甲隐形车衣', 'fragrance-trade' ),
			'slug'    => 'kdx-dunjia-paint-protection-film',
			'image'   => 'kdx-dunjia.jpg',
			'cover'   => 'covers/kdx-dunjia-cover.jpg',
			'excerpt' => __( '7.5mil 厚度 · 7 年质保 · 光泽度 150', 'fragrance-trade' ),
			'summary' => __( '盾甲是一款兼顾车漆保护、亮面效果与日常养护的隐形车衣产品，适合关注基础防护与光泽表现的用车场景。', 'fragrance-trade' ),
			'specs'   => array(
				__( '产品厚度', 'fragrance-trade' )   => '7.5mil',
				__( '质保年限', 'fragrance-trade' )   => __( '7 年', 'fragrance-trade' ),
				__( '光泽度', 'fragrance-trade' )     => '150',
				__( '拉伸强度', 'fragrance-trade' )   => '18MPa',
				__( '断裂伸长率', 'fragrance-trade' ) => '380%',
				__( '耐有机溶剂性', 'fragrance-trade' ) => __( '通过', 'fragrance-trade' ),
				__( '水接触角', 'fragrance-trade' )   => '102°',
				__( '耐粘污性', 'fragrance-trade' )   => __( '良好', 'fragrance-trade' ),
				__( '热修复', 'fragrance-trade' )     => __( '60 秒', 'fragrance-trade' ),
			),
		),
		'kdx-kaijia-plus' => array(
			'title'   => __( 'KDX 铠甲 Plus 隐形车衣', 'fragrance-trade' ),
			'slug'    => 'kdx-kaijia-plus-paint-protection-film',
			'image'   => 'kdx-kaijia-plus.jpg',
			'cover'   => 'covers/kdx-kaijia-plus-cover.jpg',
			'excerpt' => __( '8.5mil 厚度 · 8 年质保 · 断裂伸长率 460%', 'fragrance-trade' ),
			'summary' => __( '铠甲 Plus 采用更高的标称厚度和断裂伸长率，适合希望进一步提升车漆覆盖防护与膜面韧性的用车需求。', 'fragrance-trade' ),
			'specs'   => array(
				__( '产品厚度', 'fragrance-trade' )   => '8.5mil',
				__( '质保年限', 'fragrance-trade' )   => __( '8 年', 'fragrance-trade' ),
				__( '光泽度', 'fragrance-trade' )     => '150',
				__( '拉伸强度', 'fragrance-trade' )   => '23MPa',
				__( '断裂伸长率', 'fragrance-trade' ) => '460%',
				__( '耐有机溶剂性', 'fragrance-trade' ) => __( '通过', 'fragrance-trade' ),
				__( '水接触角', 'fragrance-trade' )   => '73°',
				__( '耐粘污性', 'fragrance-trade' )   => __( '良好', 'fragrance-trade' ),
				__( '热修复', 'fragrance-trade' )     => __( '60 秒', 'fragrance-trade' ),
			),
		),
		'kdx-kaijia' => array(
			'title'   => __( 'KDX 铠甲隐形车衣', 'fragrance-trade' ),
			'slug'    => 'kdx-kaijia-paint-protection-film',
			'image'   => 'kdx-kaijia.jpg',
			'cover'   => 'covers/kdx-kaijia-cover.jpg',
			'excerpt' => __( '7.5mil 厚度 · 7 年质保 · 拉伸强度 25MPa', 'fragrance-trade' ),
			'summary' => __( '铠甲隐形车衣侧重膜面韧性、亮面效果与基础耐粘污表现，并提供雾度、可见光透射比和剥离力等补充参数。', 'fragrance-trade' ),
			'specs'   => array(
				__( '产品厚度', 'fragrance-trade' )       => '7.5mil',
				__( '质保年限', 'fragrance-trade' )       => __( '7 年', 'fragrance-trade' ),
				__( '光泽度', 'fragrance-trade' )         => '150',
				__( '拉伸强度', 'fragrance-trade' )       => '25MPa',
				__( '断裂伸长率', 'fragrance-trade' )     => '430%',
				__( '耐有机溶剂性', 'fragrance-trade' )   => __( '通过', 'fragrance-trade' ),
				__( '水接触角', 'fragrance-trade' )       => '73°',
				__( '耐粘污性', 'fragrance-trade' )       => __( '三星', 'fragrance-trade' ),
				__( '热修复', 'fragrance-trade' )         => __( '60 秒', 'fragrance-trade' ),
				__( '雾度', 'fragrance-trade' )           => '0.3%',
				__( '可见光透射比', 'fragrance-trade' )   => '90%',
				__( '180°剥离力（30 分钟）', 'fragrance-trade' ) => '1400gf/inch',
				__( '180°剥离力（2 小时）', 'fragrance-trade' )  => '1800gf/inch',
				__( '涂层断裂伸长率', 'fragrance-trade' ) => '160%',
			),
		),
		'kdx-dunjia-plus' => array(
			'title'   => __( 'KDX 盾甲 Plus 隐形车衣', 'fragrance-trade' ),
			'slug'    => 'kdx-dunjia-plus-paint-protection-film',
			'image'   => 'kdx-dunjia-plus.jpg',
			'cover'   => 'covers/kdx-dunjia-plus-cover.jpg',
			'excerpt' => __( '8.5mil 厚度 · 8 年质保 · 水接触角 102°', 'fragrance-trade' ),
			'summary' => __( '盾甲 Plus 在盾甲产品方向上提升标称厚度与质保年限，兼顾膜面亮度、水接触角和日常车漆保护需求。', 'fragrance-trade' ),
			'specs'   => array(
				__( '产品厚度', 'fragrance-trade' )   => '8.5mil',
				__( '质保年限', 'fragrance-trade' )   => __( '8 年', 'fragrance-trade' ),
				__( '光泽度', 'fragrance-trade' )     => '150',
				__( '拉伸强度', 'fragrance-trade' )   => '21MPa',
				__( '断裂伸长率', 'fragrance-trade' ) => '400%',
				__( '耐有机溶剂性', 'fragrance-trade' ) => __( '通过', 'fragrance-trade' ),
				__( '水接触角', 'fragrance-trade' )   => '102°',
				__( '耐粘污性', 'fragrance-trade' )   => __( '良好', 'fragrance-trade' ),
				__( '热修复', 'fragrance-trade' )     => __( '60 秒', 'fragrance-trade' ),
			),
		),
		'kdx-jinjia-pro' => array(
			'title'   => __( 'KDX 金甲 PRO 隐形车衣', 'fragrance-trade' ),
			'slug'    => 'kdx-jinjia-pro-paint-protection-film',
			'image'   => 'kdx-jinjia-pro.jpg',
			'cover'   => 'covers/kdx-jinjia-pro-cover.jpg',
			'excerpt' => __( '7.5mil 厚度 · 8 年质保 · 光泽度 153', 'fragrance-trade' ),
			'summary' => __( '金甲 PRO 侧重高光泽、耐粘污表现与较长质保周期，适合关注亮面质感和日常清洁便利性的车漆保护方案。', 'fragrance-trade' ),
			'specs'   => array(
				__( '产品厚度', 'fragrance-trade' )   => '7.5mil',
				__( '质保年限', 'fragrance-trade' )   => __( '8 年', 'fragrance-trade' ),
				__( '光泽度', 'fragrance-trade' )     => '153',
				__( '拉伸强度', 'fragrance-trade' )   => '18MPa',
				__( '断裂伸长率', 'fragrance-trade' ) => '350%',
				__( '耐有机溶剂性', 'fragrance-trade' ) => __( '通过', 'fragrance-trade' ),
				__( '水接触角', 'fragrance-trade' )   => '95°',
				__( '耐粘污性', 'fragrance-trade' )   => __( '优秀', 'fragrance-trade' ),
				__( '热修复', 'fragrance-trade' )     => __( '90 秒', 'fragrance-trade' ),
			),
		),
	);
}

/** Find a product service previously created by this importer. */
function fragrance_trade_find_product_service_seed( $seed_key ) {
	$ids = get_posts(
		array(
			'post_type'      => 'service',
			'post_status'    => fragrance_trade_seed_post_statuses(),
			'posts_per_page' => 1,
			'fields'         => 'ids',
			'meta_key'       => '_fragrance_product_seed_key',
			'meta_value'     => $seed_key,
			'no_found_rows'  => true,
		)
	);

	return $ids ? (int) $ids[0] : 0;
}

/** Find a service with the conventional product slug. */
function fragrance_trade_find_product_service_slug( $slug ) {
	$posts = get_posts(
		array(
			'post_type'      => 'service',
			'post_status'    => fragrance_trade_seed_post_statuses(),
			'name'           => $slug,
			'posts_per_page' => 1,
			'no_found_rows'  => true,
		)
	);

	return $posts ? (int) $posts[0]->ID : 0;
}

/** Find a bundled product image already copied into the media library. */
function fragrance_trade_find_product_service_attachment( $seed_key ) {
	$ids = get_posts(
		array(
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'posts_per_page' => 1,
			'fields'         => 'ids',
			'meta_key'       => '_fragrance_product_seed_image',
			'meta_value'     => $seed_key,
			'no_found_rows'  => true,
		)
	);

	return $ids ? (int) $ids[0] : 0;
}

/**
 * Copy one bundled service image into the WordPress media library.
 *
 * @param int    $service_id Parent service post ID.
 * @param string $seed_key   Stable service seed key.
 * @param array  $seed       Service seed record.
 * @return int|WP_Error
 */
function fragrance_trade_import_product_service_image( $service_id, $seed_key, $seed ) {
	$existing = fragrance_trade_find_product_service_attachment( $seed_key );
	if ( $existing ) {
		if ( (int) wp_get_post_parent_id( $existing ) !== (int) $service_id ) {
			wp_update_post(
				array(
					'ID'          => $existing,
					'post_parent' => $service_id,
				)
			);
		}
		return $existing;
	}

	$source_file = get_template_directory() . '/assets/images/services/' . $seed['image'];
	if ( ! is_readable( $source_file ) ) {
		return new WP_Error(
			'fragrance_product_seed_image_missing',
			sprintf(
				/* translators: %s: service title. */
				__( '服务“%s”的初始化图片不存在。', 'fragrance-trade' ),
				$seed['title']
			)
		);
	}

	$image_bytes = file_get_contents( $source_file );
	if ( false === $image_bytes ) {
		return new WP_Error(
			'fragrance_product_seed_image_unreadable',
			sprintf(
				/* translators: %s: service title. */
				__( '无法读取服务“%s”的初始化图片。', 'fragrance-trade' ),
				$seed['title']
			)
		);
	}

	$upload = wp_upload_bits( $seed['image'], null, $image_bytes );
	unset( $image_bytes );
	if ( ! empty( $upload['error'] ) ) {
		return new WP_Error( 'fragrance_product_seed_upload_failed', $upload['error'] );
	}

	$attachment_id = wp_insert_attachment(
		array(
			'post_mime_type' => 'image/jpeg',
			'post_title'     => sprintf(
				/* translators: %s: service title. */
				__( '%s产品参数图', 'fragrance-trade' ),
				$seed['title']
			),
			'post_status'    => 'inherit',
		),
		$upload['file'],
		$service_id,
		true
	);

	if ( is_wp_error( $attachment_id ) ) {
		wp_delete_file( $upload['file'] );
		return $attachment_id;
	}

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

	update_post_meta( $attachment_id, '_fragrance_product_seed_image', $seed_key );
	update_post_meta(
		$attachment_id,
		'_wp_attachment_image_alt',
		sprintf(
			/* translators: %s: service title. */
			__( '%s产品参数与车型示意图', 'fragrance-trade' ),
			$seed['title']
		)
	);

	return (int) $attachment_id;
}

/** Build block-editor content for a product service. */
function fragrance_trade_build_product_service_content( $seed ) {
	$items = '';
	foreach ( $seed['specs'] as $label => $value ) {
		$items .= sprintf(
			'<li><strong>%1$s：</strong>%2$s</li>',
			esc_html( $label ),
			esc_html( $value )
		);
	}

	return sprintf(
		'<!-- wp:paragraph --><p>%1$s</p><!-- /wp:paragraph -->' .
		'<!-- wp:heading --><h2 class="wp-block-heading">%2$s</h2><!-- /wp:heading -->' .
		'<!-- wp:list --><ul class="wp-block-list">%3$s</ul><!-- /wp:list -->' .
		'<!-- wp:paragraph --><p><em>%4$s</em></p><!-- /wp:paragraph -->',
		esc_html( $seed['summary'] ),
		esc_html__( '产品参数', 'fragrance-trade' ),
		$items,
		esc_html__( '以上参数根据所提供的产品资料整理。实际产品版本、施工范围、价格、质保条件与交付标准请以门店最终确认及正式质保文件为准。', 'fragrance-trade' )
	);
}

/**
 * Import every bundled product service without overwriting existing content.
 *
 * @return array{created:int,existing:int,errors:string[]}
 */
function fragrance_trade_import_product_service_seeds() {
	$result = array(
		'created'  => 0,
		'existing' => 0,
		'errors'   => array(),
	);

	foreach ( fragrance_trade_product_service_seeds() as $seed_key => $seed ) {
		$service_id = fragrance_trade_find_product_service_seed( $seed_key );
		if ( $service_id && 'publish' === get_post_status( $service_id ) ) {
			update_post_meta( $service_id, '_fragrance_service_cover_file', $seed['cover'] );
			++$result['existing'];
			continue;
		}
		if (
			$service_id
			&& (
				'draft' !== get_post_status( $service_id )
				|| 'importing' !== get_post_meta( $service_id, '_fragrance_product_seed_state', true )
			)
		) {
			update_post_meta( $service_id, '_fragrance_service_cover_file', $seed['cover'] );
			++$result['existing'];
			continue;
		}

		if ( ! $service_id ) {
			if ( fragrance_trade_find_product_service_slug( $seed['slug'] ) ) {
				++$result['existing'];
				continue;
			}

			$service_id = wp_insert_post(
				array(
					'post_type'    => 'service',
					'post_name'    => $seed['slug'],
					'post_title'   => $seed['title'],
					'post_excerpt' => $seed['excerpt'],
					'post_status'  => 'draft',
				),
				true
			);
			if ( is_wp_error( $service_id ) ) {
				$result['errors'][] = sprintf(
					/* translators: 1: service title, 2: error message. */
					__( '无法创建服务“%1$s”：%2$s', 'fragrance-trade' ),
					$seed['title'],
					$service_id->get_error_message()
				);
				continue;
			}

			update_post_meta( $service_id, '_fragrance_product_seed_key', $seed_key );
			update_post_meta( $service_id, '_fragrance_product_seed_state', 'importing' );
			update_post_meta( $service_id, '_fragrance_service_cover_file', $seed['cover'] );
		}

		$attachment_id = fragrance_trade_import_product_service_image( $service_id, $seed_key, $seed );
		if ( is_wp_error( $attachment_id ) ) {
			$result['errors'][] = $attachment_id->get_error_message();
			continue;
		}

		set_post_thumbnail( $service_id, $attachment_id );
		$updated = wp_update_post(
			array(
				'ID'           => $service_id,
				'post_title'   => $seed['title'],
				'post_name'    => $seed['slug'],
				'post_excerpt' => $seed['excerpt'],
				'post_content' => fragrance_trade_build_product_service_content( $seed ),
				'post_status'  => 'publish',
			),
			true
		);

		if ( is_wp_error( $updated ) ) {
			$result['errors'][] = sprintf(
				/* translators: 1: service title, 2: error message. */
				__( '无法发布服务“%1$s”：%2$s', 'fragrance-trade' ),
				$seed['title'],
				$updated->get_error_message()
			);
			continue;
		}

		delete_post_meta( $service_id, '_fragrance_product_seed_state' );
		update_post_meta( $service_id, '_fragrance_service_cover_file', $seed['cover'] );
		++$result['created'];
	}

	$result['errors'] = array_values( array_unique( $result['errors'] ) );
	return $result;
}
