<?php
add_action('init', 'alt_model', 0);
function alt_model()
{
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
    $labels = array(
        'name' => __('Modelo'),
        'singular_name' => __('Modelo'),
        'search_items' => __('Buscar Modelos'),
        'all_items' => __('Todos Modelos'),
        'parent_item' => __('Hierarquia Modelo'),
        'parent_item_colon' => __('Parent Modelos:'),
        'edit_item' => __('Editar Modelo'),
        'update_item' => __('Atualizar Modelo'),
        'add_new_item' => __('Adicionar Modelo'),
        'new_item_name' => __('Adicionar nome do tipo'),
        'menu_name' => __('Modelos de veículo'),
    );
// Now register the taxonomy
    register_taxonomy('modelo',
        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' => 'modelo', 'with_front' => true),
            'rest_controller_class' => 'WP_REST_Terms_Controller',
        ));


}


//CREATED FIELD
add_action('modelo_add_form_fields', 'add_marcas_ao_modelo', 10, 2);
function add_marcas_ao_modelo($taxonomy)
{
    $arrMarcas = get_terms([
        'taxonomy' => 'marca',
        'hide_empty' => false,
    ]);


    ?>


    <div class="form-field term-slug-wrap">
        <label for="tag-slug">Selecione a marca</label>
        <select class="tag-slug" name="marca_id" id="marca">
            <?php foreach ($arrMarcas as $marca): ?>
                <option value="<?= $marca->name ?>">
                    <?= $marca->name ?>
                </option>
            <?php endforeach; ?>
        </select>

        Selecione a marca relacionada a esse modelo.
    </div>


    <?php

}

add_action('created_modelo', 'save_modelo_meta', 10, 2);
function save_modelo_meta($term_id, $ttd_id)
{
    if (!empty($_POST['marca_id'])) {
        $marca = $_POST['marca_id'];
        add_term_meta($term_id, 'modelo_meta', $marca, true);
    }
}


//UPDATE

add_action('modelo_edit_form_fields', 'edit_marcas_ao_modelo', 10, 2);
function edit_marcas_ao_modelo($term, $taxonomy)
{
    global $marca;
    $marca = get_term_meta($term->term_id, 'modelo_meta', true);

    $arrMarcas = get_terms([
        'taxonomy' => 'marca',
        'hide_empty' => false,
    ]);
    ?>

    <tr class="form-field form-required term-name-wrap">
        <th scope="row"><label for="name">Nome</label></th>
        <td>
            <select class="tag-slug" name="marca_id" id="marca">

                <?php foreach ($arrMarcas as $marca_meta): ?>
                    <option value="<?= $marca_meta->name ?>" <?php echo ($marca == $marca_meta->name) ? 'selected' : ''; ?>>
                        <?= $marca_meta->name ?>
                    </option>
                <?php endforeach; ?>

            </select>
        </td>
    </tr>

    <?php

}


add_action('edited_modelo', 'update_modelo_meta', 10, 2);
function update_modelo_meta($term_id, $ttd_id)
{
    if (!empty($_POST['marca_id'])) {
        $marca = $_POST['marca_id'];
        update_term_meta($term_id, 'modelo_meta', $marca);
    }
}


add_action('wp_ajax_get_taxonomy_product', 'get_taxonomy_product');
add_action('wp_ajax_nopriv_get_taxonomy_product', 'get_taxonomy_product');
function get_taxonomy_product()
{
    $results = new stdClass();
    $results->posts = array();
    $post_type = 'product';
    $tipo = isset($_REQUEST['tipo']) ? $_REQUEST['tipo'] : 'modelo';
    $taxonomy = isset($_REQUEST['taxonomy']) ? $_REQUEST['taxonomy'] : '';
    $taxonomy_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : null;

    if (empty($taxonomy_term)) {
        $taxonomy_term = null;
    }

    $query_args = array(
        'post_type' => $post_type,
        'posts_per_page' => -1,
    );
    if (!empty($taxonomy) && !empty($taxonomy_term)) {
        $query_args['tax_query'] = array(
            array(
                'taxonomy' => $taxonomy,
                'field' => 'slug',
                'terms' => $taxonomy_term,
            )
        );
    }
    global $post;
    $query = new WP_Query($query_args);
    while ($query->have_posts()) {
        $query->the_post();


        $arrDados = get_the_terms($post->ID, $tipo);

        foreach ($arrDados as $item) {

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

        };

    }

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

add_action('wp_ajax_nopriv_get_info_veiculo', 'get_info_veiculos');
add_action('wp_ajax_get_info_veiculo', 'get_info_veiculos');


function get_info_veiculos()
{


    //Busca os dados que queremos
    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'posts_per_page' => '-1',
    );


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


    $the_query = new WP_Query($args);

    while ($the_query->have_posts()) : $the_query->the_post();

        $ano = get_post_meta(get_the_ID(), 'alt_ano_mod', true) ?? null;
        $cambio = get_post_meta(get_the_ID(), 'alt_cambio', true) ?? null;
        $arrReturn['ano'][$ano] = $ano;
        $arrReturn['cambio'][$cambio] = $cambio;

    endwhile;

    if (empty($arrReturn)) {
        return [];
    }
    header('Content-Type: application/json');
    echo json_encode($arrReturn);
    die;
}

//REST
add_action('rest_api_init', 'get_taxonomies_custom_veiculos_modelo');
function get_taxonomies_custom_veiculos_modelo()
{

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

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

    $term = $value;
    $taxonomy = 'modelo';
    $parent_term = term_exists($term, 'modelo'); // 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_modelo_do_veiculo($post_id)
{
    //$post_id = $object['id'];
    $terms = get_the_terms($post_id, 'modelo');
    $name = '';
    if (empty($terms)) {
        return '';
    }
    foreach ($terms as $term) {

        $name = $term->name;
    }

    return $name;
}


add_action('wp_ajax_get_modelos_rest', 'get_modelos_rest');
add_action('wp_ajax_nopriv_get_modelos_rest', 'get_modelos_rest');

/**
 * Listar todas as modelos de veículos cadastrados
 */
function get_modelos_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'],
        );
    }
    if (!empty($_GET['modelo'])) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'modelo',
            'field' => 'slug',
            'terms' => $_GET['modelo'],
        );
    }


    global $post;
    $query = new WP_Query($query_args);
    $arrDataAnos = [];
    $arrDataCambios = [];
    while ($query->have_posts()) {
        $query->the_post();
        $arrDados = get_the_terms($post->ID, 'modelo');
        $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
            );

            $ano = get_post_meta($post->ID, 'alt_ano_mod', true) ?? null;
            $cambio = get_post_meta($post->ID, 'alt_cambio', true) ?? null;
            if (!empty($ano)) {
                $arrDataAnos[$ano] = $ano;
            }
            if (!empty($cambio)) {
                $arrDataCambios[$cambio] = $cambio;
            }

            $arrDataReturn = $results->posts;

        };

    }

    ksort($arrDataReturn);
    $return['posts'] = $arrDataReturn;
    $return['anos'] = $arrDataAnos;
    $return['cambios'] = $arrDataCambios;
    wp_reset_query();
    header('Content-Type: application/json');
    echo json_encode($return);
    die();
}
