<?php

defined('ABSPATH') || exit;

class Wiaas_Product_Supplier {
    public static function init() {

        add_action('init', array(__CLASS__, 'register_supplier_taxonomy'));
        add_action('created_' . 'wiaas-user-organization', array(__CLASS__, 'on_organization_added'));
    }

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

        $labels = array(
            'name' => _x('Supplier', 'taxonomy general name', 'wiaas'),
            'singular_name' => _x('Supplier', 'taxonomy singular name', 'wiaas'),
            'search_items' => __('Search Suppliers', 'wiaas'),
            'all_items' => __('All Suppliers', 'wiaas'),
            'parent_item' => __('Parent Supplier', 'wiaas'),
            'parent_item_colon' => __('Parent Supplier', 'wiaas'),
            'edit_item' => __('Edit Supplier', 'wiaas'),
            'update_item' => __('Update Supplier', 'wiaas'),
            'add_new_item' => __('Add New Supplier', 'wiaas'),
            'new_item_name' => __('New Supplier Name', 'wiaas'),
            'menu_name' => __('Supplier', '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('supplier', array('product'), $args);
    }


    /**
     * Create corresponding supplier term for organization
     *
     * @param $organization_id
     */
    public static function on_organization_added($organization_id) {
        $organization = get_term_by('id', $organization_id, 'wiaas-user-organization');

	    $supplier = term_exists($organization->slug, 'supplier');

        if (! $supplier) {
        	$supplier = wp_insert_term($organization->name, 'supplier', array(
        		'slug' => $organization->slug
	        ));
        }

       add_term_meta($supplier['term_id'], 'organisation_id', $organization->term_id);
    }
}

Wiaas_Product_Supplier::init();