<?php

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


/**
 * Class Wiaas_Package_Type
 */


class Wiaas_Package_Type {

	public static function init() {

		add_action('init', array( __CLASS__, 'register_package_type_taxonomy' ) );
	}

	/**
	 * Register wiaas package type taxonomy
	 */
	public static function register_package_type_taxonomy() {

		$labels = array(
			'name'              => _x( 'Package type', 'taxonomy general name', 'wiaas' ),
			'singular_name'     => _x( 'Package type', 'taxonomy singular name', 'wiaas' ),
			'search_items'      => __( 'Search Package types', 'wiaas' ),
			'all_items'         => __( 'All Package types', 'wiaas' ),
			'parent_item'       => __( 'Parent Package type', 'wiaas' ),
			'parent_item_colon' => __( 'Parent Package type:', 'wiaas' ),
			'edit_item'         => __( 'Edit Package type', 'wiaas' ),
			'update_item'       => __( 'Update Package type', 'wiaas' ),
			'add_new_item'      => __( 'Add New Package type', 'wiaas' ),
			'new_item_name'     => __( 'New Package type Name', 'wiaas' ),
			'menu_name'         => __( 'Package type', 'wiaas' ),
		);

		$args = array(
			'hierarchical'      => false,
			'labels'            => $labels,
			'show_ui'           => false,
			'show_admin_column' => true,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => 'package_type' ),
		);

		register_taxonomy( 'package_type', array( 'product' ), $args );


		// Register available package types
		// standard package type is default package type for wiaas packages

		$types = apply_filters('wiaas_package_types', array('standard'));

		foreach ($types as $type) {
			wp_insert_term($type, 'package_type');
		}
	}

	/**
	 * Retrieve available wiaas package types
	 * @return array
	 */
	public static function get_available_package_types() {
		$types = get_terms( array(
         'taxonomy' => 'package_type',
         'hide_empty' => false,
        ) );

		return array_map(function($type) {
			return $type->name;
		}, $types);
	}

	/**
	 * Retrieve package type for provided package id
	 * @param $package_id
	 *
	 * @return null
	 */
	public static function get_package_type($package_id) {
		$terms = wp_get_object_terms($package_id, 'package_type');
		$package_type = isset($terms[0]) ? $terms[0]->name : null;
		return $package_type;
	}

	/**
	 * Set package type for provided package id
	 * @param $package_id
	 * @param $type
	 */
	public static function set_package_type($package_id, $type) {

		wp_delete_object_term_relationships( $package_id, 'package_type' );

		if (isset($type)) {
			wp_set_object_terms($package_id, $type, 'package_type', false);
		}
	}
}

Wiaas_Package_Type::init();