<?php
/**
 * Customers class.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Modules\Sync\Customers;

use Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared\Abstracts\Hub_API\Hub_Accounts\Models\Hub_Account_Model;
use Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;
use Northmill_Online_Shared\Modules\Sync\Customers\Models\Customer_Model;

defined( 'ABSPATH' ) || exit;

/**
 * Class Customers
 */
class Customer_Sync {

	public const META_KEY_CUSTOMER_ID = 'mf_customer_id';

	/**
	 * Get NMF customer ID of customer.
	 *
	 * @param Customer_Model    $customer           Customer data.
	 * @param Hub_Account_Model $backoffice_account Backoffice account model.
	 *
	 * @return string
	 */
	public static function get_hub_customer_number(
		Customer_Model $customer,
		Hub_Account_Model $backoffice_account
	): string {
		$nmf_customer_id = get_user_meta( $customer->wc_customer_id ?? 0, self::META_KEY_CUSTOMER_ID, true );

		if ( ! empty( $nmf_customer_id ) ) { // Hub customer ID already stored for this user.
			Abstract_Shared_Base::base_instance()->logger->log(
				'sync',
				'Skipping get_customer API call, customer exists',
				array(
					'wc_customer_id'  => $customer->wc_customer_id,
					'nmf_customer_id' => $nmf_customer_id,
				),
				Log_Level_Enum::DEBUG
			);

			return (string) $nmf_customer_id; // Skip API call.
		} else {
			$nmf_customer_id = '';
		}

		$query = array(
			'SearchPhrase' => $customer->Email,
			'SearchType'   => 'Email',
		);

		$customer_numbers = $backoffice_account->api->get_customer( $query );

		if ( ! empty( $customer_numbers['list'] ) && is_array( $customer_numbers['list'] ) ) {
			// Set the first result from results as customer number.
			$nmf_customer_id = (string) $customer_numbers['list'][0]['Customer']['CustomerNumber'];

			if ( ! empty( $customer->wc_customer_id ) ) {
				// If user uses guest account and user email already registered on Woo site, update user meta
				// Or user is already registered user dave mf_customer_id on user meta.
				update_user_meta( $customer->wc_customer_id, self::META_KEY_CUSTOMER_ID, $nmf_customer_id );

				Abstract_Shared_Base::base_instance()->logger->log(
					'sync',
					'Update User#' . $customer->wc_customer_id . ' with mf_customer_id#' . $nmf_customer_id,
					null,
					Log_Level_Enum::DEBUG
				);
			}
		}

		Abstract_Shared_Base::base_instance()->logger->log(
			'sync',
			'return customer number #' . $nmf_customer_id . '#',
			null,
			Log_Level_Enum::DEBUG
		);

		return $nmf_customer_id;
	}
}
