<?php

defined( 'ABSPATH' ) || exit;

/**
 * Class Wiaas_User
 */
class Wiaas_User {

	public static function init() {
		include_once dirname( __FILE__ ) . '/class-wiaas-countries.php';
		include_once dirname( __FILE__ ) . '/user/class-wiaas-customer.php';

		add_action('init', array(__CLASS__, 'load_user_organization'));
		add_action('plugins_loaded', array(__CLASS__, 'remove_default_user_groups'), 30);

		add_filter('woocommerce_rest_prepare_customer', array(__CLASS__, 'transform_rest_customer'), 10, 3);
		add_filter('jwt_auth_token_before_dispatch', array(__CLASS__, 'transform_jwt_token_response'), 10, 2);
	}

	public static function load_user_organization() {
		if (class_exists('WP_User_Taxonomy')) {
			require_once dirname( __FILE__ ) . '/user/class-wiaas-user-organization.php';
            require_once dirname( __FILE__ ) . '/user/wiaas-organization-functions.php';

			new Wiaas_User_Organization();
		}
	}

	public static function remove_default_user_groups() {
		remove_action( 'init', 'wp_register_default_user_group_taxonomy' );
		remove_action( 'init', 'wp_register_default_user_type_taxonomy'  );
	}

	/**
	 * Apply wiaas custom transformation on retrieved JSON customer object
	 *
	 * @param $response
	 * @param $order
	 * @param $request
	 *
	 * @return mixed
	 */
	public static function transform_rest_customer($response, $order, $request) {
		$data = $response->get_data();
		$user_id = $data['id'];
		$customer_info = Wiaas_Customer::get_customer_info($user_id);

		return new WP_REST_Response($customer_info);
	}

	/**
	 * Apply wiaas custom transformation on JWT token response
	 *
	 * @param $data
	 * @param $user
	 *
	 * @return mixed
	 */
	public static function transform_jwt_token_response($data, $user) {
		return new WP_REST_Response(array(
			'token' => $data['token'],
			'userInfo' => array(
				'wiaas_id_user' => $user->ID,
				'wiaas_is_company_admin' => 1, //TODO: don't hardcode this
				'wiaas_user_full_name' => $user->first_name . ' ' . $user->last_name,
				'wiaas_user_type' => $user->roles,
				'wiaas_username' => $user->data->user_login 
			)
		));

	}


}

Wiaas_User::init();