<?php
/**
 * Cart Recovery — Line Item DTO
 *
 * Immutable value object representing a single line in a captured cart
 * snapshot. Kept deliberately minimal — only the fields the mailer / AI
 * composer need to reconstruct a human-readable recap of what the visitor
 * left behind.
 *
 * @package Niwa_AI
 * @since   0.12.0
 */

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

/**
 * Readonly line-item DTO. PHP 8.1+ `readonly` guarantees per-property
 * immutability after construction so snapshot hashes remain stable.
 */
final class Niwa_AI_Cart_Recovery_Line_Item {

	public function __construct(
		public readonly int $product_id,
		public readonly int $variation_id,
		public readonly string $name,
		public readonly int $qty,
		public readonly float $unit_price,
		public readonly float $line_total,
		public readonly string $image_url,
		public readonly string $permalink
	) {}

	/**
	 * Convert to an associative array with stable key order for JSON
	 * serialization. The key order is relied upon by the snapshot hash —
	 * do not reorder without bumping the hash version.
	 *
	 * @return array<string, mixed>
	 */
	public function to_array(): array {
		return array(
			'product_id'   => $this->product_id,
			'variation_id' => $this->variation_id,
			'name'         => $this->name,
			'qty'          => $this->qty,
			'unit_price'   => $this->unit_price,
			'line_total'   => $this->line_total,
			'image_url'    => $this->image_url,
			'permalink'    => $this->permalink,
		);
	}

	/**
	 * Reconstruct a line item from its array form (DB / JSON).
	 *
	 * @param array<string, mixed> $data Input.
	 */
	public static function from_array( array $data ): self {
		return new self(
			(int) ( $data['product_id'] ?? 0 ),
			(int) ( $data['variation_id'] ?? 0 ),
			(string) ( $data['name'] ?? '' ),
			(int) ( $data['qty'] ?? 0 ),
			(float) ( $data['unit_price'] ?? 0.0 ),
			(float) ( $data['line_total'] ?? 0.0 ),
			(string) ( $data['image_url'] ?? '' ),
			(string) ( $data['permalink'] ?? '' )
		);
	}
}
