<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}


/**
 * Registers available wiaas product categories
 *
 * Class Wiaas_Product_Category
 */
class Wiaas_Product_Category {

	/**
	 * Available wiaas product categories
	 * @var array
	 */
	private static $available_product_categories = array(
		'hardware' => array(
			'name' => 'Hardware',
			'type' => 'product',
		),
		'software' => array(
			'name' => 'Software',
			'type' => 'product',
		),
		'service' => array(
			'name' => 'Service',
			'type' => 'service',
		),
		'installation' => array(
			'name' => 'Installation',
			'type' => 'installation',
		),
	);

	public static function init() {

		add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_product_categories'));
	}

	/**
	 * Registers available wiaas product categories
	 */
	public static function register_product_categories() {

		foreach (self::$available_product_categories as $key => $available_product_category) {
			if (! has_term_meta($key)) {
				wp_insert_term($key, 'product_cat');
			}
		}
	}

	/**
	 * Retrieves category for provided product
	 * @param $product
	 *
	 * @return string|null
	 */
	public static function get_category($product) {
		$product_categories = get_the_terms($product->get_id(), 'product_cat');
		return  is_array($product_categories) && isset($product_categories[0]) ?
				$product_categories[0]->name :
				null;
	}

	/**
	 * Determines if provided product is installation
	 * @param $product
	 *
	 * @return bool
	 */
	public static function is_installation($product) {
		return self::_get_product_category_type($product) === 'installation';
	}

	/**
	 * Determines if provided product is service
	 * @param $product
	 *
	 * @return bool
	 */
	public static function is_service($product) {
		return self::_get_product_category_type($product) === 'service';
	}

	/**
	 * Determines if provided product is hardware
	 * @param $product
	 *
	 * @return bool
	 */
	public static function is_hardware($product) {
		return self::_get_product_category_type($product) === 'hardware';
	}

	/**
	 * Determines if provided product is software
	 * @param $product
	 *
	 * @return bool
	 */
	public static function is_software($product) {
		return self::_get_product_category_type($product) === 'software';
	}



	// PRIVATE


	/**
	 * Retrives product type based on its category for provided product
	 * @param $product
	 *
	 * @return null
	 */
	private static function _get_product_category_type($product) {
		$product_categories = get_the_terms($product->get_id(), 'product_cat');

		return is_array($product_categories) &&
		       isset($product_categories[0]) &&
		       isset(self::$available_product_categories[$product_categories[0]->name]) ?
		       self::$available_product_categories[$product_categories[0]->name]['type'] : null;
	}
}

Wiaas_Product_Category::init();