<?php


if (file_exists(dirname(__FILE__) . '/cmb2/init.php')) {
    require_once dirname(__FILE__) . '/cmb2/init.php';
} elseif (file_exists(dirname(__FILE__) . '/CMB2/init.php')) {
    require_once dirname(__FILE__) . '/CMB2/init.php';
}


add_action('init', 'alt_brand', 0);
function alt_brand()
{
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
    $labels = array(
        'name' => __('Marca'),
        'singular_name' => __('Marca'),
        'search_items' => __('Buscar Marcas'),
        'all_items' => __('Todos Marcas'),
        'parent_item' => __('Hierarquia Marca'),
        'parent_item_colon' => __('Parent Marcas:'),
        'edit_item' => __('Editar Marca'),
        'update_item' => __('Atualizar Marca'),
        'add_new_item' => __('Adicionar Marca'),
        'new_item_name' => __('Adicionar nome do tipo'),
        'menu_name' => __('Marcas de veículo'),
    );
// Now register the taxonomy
    register_taxonomy('marca',
        array('product','veiculos'),
        array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'show_in_rest' => true,
            'show_admin_column' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'tipo'),
        ));


}

//REST
add_action('rest_api_init', 'get_taxonomies_custom_veiculos_marca');

function get_taxonomies_custom_veiculos_marca()
{

    // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    register_rest_field('product', 'marca', array(
            'get_callback' => 'get_marca_do_veiculo',
            'update_callback' => 'update_marca_veiculo',
            'schema' => null,
        )
    );
}

function update_marca_veiculo($value, $object, $field_name)
{

    $term = $value;
    $taxonomy = 'marca';
    $parent_term = term_exists($term, 'marca'); // array is returned if taxonomy is given
    //Manually creating the taxonomy term
    wp_insert_term($term, $taxonomy);
    //Manually assigning the term
    wp_set_object_terms($object->id, $term, $taxonomy);
    return update_post_meta($object->id, $field_name, $value);


}

function get_marca_do_veiculo($post_id)
{
    $terms = get_the_terms($post_id, 'marca');
    $name = '';
    if(empty($terms)){
        return '';
    }
    foreach ($terms as $term) {

        $name = $term->name;
    }

    return $name;
}


add_action('cmb2_admin_init', 'alt_register_taxonomy_metabox');
/**
 * Hook in and add a metabox to add fields to taxonomy terms
 */
function alt_register_taxonomy_metabox()
{
    $prefix = 'alt_term_';
    /**
     * Metabox to add fields to categories and tags
     */
    $cmb_term = new_cmb2_box(array(
        'id' => $prefix . 'marca',
        'title' => 'Imagem de categoria',
        'object_types' => array('term'),
        'taxonomies' => array('marca'),
        'new_term_section' => true,
    ));

    $cmb_term->add_field(array(
        'name' => 'Logo da marca',
        'desc' => 'Selecione o arquivo de imagem da marca.',
        'id' => 'marca_img',
        'type' => 'file',
        'options' => array(
            'url' => false,
        ),
    ));


}


function adicionarMarcasAutomaticamente()
{
    alt_add_marca('Volkswagen', 'volkswagen');
    alt_add_marca('Chevrolet', 'chevrolet');
    alt_add_marca('Fiat', 'fiat');
    alt_add_marca('Ford', 'ford');
    alt_add_marca('Renault', 'renault');
    alt_add_marca('Honda', 'honda');
    alt_add_marca('Hyundai', 'hyundai');
    alt_add_marca('Toyota', 'toyota');

}

function alt_add_marca($nome, $slug, $img = null)
{
    if (!term_exists('honda', 'marca')) {
        $arrTerm = wp_insert_term(
            $nome,
            'marca',
            array(
                'description' => 'Veículos ' . $nome,
                'slug' => $slug
            )
        );
    }

    alt_add_meta_tag($slug, $img);
}

function alt_add_meta_tag($slug, $img = null)
{

    if (empty($img)) {
        $img = "https://s3-sa-east-1.amazonaws.com/catarina-prd/base/marcas/{$slug}.png";
    }

    $arrTerm = get_term_by('slug', $slug, 'marca', 'ARRAY_A');

    if (!metadata_exists('term', $arrTerm['term_id'], 'marca_img')) {
        add_term_meta($arrTerm['term_id'], 'marca_img', $img);
    }
}

//add_action('init', 'adicionarMarcasAutomaticamente');


add_action('wp_ajax_get_marcas_rest', 'get_marcas_rest');
add_action('wp_ajax_nopriv_get_marcas_rest', 'get_marcas_rest');

/**
 * Listar todas as marcas de veículos cadastrados
 */
function get_marcas_rest()
{

    $results = new stdClass();
    $results->posts = array();
    $post_type = 'veiculos';
    $query_args = array(
        'post_type' => $post_type,
        'posts_per_page' => -1,
    );

    if (!empty($_GET['tipo'])) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'tipo',
            'field' => 'slug',
            'terms' => $_GET['tipo'],
        );
    }

    if (!empty($_GET['marca'])) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'marca',
            'field' => 'slug',
            'terms' => $_GET['marca'],
        );
    }

    global $post;
    $query = new WP_Query($query_args);


    while ($query->have_posts()) {
        $query->the_post();
        $arrDados = get_the_terms($post->ID, 'marca');


        $arrDataReturn = [];

        foreach ($arrDados as $item) {

            $results->posts[$item->slug] = array(
                'post_id' => $post->ID,
                'term_id' => $item->term_id,
                'slug' => $item->slug,
                'name' => $item->name
            );

            $arrDataReturn  = $results->posts;
        };

    }


    ksort($arrDataReturn);
    $return['posts']  = $arrDataReturn;

    wp_reset_query();
    header('Content-Type: application/json');
    echo json_encode($return);
    die();
}
