<?php

/**
 * Class Wiaas_Access_Management
 */
class Wiaas_Access_Management {

	/**
	 *  Handles organization and role based access management to wiaas objects (orders, products)
	 *
	 * Using Groups Access for achieve this
	 *
	 */

	public static function init() {

		add_action( 'save_post', array( __CLASS__, 'maybe_handle_product_access' ), 999, 2 );

		add_action('woocommerce_new_order', array( __CLASS__, 'assign_order_to_organization' ));
	}

	/**
	 * Automatize access control for product and packages
	 *
	 * @param int $post_id
	 *  @param WP_Post $post
	 */
	public static function maybe_handle_product_access($post_id, $post) {

		// $post_id and $post are required
		if ( empty( $post_id ) || empty( $post ) || $post->post_type !== 'product') {
			return;
		}

		$product = wc_get_product($post_id);

		$access_group = null;

		// if product is not bundle or it not completed set it visible only for admin
		if ($product->get_type() !== 'bundle' ||
		    $product->get_status() !== 'publish' ||
		    empty(Wiaas_Package_Pricing::get_package_prices($product))) {

			$access_group = Groups_Group::read_by_name('admin');
		} else {

			$access_group = Groups_Group::read_by_name('Registered');
		}

		if ($access_group) {
			Groups_Post_Access::update(
				array(
					'post_id' => $product->get_id(),
					'groups_read' => $access_group->group_id
				)
			);
		}

	}

	/**
	 * Assignees order to corresponding user organization when order is created.
	 *
	 * @param int $order_id
	 */
	public static function assign_order_to_organization($order_id) {
		// assign order to customer organization
		$customer_id = wiaas_get_current_user_organization_id();
		Wiaas_User_Organization::assign_post_to_organization($order_id, $customer_id);
		$order = wc_get_order($order_id);

		// assign order to commercial lead organization
		$commercial_lead_id = absint($order->get_meta('_wiaas_commercial_lead_id', true));
		if ($commercial_lead_id) {
			Wiaas_User_Organization::assign_post_to_organization($order_id, $commercial_lead_id);
		}

	}
}

Wiaas_Access_Management::init();
