<?php

class Wiaas_Unit_Test_Order_Factory {


	/**
	 * @param array $args {
	 *      @type int $customer_id
	 * }
	 *
	 * @return WC_Order|WP_Error
	 */
	public function create_new_order($args = array()) {

		$customer_id = empty($args['customer_id']) ? get_current_user_id() : $args['customer_id'];

		$order = wc_create_order(array(
			'customer_id' => $customer_id
		));

		return $order;
	}

	/**
	 * @param WC_Order|int $order
	 * @param int $customer_organization_id
	 */
	public function add_customer_organization_info($order, $customer_organization_id) {

		if (is_numeric($order)) {

			$order = wc_get_order($order);
		}

		$order->add_meta_data('_wiaas_customer', $customer_organization_id);

		$order->add_meta_data('_wiaas_customer_info', wiaas_get_organization_info($customer_organization_id));

		$order->save_meta_data();
	}


	/**
	 * @param array $args
	 * @param WC_Order_Item_Product|null $bundle_item
	 * @param WC_Order|null $order
	 *
	 * @return WC_Order_Item_Product
	 */
	public function create_new_simple_product_order_item($args = array(), $bundle_item = null, $order = null) {

		$defaults = array(
			'quantity' => 1,
			'total' => 0
		);

		$args = wp_parse_args($args, $defaults);

		$item = new WC_Order_Item_Product();

		$item->set_props(
			array(
				'quantity'     => $args['quantity'],
				'total'        => $args['total'],
			)
		);

		if (! empty($args['category']) ) {

			$item->add_meta_data('_wiaas_category', $args['category']);
		}

		if (! empty($args['supplier_organization_id']) ) {

			$item->add_meta_data('_wiaas_supplier_organization_id', $args['supplier_organization_id']);
		}

		$item->set_backorder_meta();

		if (! empty($order) ) {

			$order->add_item($item);

			$order->save();
		}

		return $item;
	}

	/**
	 * @param array $args
	 * @param WC_Order|null $order
	 *
	 * @return WC_Order_Item_Product
	 */
	public function create_new_bundle_order_item($args = array(), $order = null) {

		$defaults = array(
			'quantity' => 1,
			'total' => 0
		);

		$args = wp_parse_args($args, $defaults);

		$item = new WC_Order_Item_Product();

		$item->set_props(
			array(
				'quantity'     => $args['quantity'],
				'total'        => $args['total'],
			)
		);

		$item->set_backorder_meta();

		if (! empty($order) ) {

			$order->add_item($item);

			$order->save();
		}

		return $item;
	}

	/**
	 * @param WC_Order $order
	 * @param array $items
	 */
	public function add_order_items($order, $items) {

		foreach ( $items as $item ) {

			$order->add_item($item);
		}

		$order->save();
	}
}