<?php

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


/**
 * Class Wiaas_Template_Category
 */


class Wiaas_Template_Category {

    public static function init() {

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

    /**
     * Register wiaas template category taxonomy
     */
    public static function register_template_category_taxonomy() {

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

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

        register_taxonomy( 'template_category', array( 'product' ), $args );
    }

    /**
     * Retrieve available wiaas Template categories
     * @return array
     */
    public static function get_available_template_categories() {
        $types = get_terms( array(
            'taxonomy' => 'template_category',
            'hide_empty' => false,
        ) );

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

    /**
     * Retrieve Template category for provided package id
     * @param $product_id
     *
     * @return null
     */
    public static function get_template_category($product_id) {
        $terms = wp_get_object_terms($product_id, 'template_category');
        $template_category = isset($terms[0]) ? $terms[0]->name : null;
        return $template_category;
    }

    /**
     * Set Template category for provided package id
     * @param $product_id
     * @param $type
     */
    public static function set_template_category($product_id, $type) {

        wp_delete_object_term_relationships( $product_id, 'template_category' );

        if (isset($type)) {
            wp_set_object_terms($product_id, $type, 'template_category', false);
        }
    }
}

Wiaas_Template_Category::init();