<?php

namespace Blazemedia\Affiliation\CustomTaxonomies;

use Blazemedia\Affiliation\AdminUserInterface\Settings\PostTypes;



/**
 * È una tassonomia di servizio per stabilire le tipologie di pagina
 * nella sezione orientamento a soli scopi di servizio.
 * I term sono pubblicabili solo da backend
 */
class BlzAffiliationAttributes {

    public $taxonomy_name   = 'blz_affiliation_attributes';

    public $mandatory_terms = [ 'paid' ];

    public $post_types      = [];
        
    /**
     * Initializer for setting up action handler
     */
    public function __construct() {

        $this->post_types  = PostTypes::getInstance()->post_types;
    
        add_action('init',             [ $this, 'init_service_tax'     ] );
        add_filter( 'add_meta_boxes' , [ $this, 'remove_taxonomies_metaboxes' ] );       

    }

    public function init_service_tax() {

        $labels = array(
            'name'              => _x( 'Attributi Affiliazione', 'taxonomy general name' ),
            'singular_name'     => _x( 'Attributo Affiliazione', 'taxonomy singular name' ),
            'search_items'      => __( 'Search item' ),
            'all_items'         => __( 'All items' ),
            'parent_item'       => __( 'Parent item' ),
            'parent_item_colon' => __( 'Parent item:' ),
            'edit_item'         => __( 'Edit item' ),
            'update_item'       => __( 'Update item' ),
            'add_new_item'      => __( 'Add New item' ),
            'new_item_name'     => __( 'New item Name' ),
            'menu_name'         => __( 'Item' ),
        );

        register_taxonomy( $this->taxonomy_name, $this->post_types, [

            'hierarchical'       => true,
            'labels'             => $labels,
            'show_ui'            => true,
            'show_admin_column'  => false,
            'show_in_nav_menus'  => false,
            'show_in_menu'       => false,
            'show_in_rest'       => true,
            'show_in_quick_edit' => false,
            'query_var'          => $this->taxonomy_name,
            'rewrite'            => [ 'slug' => $this->taxonomy_name, 'with_front' => false ],
        ]);

        $this->write_mandatory_terms();
    }

    /**
     * Aggiunge i termini indispensabili per il funzionamento del tema
     *
     * @return void
     */
    public function write_mandatory_terms() {

        /// prende i termini che non sono stati ancora creati
        $mandatory_terms = array_diff( $this->mandatory_terms, get_terms( [ 'taxonomy' => $this->taxonomy_name,  'fields' => 'slugs' ] ) );

        /// aggiunge i term che ancora non esistono
        foreach( $mandatory_terms as $term ) {

            wp_insert_term( $term, $this->taxonomy_name );
        }
    }

    function remove_taxonomies_metaboxes() {

        foreach($this->post_types as $post_type) {
            remove_meta_box( 'blz_affiliation_attributesdiv', $post_type, 'side');
        }

    }


}