<?php

class Wiaas_Unit_Test_Organization_Factory {


	/**
	 * @param array $args {
	 *      @type string $name
	 *      @type int $parent_id
	 * }
	 *
	 * @return int Organization ID
	 */
	public function create_new_organization($args = array()) {

		$defaults = array(
			'name' => 'organization'
		);

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

		$term_args = array();

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

			$term_args['parent'] = $args['parent_id'];
		}

		$result = wp_insert_term(
			$args['name'],
			Wiaas_User_Organization::TAXONOMY_NAME,
			$term_args
		);

		if (! is_wp_error($result) ) {

			return $result['term_id'];
		}

		return 0;
	}

	public function assign_user_to_organization($user_id, $organization_id) {
		wp_set_object_terms(
			$user_id,
			$organization_id,
			Wiaas_User_Organization::TAXONOMY_NAME);

		update_user_meta($user_id, '_wiaas_organization_id', $organization_id);
	}

	public function delete_organization($organization_id) {
		wp_delete_term(
			$organization_id,
			Wiaas_User_Organization::TAXONOMY_NAME);
	}

	public function delete_organizations() {

		$terms = get_terms(array(
			'taxonomy' => Wiaas_User_Organization::TAXONOMY_NAME,
			'hide_empty' => false
		));

		foreach ($terms as $term) {

			wp_delete_term($term->term_id, Wiaas_User_Organization::TAXONOMY_NAME);
		}
	}
}