<?php
/**
 * Customer factory.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Modules\Sync\Customers;

use Northmill_Online_Shared\Modules\Sync\Customers\Models\Customer_Model;
use WC_Order;

defined( 'ABSPATH' ) || exit;

/**
 * Class Customer_Factory
 */
class Customer_Factory {
	/**
	 * Create a customer model from a WooCommerce order.
	 *
	 * @param WC_Order $order The order to create the customer from.
	 *
	 * @return Customer_Model|null The customer model if created, otherwise null.
	 */
	public static function create_customer_from_order( WC_Order $order ): ?Customer_Model {
		$nmf_customer_id = get_post_meta( $order->get_id(), Customer_Sync::META_KEY_CUSTOMER_ID, true );

		$name = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
		if ( empty( $name ) ) {
			return null;
		}

		$customer_number = ( isset( $nmf_customer_id ) ) ? $nmf_customer_id : '';

		$customer = array(
			'wc_customer_id' => $order->get_customer_id(),
			'CustomerNumber' => $customer_number,
			'Name'           => $name,
			'Address1'       => $order->get_billing_address_1(),
			'Address2'       => $order->get_billing_address_2(),
			'PostCode'       => $order->get_billing_postcode(),
			'City'           => $order->get_billing_city(),
			'Country'        => $order->get_billing_country(),
			'Email'          => $order->get_billing_email(),
			'Mobile'         => $order->get_billing_phone(),
		);

		foreach ( $customer as $key => $v ) {
			if ( empty( $v ) && 'CustomerNumber' !== $key ) {
				unset( $customer[ $key ] );
			}
		}

		return new Customer_Model( $customer );
	}
}
