<?php
/**
 * PufferGo Product Data — 产品模板的数据收集 + 解析层。
 *
 * 将 single-puffergo_product.php 中 70 行 meta 读取 + JSON 解析 + 格式化逻辑
 * 抽成独立类，模板中只需 PufferGo_Product_Data::from_current_post() 即可获取全部数据。
 *
 * @package PufferGo
 */

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

class PufferGo_Product_Data {

	/** @var int 产品 ID */
	public $id;

	/** @var string 产品标题 */
	public $title;

	/** @var string 简短描述 */
	public $short_description;

	// ── 价格 ──
	/** @var string 格式化后的价格展示文本 */
	public $price_display = '';
	/** @var array 原始价格数据 */
	public $price_data = array();

	// ── MOQ ──
	/** @var string 格式化后的起订量 */
	public $moq_display = '';
	/** @var array 原始 MOQ 数据 */
	public $moq_data = array();

	// ── 交期 ──
	/** @var string 格式化后的交期 */
	public $lead_time_display = '';
	/** @var array 原始交期数据 */
	public $lead_time_data = array();

	// ── 画廊 ──
	/** @var array 画廊项目 [{type, id, src?, poster?}] */
	public $gallery_items = array();
	/** @var array|null 主图项目 */
	public $main_item = null;
	/** @var int 主图附件 ID */
	public $main_image_id = 0;

	/** @var string 主图 alt 文本 */
	public $main_image_alt = '';

	/** @var string 主图视频 poster URL */
	public $main_poster_url = '';

	/** @var string 主图视频源 URL */
	public $main_video_src = '';

	// ── 规格 ──
	/** @var array 规格列表 [{key, value}] */
	public $specs = array();

	// ── CTA ──
	/** @var bool CTA 是否可见 */
	public $cta_visible = true;
	/** @var string CTA 按钮文本 */
	public $cta_text = '';
	/** @var string CTA 链接 */
	public $cta_url = '';
	/** @var bool CTA 是否是锚点 */
	public $cta_is_anchor = false;
	/** @var string CTA 链接额外属性 */
	public $cta_link_attrs = '';

	// ── 其他 ──
	/** @var string 手册下载 URL */
	public $brochure_url = '';

	// ── 联系表单 ──
	/** @var bool 联系表单是否启用 */
	public $form_enabled = true;
	/** @var array 联系表单配置 */
	public $form_config = array();

	// ── 分类 ──
	/** @var array 产品分类 */
	public $categories = array();
	/** @var WP_Term|null 主分类 */
	public $primary_category = null;

	/**
	 * 从当前文章创建数据对象。
	 *
	 * @return self
	 */
	public static function from_current_post() {
		return new self( get_the_ID() );
	}

	/**
	 * 构造函数：读取、解析、格式化全部产品数据。
	 *
	 * @param int $product_id 产品 ID。
	 */
	public function __construct( $product_id ) {
		$this->id    = $product_id;
		$this->title = get_the_title( $product_id );

		$this->load_categories();
		$this->load_meta();
		$this->parse();
		$this->format();
		$this->load_cta();
		$this->load_contact_form();
	}

	/**
	 * 加载分类。
	 */
	private function load_categories() {
		$this->categories       = get_the_terms( $this->id, 'puffergo_product_cat' );
		$this->primary_category = ( ! empty( $this->categories ) && ! is_wp_error( $this->categories ) )
			? $this->categories[0] : null;
	}

	/**
	 * 加载原始 meta。
	 */
	private function load_meta() {
		$this->short_description = get_post_meta( $this->id, '_puffergo_short_description', true );
		$this->brochure_url      = get_post_meta( $this->id, '_puffergo_brochure_url', true );
	}

	/**
	 * 解析 JSON 字段。
	 */
	private function parse() {
		$price_raw     = get_post_meta( $this->id, '_puffergo_price', true );
		$moq_raw       = get_post_meta( $this->id, '_puffergo_moq', true );
		$lead_time_raw = get_post_meta( $this->id, '_puffergo_lead_time', true );
		$gallery_raw   = get_post_meta( $this->id, '_puffergo_gallery', true );
		$specs_raw     = get_post_meta( $this->id, '_puffergo_specs', true );

		$this->price_data     = $price_raw ? json_decode( $price_raw, true ) : array();
		$this->moq_data       = $moq_raw ? json_decode( $moq_raw, true ) : array();
		$this->lead_time_data = $lead_time_raw ? json_decode( $lead_time_raw, true ) : array();
		$this->gallery_items  = PufferGo_Product_CPT::normalize_gallery( $gallery_raw );
		$this->specs          = PufferGo_Product_CPT::normalize_specs( $specs_raw );

		// 画廊 fallback 到特色图
		$thumbnail_id = get_post_thumbnail_id( $this->id );
		if ( empty( $this->gallery_items ) && $thumbnail_id ) {
			$this->gallery_items = array( array( 'type' => 'image', 'id' => $thumbnail_id ) );
		}

		// 预处理每个画廊项的 URL 和缩略图 ID
		$this->gallery_items = array_map( array( $this, 'enrich_gallery_item' ), $this->gallery_items );

		// 主图信息
		$this->main_item     = ! empty( $this->gallery_items ) ? $this->gallery_items[0] : null;
		$this->main_image_id = $this->main_item ? ( $this->main_item['id'] ?? 0 ) : 0;

		if ( $this->main_image_id ) {
			$this->main_image_alt = get_post_meta( $this->main_image_id, '_wp_attachment_image_alt', true );
		}
		if ( $this->main_item ) {
			$this->main_poster_url = $this->main_item['poster_url'] ?? '';
			$this->main_video_src  = $this->main_item['video_src'] ?? '';
		}
	}

	/**
	 * 预处理单个画廊项：解析 video_src / poster_url / thumb_id。
	 *
	 * @param array $item 原始画廊项。
	 * @return array 增强后的画廊项。
	 */
	private function enrich_gallery_item( $item ) {
		$is_video   = in_array( $item['type'], array( 'video', 'url' ), true );
		$video_src  = '';
		$poster_url = '';
		$thumb_id   = $item['id'] ?? 0;

		if ( 'url' === $item['type'] ) {
			$video_src = $item['src'] ?? '';
		} elseif ( 'video' === $item['type'] ) {
			$video_src = $thumb_id ? wp_get_attachment_url( $thumb_id ) : '';
		}

		if ( $is_video && ! empty( $item['poster'] ) ) {
			$poster_url = wp_get_attachment_url( $item['poster'] );
			$thumb_id   = (int) $item['poster'];
		}

		$item['is_video']   = $is_video;
		$item['video_src']  = $video_src;
		$item['poster_url'] = $poster_url;
		$item['thumb_id']   = $thumb_id;

		return $item;
	}

	/**
	 * 格式化展示字段。
	 */
	private function format() {
		$use_formatter = class_exists( 'PufferGo_Unit_Formatter' );

		if ( $use_formatter ) {
			$this->price_display     = PufferGo_Unit_Formatter::format( $this->price_data, 'currency' );
			$this->moq_display       = PufferGo_Unit_Formatter::format( $this->moq_data, 'quantity' );
			$this->lead_time_display = PufferGo_Unit_Formatter::format( $this->lead_time_data, 'time' );
		} else {
			$this->price_display     = isset( $this->price_data['value'] ) ? $this->price_data['value'] : '';
			$this->moq_display       = isset( $this->moq_data['value'] ) ? $this->moq_data['value'] : '';
			$this->lead_time_display = isset( $this->lead_time_data['min'] )
				? $this->lead_time_data['min'] . '-' . $this->lead_time_data['max'] . ' ' . ( $this->lead_time_data['unit'] ?? '' )
				: '';
		}
	}

	/**
	 * 加载 CTA 按钮配置。
	 */
	private function load_cta() {
		$cta_raw  = get_post_meta( $this->id, '_puffergo_cta_button', true );
		$cta_data = $cta_raw ? json_decode( $cta_raw, true ) : array();

		$this->cta_visible   = ! isset( $cta_data['visible'] ) || $cta_data['visible'];
		$this->cta_text      = ! empty( $cta_data['text'] ) ? $cta_data['text'] : __( 'Send Inquiry', 'puffergo' );
		$this->cta_url       = ! empty( $cta_data['url'] ) ? $cta_data['url'] : '#contact-form';
		$this->cta_is_anchor = strpos( $this->cta_url, '#' ) === 0;
		$this->cta_link_attrs = $this->cta_is_anchor ? '' : ' target="_blank" rel="noopener noreferrer"';
	}

	/**
	 * 加载联系表单配置。
	 */
	private function load_contact_form() {
		$form_config_raw     = get_post_meta( $this->id, '_puffergo_contact_form', true );
		$this->form_config   = $form_config_raw ? json_decode( $form_config_raw, true ) : array();
		$this->form_enabled  = ! isset( $this->form_config['enabled'] ) || $this->form_config['enabled'];
	}

	/**
	 * 获取联系表单的 block attributes。
	 *
	 * @return array
	 */
	public function get_form_block_attrs() {
		$attrs = array(
			'title'      => ! empty( $this->form_config['title'] ) ? $this->form_config['title'] : __( 'Send Inquiry', 'puffergo' ),
			'subtitle'   => ! empty( $this->form_config['subtitle'] ) ? $this->form_config['subtitle'] : __( 'Fill out the form below and we will get back to you as soon as possible.', 'puffergo' ),
			'buttonText' => ! empty( $this->form_config['buttonText'] ) ? $this->form_config['buttonText'] : __( 'Send Inquiry', 'puffergo' ),
		);

		if ( ! empty( $this->form_config['fields'] ) ) {
			$attrs['fields'] = $this->form_config['fields'];
		}
		if ( ! empty( $this->form_config['successMessage'] ) ) {
			$attrs['successMessage'] = $this->form_config['successMessage'];
		}
		if ( ! empty( $this->form_config['successUrl'] ) ) {
			$attrs['successUrl'] = $this->form_config['successUrl'];
		}

		return $attrs;
	}

	/**
	 * 获取面包屑数据。
	 *
	 * @return array 每个元素 ['url' => string|null, 'label' => string]
	 */
	public function get_breadcrumb_items() {
		$items   = array();
		$items[] = array(
			'url'   => get_post_type_archive_link( 'puffergo_product' ),
			'label' => __( 'Products', 'puffergo' ),
		);

		if ( $this->primary_category ) {
			$items[] = array(
				'url'   => get_term_link( $this->primary_category ),
				'label' => $this->primary_category->name,
			);
		}

		$items[] = array(
			'url'   => null,
			'label' => $this->title,
		);

		return $items;
	}
}
