<?php

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


/**
 * Class Wiaas_Package_Status
 */


class Wiaas_Package_Status {

    const AVAILABLE = 'available';
    const INVALID_MARGIN = 'margin_exceeded';
    const INVALID_TEMPLATE = 'invalid_template';

	public static function init() {
		add_action('init', array( __CLASS__, 'register_package_status_taxonomy' ) );
	}

	/**
	 * Register wiaas package status taxonomy
	 */
	public static function register_package_status_taxonomy() {

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

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

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


		// Register available package statuses

		$statuses = [self::AVAILABLE, self::INVALID_MARGIN, self::INVALID_TEMPLATE];

		foreach ($statuses as $status) {
			if (! has_term($status)) {
				wp_insert_term($status, 'package_status');
			}
		}
	}

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

		return array_map(function($status) {
			return $status->name;
		}, $statuses);
	}

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

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

		wp_delete_object_term_relationships( $package_id, 'package_status' );

		if (isset($status)) {
			wp_set_object_terms($package_id, $status, 'package_status', false);
		}
	}
}

Wiaas_Package_Status::init();