<?php
/**
 * Order Data — Single source of truth for reading InPost locker data from orders.
 *
 * Every display function (admin, thank-you, email, My Account) calls
 * parcselect_get_order_data() and gets all data in one place. No scattered get_meta() calls.
 *
 * @package ParcelSelector
 */

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

/**
 * Country code → native country name map.
 * Must stay in sync with JS countries.js COUNTRIES object.
 *
 * @return array<string, string>
 */
if ( ! function_exists( 'parcselect_get_country_names_map' ) ) {
function parcselect_get_country_names_map() {
	// Free version: InPost Paczkomaty, Poland only.
	return array(
		'pl' => 'Polska',
	);
}
}

/**
 * Country code → flag emoji.
 *
 * @param string $cc Two-letter country code (lowercase).
 * @return string Flag emoji or empty string.
 */
if ( ! function_exists( 'parcselect_get_country_flag' ) ) {
function parcselect_get_country_flag( $cc ) {
	$cc = strtolower( $cc );
	if ( 'uk' === $cc ) {
		$cc = 'gb';
	}
	if ( ! preg_match( '/^[a-z]{2}$/', $cc ) ) {
		return '';
	}
	// v4.2.5: Local PNG flag (was flagcdn.com CDN). Windows does NOT render Unicode flag emoji as colored flags, so PNG image is required for cross-platform consistency.
	return '<img src="' . esc_url( PARCSELECT_PLUGIN_URL . 'assets/flags/20x15/' . $cc . '.png' ) . '" width="20" height="15" alt="' . esc_attr( strtoupper( $cc ) ) . '" style="vertical-align:middle;margin-right:3px;border:1px solid #e5e7eb;border-radius:2px;" />';
}
}

/**
 * Read all InPost locker data from an order.
 * Always use this function — never call get_meta() directly.
 *
 * @param WC_Order $order WooCommerce order object.
 * @return array {
 *   @type array $paczkomat  Locker data (name, address1, city, post_code, country, country_name).
 *   @type array $customer   Customer data (first_name, last_name, email, phone).
 *   @type bool  $has_data   True when locker data exists.
 * }
 */
if ( ! function_exists( 'parcselect_get_order_data' ) ) {
function parcselect_get_order_data( $order ) {
	if ( ! is_a( $order, 'WC_Order' ) ) {
		return array( 'paczkomat' => array(), 'customer' => array(), 'has_data' => false );
	}

	$name         = (string) $order->get_meta( '_ps_locker_name', true );
	$address1     = (string) $order->get_meta( '_ps_locker_address1', true );
	$city         = (string) $order->get_meta( '_ps_locker_city', true );
	$post_code    = (string) $order->get_meta( '_ps_locker_post_code', true );
	$country      = (string) $order->get_meta( '_ps_locker_country', true );
	$country_name = (string) $order->get_meta( '_ps_locker_country_name', true );

	// Legacy meta keys from 500_temp plugin — backward compatibility
	if ( empty( $name ) ) {
		$name      = (string) $order->get_meta( '_inpost_paczkomat_name', true );
		$address1  = (string) $order->get_meta( '_inpost_paczkomat_address1', true );
		$city      = (string) $order->get_meta( '_inpost_paczkomat_city', true );
		$post_code = (string) $order->get_meta( '_inpost_paczkomat_post_code', true );
		$country   = (string) $order->get_meta( '_inpost_paczkomat_country', true );
		$country_name = (string) $order->get_meta( '_inpost_paczkomat_country_name', true );
	}

	// Fallback: shipping line item meta. When the checkout order-meta save did
	// not persist the _ps_locker_* keys (transient-lock race — see
	// class-ps-order-save.php), the locker ID is still on the shipping line
	// item: parcselect_save_shipping_item_meta() writes it under the
	// "Parcel Locker" / "Pickup Point" key. Recover it so the admin metabox,
	// thank-you page and order emails still display the locker.
	$is_custom_from_item = null;
	if ( empty( $name ) ) {
		foreach ( $order->get_items( 'shipping' ) as $ship_item ) {
			if ( false === strpos( (string) $ship_item->get_method_id(), 'parcselect_inpost_paczkomat' ) ) {
				continue;
			}
			$item_locker = (string) $ship_item->get_meta( __( 'Parcel Locker', 'parcel-selector' ) );
			if ( '' === $item_locker ) {
				$item_locker = (string) $ship_item->get_meta( 'Parcel Locker' );
			}
			if ( '' === $item_locker ) {
				$item_locker = (string) $ship_item->get_meta( __( 'Pickup Point', 'parcel-selector' ) );
				if ( '' !== $item_locker ) { $is_custom_from_item = true; }
			}
			if ( '' === $item_locker ) {
				$item_locker = (string) $ship_item->get_meta( 'Pickup Point' );
				if ( '' !== $item_locker ) { $is_custom_from_item = true; }
			}
			if ( '' !== $item_locker ) {
				$name = $item_locker;
				if ( null === $is_custom_from_item ) { $is_custom_from_item = false; }
				// Address fields were never persisted to order meta — use the order
				// shipping address (locker address is copied there on a normal save)
				// as a best-effort fallback.
				if ( '' === $address1 )  { $address1  = (string) $order->get_shipping_address_1(); }
				if ( '' === $city )      { $city      = (string) $order->get_shipping_city(); }
				if ( '' === $post_code ) { $post_code = (string) $order->get_shipping_postcode(); }
				if ( '' === $country )   { $country   = (string) $order->get_shipping_country(); }
				break;
			}
		}
	}

	// Auto-fill country_name from code if missing
	if ( empty( $country_name ) && ! empty( $country ) ) {
		$map          = parcselect_get_country_names_map();
		$cc           = strtolower( $country );
		$country_name = isset( $map[ $cc ] ) ? $map[ $cc ] : strtoupper( $country );
	}

	$has_data = ! empty( $name );

	$cust_fn = (string) $order->get_meta( '_ps_customer_first_name', true );
	$cust_ln = (string) $order->get_meta( '_ps_customer_last_name', true );
	$cust_em = (string) $order->get_meta( '_ps_customer_email', true );
	$cust_ph = (string) $order->get_meta( '_ps_customer_phone', true );

	$is_custom     = '1' === (string) $order->get_meta( '_ps_is_custom_pickup', true );
	if ( ! $is_custom && null !== $is_custom_from_item ) {
		$is_custom = $is_custom_from_item;
	}
	$time_to_order = (string) $order->get_meta( '_ps_time_to_order', true );
	$device_type   = (string) $order->get_meta( '_ps_device_type', true );
	$delivery_time = (string) $order->get_meta( '_ps_delivery_time', true );
	$order_note    = (string) $order->get_meta( '_ps_order_note', true );

	return array(
		'paczkomat' => array(
			'name'          => $name,
			'address1'      => $address1,
			'city'          => $city,
			'post_code'     => $post_code,
			'country'       => $country,
			'country_name'  => $country_name,
			'is_custom'     => $is_custom,
			'time_to_order' => $time_to_order,
			'device_type'   => $device_type,
			'delivery_time' => $delivery_time,
			'order_note'    => $order_note,
		),
		'customer'  => array(
			'first_name' => $cust_fn,
			'last_name'  => $cust_ln,
			'email'      => $cust_em,
			'phone'      => $cust_ph,
		),
		'has_data'  => $has_data,
	);
}
}
