<?php
/**
 * Privacy-safe order data for the campaign editor preview.
 *
 * @package VoidPulse
 */

namespace VoidPulse\Admin;

use VoidPulse\Privacy\SafeOrderFormatter;

defined( 'ABSPATH' ) || exit;

final class PreviewOrder {
	/**
	 * Return the newest eligible order or deterministic example data.
	 *
	 * @return array<string,mixed>
	 */
	public static function data() {
		if ( ! function_exists( 'wc_get_orders' ) ) {
			return self::fallback();
		}

		$orders = wc_get_orders(
			array(
				'status'  => array( 'processing', 'completed' ),
				'limit'   => 10,
				'orderby' => 'date',
				'order'   => 'DESC',
				'return'  => 'objects',
			)
		);
		if ( ! is_array( $orders ) ) {
			return self::fallback();
		}

		$image_candidate = null;
		$text_candidate  = null;
		foreach ( $orders as $order ) {
			if ( ! is_object( $order ) || ! method_exists( $order, 'get_items' ) ) {
				continue;
			}
			foreach ( $order->get_items( 'line_item' ) as $item ) {
				if ( ! is_object( $item ) || ! method_exists( $item, 'get_name' ) ) {
					continue;
				}
				$date = $order->get_date_paid() ?: $order->get_date_created();
				if ( ! $date ) {
					continue;
				}
				$product       = method_exists( $item, 'get_product' ) ? $item->get_product() : null;
				$product_image = self::product_image_url( $product );
				$candidate     = array(
					'order'         => $order,
					'product'       => sanitize_text_field( $item->get_name() ),
					'product_image' => $product_image,
					'timestamp'     => $date->getTimestamp(),
				);
				if ( $product_image ) {
					$image_candidate = $candidate;
					break 2;
				}
				if ( ! $text_candidate ) {
					$text_candidate = $candidate;
				}
			}
		}
		$candidate = $image_candidate ?: $text_candidate;
		if ( $candidate ) {
			return self::from_order(
				$candidate['order'],
				$candidate['product'],
				$candidate['product_image'],
				$candidate['timestamp']
			);
		}

		return self::fallback();
	}

	/**
	 * Resolve real product artwork, including variation parents and galleries.
	 *
	 * @param mixed $product WooCommerce product object.
	 * @return string
	 */
	private static function product_image_url( $product ) {
		if ( ! is_object( $product ) || ! method_exists( $product, 'exists' ) || ! $product->exists() ) {
			return '';
		}
		$image_id = absint( $product->get_image_id() );
		$parent   = null;
		if ( $product->is_type( 'variation' ) ) {
			$parent = wc_get_product( $product->get_parent_id() );
			if ( ! $image_id && $parent ) {
				$image_id = absint( $parent->get_image_id() );
			}
		}
		if ( ! $image_id && method_exists( $product, 'get_gallery_image_ids' ) ) {
			$gallery  = array_filter( array_map( 'absint', $product->get_gallery_image_ids() ) );
			$image_id = $gallery ? reset( $gallery ) : 0;
		}
		if ( ! $image_id && $parent && method_exists( $parent, 'get_gallery_image_ids' ) ) {
			$gallery  = array_filter( array_map( 'absint', $parent->get_gallery_image_ids() ) );
			$image_id = $gallery ? reset( $gallery ) : 0;
		}
		$image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' ) : '';
		return $image_url ? esc_url_raw( $image_url ) : '';
	}

	/**
	 * Build preformatted variants without exposing sensitive order fields.
	 *
	 * @param \WC_Order $order         Order.
	 * @param string    $product       Product display name.
	 * @param string    $product_image Product image URL.
	 * @param int       $timestamp     Purchase timestamp.
	 * @return array<string,mixed>
	 */
	private static function from_order( $order, $product, $product_image, $timestamp ) {
		$formatter  = new SafeOrderFormatter();
		$identities = array();
		foreach ( array( 'first_name', 'first_initial', 'anonymous', 'someone', 'customer' ) as $format ) {
			$identities[ $format ] = $formatter->customer( $order, $format );
		}
		$locations = array();
		foreach ( array( 'city', 'region', 'country', 'city_country', 'hidden' ) as $format ) {
			$locations[ $format ] = $formatter->location( $order, $format );
		}

		return array(
			'source'        => 'order',
			'label'         => __( 'Most recent order', 'voidpulse-social-proof-for-woocommerce' ),
			'identities'    => $identities,
			'locations'     => $locations,
			'product'       => $product ?: __( 'Product', 'voidpulse-social-proof-for-woocommerce' ),
			'product_image' => $product_image,
			'time_ago'      => sprintf(
				/* translators: %s: human-readable elapsed time. */
				__( '%s ago', 'voidpulse-social-proof-for-woocommerce' ),
				human_time_diff( absint( $timestamp ), time() )
			),
		);
	}

	/**
	 * Return useful preview data when no eligible order exists.
	 *
	 * @return array<string,mixed>
	 */
	private static function fallback() {
		return array(
			'source'     => 'example',
			'label'      => __( 'Example order', 'voidpulse-social-proof-for-woocommerce' ),
			'identities' => array(
				'first_name'    => 'Alex',
				'first_initial' => 'Alex M.',
				'anonymous'     => __( 'Anonymous customer', 'voidpulse-social-proof-for-woocommerce' ),
				'someone'       => __( 'Someone', 'voidpulse-social-proof-for-woocommerce' ),
				'customer'      => __( 'Customer', 'voidpulse-social-proof-for-woocommerce' ),
			),
			'locations'  => array(
				'city'         => 'Brisbane',
				'region'       => 'Queensland',
				'country'      => 'Australia',
				'city_country' => 'Brisbane, Australia',
				'hidden'       => '',
			),
			'product'       => __( 'Sample Product', 'voidpulse-social-proof-for-woocommerce' ),
			'product_image' => '',
			'time_ago'      => __( '8 minutes ago', 'voidpulse-social-proof-for-woocommerce' ),
		);
	}
}
