<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
add_action('wp_ajax_nopriv_widget_buscar_veiculos', 'widget_buscar_veiculos');
add_action('wp_ajax_widget_buscar_veiculos', 'widget_buscar_veiculos');


function widget_buscar_veiculos()
{
    $filter = [];

    if (!empty($_GET['marca'])) {
        $filter[] = array(
            'taxonomy' => 'marca',
            'field' => 'slug',
            'terms' => $_GET['marca'],
        );
    }
    if (!empty($_GET['modelo'])) {
        $filter[] = array(
            'taxonomy' => 'modelo',
            'field' => 'slug',
            'terms' => $_GET['modelo'],
        );
    }
    //Busca os dados que queremos
    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'posts_per_page' => '-1',
        'tax_query' => array($filter),
    );
    $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;
        $arrReturn['ano'][$ano] = $ano;

    endwhile;

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