<?php

/**
 * @author Bill Minozzi
 * @copyright  2024
 * List View Search
 */
if (!defined("ABSPATH")) {
    exit();
}
/*
>>>>>> NA PAGINA TEMPL3, VERIFIQUE CANPOS CHECKBOX...
*/
// Verifica se é um tema FSE
if (wp_is_block_theme()) {
    //
}
////////////////////////////////////////////

//////////////////////////////////////
//function multidealer_single_property_ajax()
function multidealer_single_property_ajax()
{

    // die(var_export(__LINE__));


    ob_start();
    $multidealer_post_id = $_POST['post_id'];
    if ($multidealer_post_id) {
        echo '<div class="modal-overlay22"></div>';  // Overlay
        // echo '<div class="modal-container22">';
        echo '<button class="close-modal22">Close</button>';
        echo '<br>';
        function multidealer_enqueue_flexslider_public()
        {
            if (!wp_script_is('jquery', 'enqueued')) {
                wp_enqueue_script('jquery');
            }
            // Carrega o script apenas para a parte pública
            wp_register_script('flexslider22', MULTIDEALERURL . 'includes/gallery/js/jquery.flexslider-min.js', array('jquery'), null, true);
            wp_enqueue_script('flexslider22');
        }
        add_action('wp_enqueue_scripts', 'multidealer_enqueue_flexslider_public', 1);
        function multidealer_enqueue_flexslider_admin($hook)
        {
            if (!wp_script_is('jquery', 'enqueued')) {
                wp_enqueue_script('jquery');
            }
            // Carrega o script apenas no painel de administração
            wp_register_script('flexslider23', MULTIDEALERURL . 'includes/gallery/js/jquery.flexslider-min.js', array('jquery'), null, true);
            wp_enqueue_script('flexslider23');
        }
        add_action('admin_enqueue_scripts', 'multidealer_enqueue_flexslider_admin', 1);
        $multidealer_overwrite_gallery = strtolower(get_option(
            'multidealer_overwrite_gallery',
            'yes'
        ));
        if ($multidealer_overwrite_gallery == 'yes')
            require_once(MULTIDEALERPATH . 'includes/gallery/gallery.php');

        include_once(MULTIDEALERPATH . 'includes/templates/template-functions.php');
        include_once(MULTIDEALERPATH . 'includes/templates/template-single.php');
        //echo '</div>';
        $output = ob_get_clean();

        die($output);


        // ***********************************
        $allowed_html = array(
            'div' => array(
                'class' => array(),
                'id' => array(),
                'style' => array(),
            ),
            'span' => array(
                'class' => array(),
            ),
            'a' => array(
                'href' => array(),
                'class' => array(),
                'data-toggle' => array(),
                'data-target' => array(),
            ),
            'img' => array(
                'src' => array(),
                'class' => array(),
                'alt' => array(),
            ),
            'input' => array(
                'type' => array(),
                'class' => array(),
                'id' => array(),
                'value' => array(),
                'onclick' => array(),
            ),
            'button' => array(
                'type' => array(),
                'class' => array(),
                'data-toggle' => array(),
                'data-target' => array(),
            ),
            'ul' => array(
                'class' => array(),
                'id' => array(),
                'data-*' => array(),
            ),
            'li' => array(
                'class' => array(),
                'data-*' => array(),
            ),
            'br' => array(),
            'h4' => array(),
            'style' => array(),
        );
        //wp_die(wp_kses($output, $allowed_html));
        // Bloqueia o flexslider.
        //  wp_die($output);
    }
    return;
}
function multidealer_search_ajax()
{

    // die(var_export(__LINE__));
    //
    //
    //
    //
    //



    global $wp;
    global $query, $wp_query, $CarDealer_hp_or_kw;
    $wp_query->is_404 = false;
    global $multidealer_aMeta;
    global $Multidealer_template_gallery;
    global $multidealer_quantity;

    /*
    $multidealer_postNumber = $multidealer_quantity;
    global $multidealer_postNumber;

    //die(var_export($multidealer_postNumber));
    */

    //
    //
    //
    //
    //



    $multidealer_measure = get_option('multidealer_measure', 'M2');
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;
    if (get_query_var('paged')) {
        $paged = get_query_var('paged');
    } elseif (get_query_var('page')) {
        $paged = get_query_var('page');
    }
    if (! isset($paged))
        $paged = multidealer_get_page();
    $submit = false;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Verifica se a string de consulta 'form_data' está definida
        if (isset($_POST['form_data'])) {
            $form_data = $_POST['form_data'];
            if (!empty($form_data)) {
                parse_str($form_data, $queryArray);
                $multidealer_aMeta = [];
                foreach ($queryArray as $key => $value) {
                    $$key = $value;
                    // Verifica se a chave começa com 'meta_'
                    if (strpos($key, 'meta_') === 0) {
                        // Remove o prefixo 'meta_' da chave
                        $filterKey = substr($key, 5);
                        $multidealer_aMeta[] = [
                            'key' => $filterKey, // Chave sem o prefixo
                            'value' => $value    // Valor correspondente
                        ];
                    }
                }
            } else {
                //echo "A string de consulta está vazia.<br>";
            }
        } else {
            //echo "Nenhum dado foi recebido.<br>";
        }
    } else {
        echo "Not POST.<br>";
    }
    //die(var_export($multidealer_aMeta));
    // array ( 0 => array ( 'key' => 'purpose', 'value' => 'Rent', ), 1 => array ( 'key' => 'beds', 'value' => '', ), 2 => array ( 'key' => 'baths', 'value' => '', ), 3 => array ( 'key' => 'locations', 'value' => '', ), 4 => array ( 'key' => 'order', 'value' => '', ), 5 => array ( 'key' => 'price', 'value' => '0 - 6000', ), 6 => array ( 'key' => 'price_max', 'value' => '6000', ), )
    foreach ($multidealer_aMeta as $meta) {
        // Verifica se a chave 'key' e 'value' existem no elemento atual
        if (isset($meta['key']) && isset($meta['value'])) {
            // Cria uma variável com o nome baseado na chave e atribui o valor correspondente
            ${$meta['key']} = $meta['value'];
        }
    }
    foreach ($multidealer_aMeta as $item) {
        // Verifica se o primeiro elemento é 'order'
        if (isset($item[0]) && $item[0] === 'order') {
            // Pega o valor do segundo elemento
            $order = isset($item[1]) ? $item[1] : null;
            //>>>>>>>>>>>>>>>>>>>>>>>>>>
            break; // Se você só precisa do primeiro item encontrado
        }
    }
    $priceMin = '';
    $priceMax = 9999999999;
    // Itera pela array para encontrar os valores de 'price' e 'price_max'
    foreach ($multidealer_aMeta as $meta) {
        if ($meta['key'] === 'price') {
            $price = $meta['value'];
            $pos = strpos($price, '-');
            if ($pos !== false) {
                $priceMin = trim(substr($price, 0, $pos - 1));
                $priceMax = trim(substr($price, $pos + 1));
            }
        } elseif ($meta['key'] === 'price_max') {
            // $priceMax = $meta['value'];
        }
    }
    $multidealer_afieldsId = multidealer_get_fields("all");
    $totfields = count($multidealer_afieldsId);
    $afilter = [];
    // Loop para construir a estrutura desejada
    foreach ($multidealer_aMeta as $x) {
        $excludedValues = ['', 'All', '0', '0 - 60000', '60000', 'year_high', "price_high", "price_low", "year_high", "year_low", "mileage_high", "mileage_low"];
        $excludedKeys = ['car_price', 'price', 'make']; // Defina as keys que você quer excluir
        if (!in_array($x['value'], $excludedValues) && !in_array($x['key'], $excludedKeys)) {
            // Inicializa a variável key
            // $key = 'car-' . $x['key']; // Acessa a chave da entrada em multidealer_aMeta
            $key =  'product-' . $x['key']; // Acessa a chave da entrada em multidealer_aMeta
            if ($key !== 'product-price_max' and $key !== 'product-locations' and $key !== 'meta_order') {
                $afilter[] = [
                    'key' =>  $key,            // Acessa a chave da entrada em multidealer_aMeta
                    'value' => $x['value']    // Acessa o valor da entrada em multidealer_aMeta
                ];
            }
        }
    }
    if ($price != "") {
        $afilter[] = array(
            array(
                "key"     => "product-price",
                "value"   => array($priceMin, $priceMax),
                "type"    => "numeric",
                "compare" => "BETWEEN"
            )
        );
    }
    if (!empty($order)) {
        /*
        if ($order == "price_high") {
            $wmetakey = "price";
            $wmetaorder = "DESC";
        }
        if ($order == "price_low") {
            $wmetakey = "price";
            $wmetaorder = "ASC";
        }
        if ($order == "year_high") {
            $wmetakey = "car-year";
            $wmetaorder = "DESC";
        }
        if ($order == "year_low") {
            $wmetakey = "car-year";
            $wmetaorder = "ASC";
        }
        if ($order == "mileage_high") {
            $wmetakey = "car-miles";
            $wmetaorder = "DESC";
        }
        if ($order == "mileage_low") {
            $wmetakey = "car-miles";
            $wmetaorder = "ASC";
        }
        */
    } // no order
    if (isset($meta_order))
        $order = $meta_order;
    else
        $order = '';
    if (!empty($order)) {
        if ($order == 'price_high') {
            $wmetakey = 'product-price';
            $wmetaorder = 'DESC';
        }
        if ($order == 'price_low') {
            $wmetakey = 'product-price';
            $wmetaorder = 'ASC';
        }
        if ($order == 'year_high') {
            $wmetakey = 'product-year';
            $wmetaorder = 'DESC';
        }
        if ($order == 'year_low') {
            $wmetakey = 'product-year';
            $wmetaorder = 'ASC';
        }
    } // no order

    $args = array(
        'post_type' => 'products',
        'posts_per_page' => -1,
        'paged' => 1,
    );

    $args['meta_query'] = $afilter;
    if (!empty($meta_locations) and $meta_locations <> 'All') {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'locations',
                'field' => 'name',
                'terms' => $meta_locations,
            ),
        );
    }
    wp_reset_query();
    $wp_query = new WP_Query($args);
    $qtotalposts = $wp_query->post_count;
    //
    //
    //
    //
    //
    //die(var_export($qtotalpostposts));

    // $multidealer_postNumber = $multidealer_quantity;
    // $multidealer_quantity = trim(get_option('multidealer_quantity',  '3'));
    // die(var_export($multidealer_quantity));

    $args = array(
        'post_type' => 'products',
        'posts_per_page' => $multidealer_quantity,  // Usando 'posts_per_page' em vez de 'showposts'
        'paged' => $paged,       // Certifique-se de que a variável $paged está sendo corretamente definida
    );


    //die(var_export($args));

    $args['meta_query'] = $afilter;
    if (!empty($meta_locations) and $meta_locations <> 'All') {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'locations',
                'field' => 'name',
                'terms' => $meta_locations,
            ),
        );
    }
    // $args['meta_query'] = $afilter;  // Aqui $afilter deve ser um array válido de 'meta_query'
    // Se houver uma ordenação personalizada
    if (!empty($order)) {
        $args['orderby'] = 'meta_value';
        $args['meta_type'] = 'NUMERIC';
        $args['meta_key'] = $wmetakey; // Defina o meta_key para ordenar
        $args['order'] = $wmetaorder; // Ordem crescente ou decrescente
    }
    wp_reset_query();
    $wp_query = new WP_Query($args);

    //die(var_export($args));
    //
    //
    //
    //
    //




    if (! $wp_query->have_posts()) {
        // echo var_dump($args);
        die(__('No posts found!', 'multidealer') . '<br>');
    } else {
        // $qposts = $wp_query->post_count;
        /*
        $Cardealer_template_gallery = trim(get_option(
            'CarDealer_template_gallery',
            'yes'
        ));
        */
        if ($Multidealer_template_gallery == 'yes')
            require_once(MULTIDEALERPATH . 'includes/templates/template-showroom2.php');
        else
            require_once(MULTIDEALERPATH . "includes/templates/template-showroom3.php");
        //
        //
        //
        //
        //

    }
    $allowed_html = array(
        'div' => array(
            'class' => array(),
            'id' => array(),
            'style' => array(),
        ),
        'span' => array(
            'class' => array(),
        ),
        'a' => array(
            'href' => array(),
            'class' => array(),
            'data-toggle' => array(),
            'data-target' => array(),
        ),
        'img' => array(
            'src' => array(),
            'class' => array(),
            'alt' => array(),
        ),
        'input' => array(
            'type' => array(),
            'class' => array(),
            'id' => array(),
            'value' => array(),
            'onclick' => array(),
        ),
        'button' => array(
            'type' => array(),
            'class' => array(),
            'data-toggle' => array(),
            'data-target' => array(),
        ),
        'br' => array(),
        'h4' => array(),
        'style' => array(),
    );
    // wp_die(wp_kses($output, $allowed_html));
    wp_die($output);
}
