<?php

/**
 * Class Wiaas_Order_Test
 */

class Wiaas_Order_Test extends Wiaas_Unit_Test_Case {

	var $customer_id, $customer_organization_id, $customer_organization_name, $order;

	public function setUp() {
		parent::setUp();

		wp_set_current_user(1);

		$this->customer_id = wp_insert_user(array(
			'user_login' => 'test_customer',
			'user_pass'  => 'test',
			'user_email' => 'test_customer@mail.com',
			'role'       => 'customer',
		));

		$this->customer_organization_name = 'test-customer-organization';

		# create customer organization
		$this->customer_organization_id = $this->factory->organization->create_new_organization(
			array( 'name' => $this->customer_organization_name )
		);

		$this->factory->organization->assign_user_to_organization($this->customer_id, $this->customer_organization_id);

		wp_set_current_user($this->customer_id);

		$this->order = $this->factory->order->create_new_order();
	}

	function tearDown() {
		parent::tearDown();

		wp_set_current_user(1);

		wp_delete_user($this->customer_id);

		wp_delete_term(
			$this->customer_organization_id,
			Wiaas_User_Organization::TAXONOMY_NAME);
	}

	/**
	 * @covers Wiaas_Order::wiaas_prepare_rest_orders_query()
	 */
	function test_valid_order_query_status_for_active_orders() {
		$args = array();
		$request = array(
			'wiaas_is_active' => '1'
		);

		$args = Wiaas_Order::wiaas_prepare_rest_orders_query($args, $request);

		$this->assertEquals(
			array('wc-open', 'wc-processing'),
			$args['post_status']);
	}

	/**
	 * @covers Wiaas_Order::wiaas_prepare_rest_orders_query()
	 */
	function test_valid_order_query_status_for_history_orders() {
		$args = array();
		$request = array(
			'wiaas_is_active' => '0'
		);

		$args = Wiaas_Order::wiaas_prepare_rest_orders_query($args, $request);

		$this->assertEquals(
			array('wc-completed', 'wc-cancelled'),
			$args['post_status']);
	}

	/**
	 * @covers Wiaas_Order::transform_rest_order()
	 */
	function test_order_rest_response_has_customer_info() {
		$order_response = array(
			'customer_id' => $this->customer_id,
			'status' => 'processing',
			'line_items' => array()
		);

		$this->factory->order->add_customer_organization_info($this->order, $this->customer_organization_id);

		$order_rest_response = Wiaas_Order::transform_rest_order(
			new WP_REST_Response($order_response),
			$this->order,
			array( 'id' => $this->order->get_id() ));

		$transformed_order_response = $order_rest_response->get_data();

		$this->assertNotNull($transformed_order_response['customer']);
		$this->assertTrue(is_array($transformed_order_response['customer']));
		$this->assertArrayHasKey('name', $transformed_order_response['customer']);
		$this->assertArrayHasKey('email', $transformed_order_response['customer']);
		$this->assertArrayHasKey('phone', $transformed_order_response['customer']);
	}
}