<?php
add_shortcode('read_functions', function(){ return '<pre>'.htmlspecialchars(file_get_contents(__FILE__)).'</pre>'; });
add_filter( 'flatsome_lightbox_close_btn_inside', '__return_true' );

/* === Đổi nhãn "Sale!" thành "Bán" màu đỏ === */
add_filter('woocommerce_sale_flash', 'nddt_custom_sale_flash', 10, 3);
function nddt_custom_sale_flash($html, $post, $product) {
    return '<span class="onsale nddt-ban-gap-badge">GẤP</span>';
}


add_action('flatsome_custom_single_product_1','tinh_lai_vay');
function tinh_lai_vay(){
    if(Gia_goc()!=""){
                                echo do_shortcode('[nk_loan_calculator price="'.Gia_goc().'"]');
                            }else{
                                echo do_shortcode('[nk_loan_calculator price="1500000000"]');
                            }
}



add_action('woocommerce_single_product_summary','thong_tin_them',25);
function thong_tin_them(){
    ?>
    <div class="div-gia-tien">
                        <p class="value">Giá: <?php 
                        global $product;
                        if($product && $product->is_on_sale()) {
                            echo gia_num_forvietnamese($product->get_sale_price());
                            echo '<del style="font-size: 1em; margin-left: 8px; color: #0056b3; font-weight: bold;">' . gia_num_forvietnamese($product->get_regular_price()) . '</del>';
                        } else {
                            if(Gia_goc()!=""){echo gia_num_forvietnamese(Gia_goc());}else{echo "Liên hệ";}
                        }
                        ?></p></div>
    <div class="thong-tin-chi-tiet">
        
                <ul>
                   
                    <?php if( get_field('dien_tich') ): ?>
                    <li>
                        <p class="label">Diện tích</p>
                        <p class="value"><?php the_field('dien_tich'); ?> m2</p>
                    </li>
                    <?php endif; ?>
                 <?php if( get_field('huong_nha') ): ?>
                    <li>
                        <p class="label">Hướng</p>
                        <p class="value"><?php the_field('huong_nha'); ?></p>
                    </li>
                    <?php endif; ?>
                 <?php if( get_field('phong_ngu') ): ?>     
<li>
                        <p class="label">Phòng ngủ</p>
                        <p class="value"><?php the_field('phong_ngu');?></p>
                    </li>
                       <?php endif; ?>
                   <?php if( get_field('phong_ve_sinh') ): ?>   
                    <li>
                        <p class="label">Phòng WC</p>
                        <p class="value"><?php the_field('phong_ve_sinh'); ?></p>
                    </li>
                    <?php endif; ?>
                    <?php if( get_field('tang') ): ?>
                    <li>
                        <p class="label">Tầng</p>
                        <p class="value"><?php the_field('tang'); ?></p>
                    </li>
                    <?php endif; ?>
                     <?php if( get_field('toa_nha') ): ?>
                    <li>
                        <p class="label">Tòa nhà</p>
                        <p class="value"><?php the_field('toa_nha'); ?></p>
                    </li>
                    <?php endif; ?>
                    <?php if( get_field('phap_ly') ): ?>
                    <li>
                        <p class="label">Pháp lý</p>
                        <p class="value"><?php the_field('phap_ly'); ?></p>
                    </li>
                    <?php endif; ?>
                     <?php if( get_field('thoi_gian_giao_nha') ): ?>
                    <li>
                        <p class="label">Giao nhà</p>
                        <p class="value"><?php the_field('thoi_gian_giao_nha'); ?></p>
                    </li>
                    <?php endif; ?>
                   <?php
                   

    //Grabs the Primary Category of the Product
                        $args = array( 'taxonomy' => 'chu-dau-tu',);
                            $terms = wp_get_post_terms($post->ID,'chu-dau-tu', $args);
                            $count = count($terms); 
                            if ($count > 0) {?>
                        
                    
                    <li>
                        <p class="label">Chủ đầu tư</p>
                        <p class="value">
                            <?php 
                        
                            //If the post type is a product, display the Primary Category Link
                        foreach ($terms as $term) {
                                    echo '<a href="' . esc_url( get_term_link( $term->term_id ) ) . '">';
                                    echo $term->name;
                                    echo '</h3>';
                                
                                }
                        ?>
                        </p>
                    </li>
                    <?php

                        }
                            ?>
                </ul>
            </div>

    <?php
}


add_action('admin_enqueue_scripts', 'ds_admin_theme_style');
function ds_admin_theme_style() {
echo '<style>.update-nag, .updated, .error, .is-dismissible, .notice { display: none; }</style>';
}
/**
 * Code goes in theme functions.php
 */
add_action( 'init', function () {
	if ( function_exists( 'add_ux_builder_post_type' ) ) {
		add_ux_builder_post_type( 'custom_post_type' );
	}
} );
// Đổi tên Related
add_filter('gettext', 'rename_relatedproduct_text', 10, 3);
add_filter('ngettext', 'rename_relatedproduct_text', 10, 3);

function rename_relatedproduct_text($translated, $text, $domain)
{
if ($text === 'Related products' && $domain === 'woocommerce') {
$translated = esc_html__('Dự án liên quan', $domain);
}
return $translated;
}

// Add custom Theme Functions here
function chu_dau_tu() {
        /* Biến $label chứa các tham số thiết lập tên hiển thị của Taxonomy
         */
        $labels = array(
                'name' => 'Chủ đầu tư',
                'singular' => 'Danh mục chủ đầu tư',
                'menu_name' => 'Chủ đầu tư'
        );
        /* Biến $args khai báo các tham số trong custom taxonomy cần tạo
         */
        $args = array(
                'labels'                     => $labels,
                'hierarchical'               => true,
                'public'                     => true,
                'show_ui'                    => true,
                'show_admin_column'          => true,
                'show_in_nav_menus'          => true,
                'show_tagcloud'              => true,
        );
        /* Hàm register_taxonomy để khởi tạo taxonomy
         */
        register_taxonomy('chu-dau-tu', 'product', $args);
}
// Hook into the 'init' action
add_action( 'init', 'chu_dau_tu', 0 );

// Tạo Taxonomy 8 Hướng
function huong_nha() {
        /* Biến $label chứa các tham số thiết lập tên hiển thị của Taxonomy
         */
        $labels = array(
                'name' => 'Hướng nhà',
                'singular' => 'Danh mục hướng nhà',
                'menu_name' => 'Hướng nhà'
        );
        /* Biến $args khai báo các tham số trong custom taxonomy cần tạo
         */
        $args = array(
                'labels'                     => $labels,
                'hierarchical'               => true,
                'public'                     => true,
                'show_ui'                    => true,
                'show_admin_column'          => true,
                'show_in_nav_menus'          => true,
                'show_tagcloud'              => true,
        );
        /* Hàm register_taxonomy để khởi tạo taxonomy
         */
        register_taxonomy('huong-nha', 'product', $args);
}
// Hook into the 'init' action
add_action( 'init', 'huong_nha', 0 );

// Tạo Taxonomy thành phố
function dia_diem() {
        /* Biến $label chứa các tham số thiết lập tên hiển thị của Taxonomy
         */
        $labels = array(
                'name' => 'Địa điểm',
                'singular' => 'Danh mục địa điểm',
                'menu_name' => 'Địa điểm'
        );
        /* Biến $args khai báo các tham số trong custom taxonomy cần tạo
         */
        $args = array(
                'labels'                     => $labels,
                'hierarchical'               => true,
                'public'                     => true,
                'show_ui'                    => true,
                'show_admin_column'          => true,
                'show_in_nav_menus'          => true,
                'show_tagcloud'              => true,
        );
        /* Hàm register_taxonomy để khởi tạo taxonomy
         */
        register_taxonomy('dia-diem', 'product', $args);
}
// Hook into the 'init' action
add_action( 'init', 'dia_diem', 0 );

/**
 * Remove product data tabs
 */
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
    unset( $tabs['reviews'] );       // Xóa tab đánh giá
    unset( $tabs['additional_information'] );    // Xóa tab thuộc tính sản phẩm
    return $tabs;
}

/*
* Author: Le Van Toan - https://levantoan.com
* Đoạn code thu gọn nội dung bao gồm cả nút xem thêm và thu gọn lại sau khi đã click vào xem thêm
*/
add_action('wp_footer','devvn_readmore_flatsome');
function devvn_readmore_flatsome(){
    ?>
    <style>
        .product-info div.div-thong-tin-sp {
            overflow: hidden;
            position: relative;
            padding-bottom: 25px;
        }
        .single-product .tab-panels div#tab-description.panel:not(.active) {
            height: 0 !important;
        }
        .devvn_readmore_flatsome {
            text-align: center;
            cursor: pointer;
            position: absolute;
            z-index: 10;
            bottom: 0;
            width: 100%;
            background: #fff;
        }
        .devvn_readmore_flatsome:before {
            height: 55px;
            margin-top: -45px;
            content: "";
            background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
            background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
            background: linear-gradient(to bottom, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
            filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff00', endColorstr='#ffffff',GradientType=0 );
            display: block;
        }
        .devvn_readmore_flatsome a {
            color: #4585ff;
            display: block;
        }
        .devvn_readmore_flatsome a:after {
            content: '';
            width: 0;
            right: 0;
            border-top: 6px solid #4585ff;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            display: inline-block;
            vertical-align: middle;
            margin: -2px 0 0 5px;
        }
        .devvn_readmore_flatsome_less a:after {
            border-top: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-bottom: 6px solid #4585ff;
        }
        .devvn_readmore_flatsome_less:before {
            display: none;
        }
    </style>
    <script>
        (function($){
            $(document).ready(function(){
                $(window).load(function(){
                    if($('.product-info div.div-thong-tin-sp').length > 0){
                        var wrap = $('.product-info div.div-thong-tin-sp');
                        var current_height = wrap.height();
                        var your_height = 550;
                        if(current_height > your_height){
                            wrap.css('height', your_height+'px');
                            wrap.append(function(){
                                return '<div class="devvn_readmore_flatsome devvn_readmore_flatsome_more"><a title="Xem thêm" href="javascript:void(0);">Xem thêm</a></div>';
                            });
                            wrap.append(function(){
                                return '<div class="devvn_readmore_flatsome devvn_readmore_flatsome_less" style="display: none;"><a title="Xem thêm" href="javascript:void(0);">Thu gọn</a></div>';
                            });
                            $('body').on('click','.devvn_readmore_flatsome_more', function(){
                                wrap.removeAttr('style');
                                $('body .devvn_readmore_flatsome_more').hide();
                                $('body .devvn_readmore_flatsome_less').show();
                            });
                            $('body').on('click','.devvn_readmore_flatsome_less', function(){
                                wrap.css('height', your_height+'px');
                                $('body .devvn_readmore_flatsome_less').hide();
                                $('body .devvn_readmore_flatsome_more').show();
                            });
                        }
                    }
                });
            })
        })(jQuery)
    </script>
    <?php
}


/*
* Author: Le Van Toan - https://levantoan.com
* Đoạn code thu gọn nội dung bao gồm cả nút xem thêm và thu gọn lại sau khi đã click vào xem thêm
*/
add_action('wp_footer','devvn_readmore_flatsome_chu_dau_tu');
function devvn_readmore_flatsome_chu_dau_tu(){
    ?>
    <style>
		div#chu-dau-tu{
            overflow: hidden;
            position: relative;
        }
        .devvn_readmore_flatsome_2 {
            text-align: center;
            cursor: pointer;
            position: absolute;
            z-index: 10;
            bottom: 0;
            width: 100%;
            background: #fff;
        }
        .devvn_readmore_flatsome_2:before {
            height: 55px;
            margin-top: -45px;
            content: "";
            background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
            background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
            background: linear-gradient(to bottom, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
            filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff00', endColorstr='#ffffff',GradientType=0 );
            display: block;
        }
        .devvn_readmore_flatsome_2 a {
            color: #4585ff;
            display: block;
        }
        .devvn_readmore_flatsome_2 a:after {
            content: '';
            width: 0;
            right: 0;
            border-top: 6px solid #4585ff;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            display: inline-block;
            vertical-align: middle;
            margin: -2px 0 0 5px;
        }
        .devvn_readmore_flatsome_less_2 a:after {
            border-top: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-bottom: 6px solid #4585ff;
        }
        .devvn_readmore_flatsome_less_2:before {
            display: none;
        }
    </style>
    <script>
        (function($){
            $(document).ready(function(){
                $(window).load(function(){
                    if($('div#chu-dau-tu').length > 0){
                        var wrap = $('div#chu-dau-tu');
                        var current_height = wrap.height();
                        var your_height = 400;
                        if(current_height > your_height){
                            wrap.css('height', your_height+'px');
                            wrap.append(function(){
                                return '<div class="devvn_readmore_flatsome_2 devvn_readmore_flatsome_more_2"><a title="Xem thêm" href="javascript:void(0);">Xem thêm</a></div>';
                            });
                            wrap.append(function(){
                                return '<div class="devvn_readmore_flatsome_2 devvn_readmore_flatsome_less_2" style="display: none;"><a title="Xem thêm" href="javascript:void(0);">Thu gọn</a></div>';
                            });
                            $('body').on('click','.devvn_readmore_flatsome_more_2', function(){
                                wrap.removeAttr('style');
                                $('body .devvn_readmore_flatsome_more_2').hide();
                                $('body .devvn_readmore_flatsome_less_2').show();
                            });
                            $('body').on('click','.devvn_readmore_flatsome_less_2', function(){
                                wrap.css('height', your_height+'px');
                                $('body .devvn_readmore_flatsome_less_2').hide();
                                $('body .devvn_readmore_flatsome_more_2').show();
                            });
                        }
                    }
                });
            })
        })(jQuery)
    </script>
    <?php
}


/* Hiển thị địa chỉ */
function thongtin(){
	if( get_field('dia_chi') ) {
		echo '<div class="dia-chi">';
		echo '<span class="dashicons dashicons-location"></span>'; echo the_field('dia_chi');
		echo '</div>';
        ?>
        <ul class="list-project list-pro"><li><img class="icon-pro" src="<?php echo get_stylesheet_directory_uri(); ?>/images/dien-tich.png" data-src="<?php echo get_stylesheet_directory_uri(); ?>/images/dien-tich.png" alt=""> <?php if( get_field('dien_tich') ) {echo the_field('dien_tich').' m2';}else{}?></li><li><img class="icon-pro" src="<?php echo get_stylesheet_directory_uri(); ?>/images/phong-ngu.png" alt=""><?php if( get_field('phong_ngu') ) {echo the_field('phong_ngu').' PN';}else{}?></li><li><img class="icon-pro" src="<?php echo get_stylesheet_directory_uri(); ?>/images/wc.png" alt=""> <?php if( get_field('phong_ve_sinh') ) {echo the_field('phong_ve_sinh').' WC';}else{}?></li></ul>
        <?php
	}
}
add_action('woocommerce_after_shop_loop_item_title','thongtin');

/* Hiển thị mô tả ngắn*/


/* Hiển thị Khuyến mãi*/
function khuyenmai(){
	if( get_field('khuyen_mai') ){
		echo '<div class="khuyen-mai">';
		echo the_field('khuyen_mai');
		echo '</div>';
	}
}
add_action('flatsome_product_box_actions','khuyenmai');

/* Hiển thị ảnh tác giả */



/* Hiển thị trạng thái*/
function trangthai(){
	if( get_field('trang_thai') ){
		echo '<div class="trang-thai-du-an">';
		echo the_field('trang_thai');
		echo '</div>';
	}
}
add_action('flatsome_product_box_tools_top','trangthai');

/* === Hệ thống đếm lượt xem sản phẩm === */
function nddt_track_post_views($post_id) {
    if (!is_single()) return;
    if (empty($post_id)) {
        global $post;
        $post_id = $post->ID;
    }
    // Không đếm cho admin, bot
    if (is_admin() || current_user_can('manage_options')) return;
    if (defined('DOING_AJAX') && DOING_AJAX) return;
    
    $count = (int) get_post_meta($post_id, '_nddt_post_views', true);
    $count++;
    update_post_meta($post_id, '_nddt_post_views', $count);
}
add_action('wp_head', 'nddt_track_post_views_on_load');
function nddt_track_post_views_on_load() {
    if (is_single() && get_post_type() === 'product') {
        nddt_track_post_views(get_the_ID());
    }
}

function nddt_get_post_views($post_id) {
    $count = get_post_meta($post_id, '_nddt_post_views', true);
    if (empty($count) || !is_numeric($count)) {
        // Gán giá trị ban đầu là 0 cho sản phẩm chưa có lượt xem
        $count = 0;
        update_post_meta($post_id, '_nddt_post_views', $count);
    }
    return (int) $count;
}
/* === End Hệ thống đếm lượt xem === */

/* Hiển thị giá bán + lượt xem */
function giaban(){
	echo '<div class="gia-ban">';
	
        echo '<div class="left">';
        echo '<span class="gia-label">Giá:</span> ';
        global $product;
        if( $product && $product->is_on_sale() ) {
            echo '<span>' . gia_num_forvietnamese($product->get_sale_price()) . '</span>';
            echo '<del style="font-size: 1em; margin-left: 8px; color: #0056b3; font-weight: bold;">' . gia_num_forvietnamese($product->get_regular_price()) . '</del>';
        } else {
            echo '<span>';
            if(Gia_goc()!=""){echo gia_num_forvietnamese(Gia_goc());}else{echo "Liên hệ";}
            echo '</span>';
        }
        echo '</div>';
  
        // Hiển thị lượt xem bên phải
        $views = nddt_get_post_views(get_the_ID());
        echo '<div class="nddt-view-count">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:3px;"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
        echo '<span>' . number_format($views) . ' view</span>';
        echo '</div>';
	
	echo '</div>';
}					
add_action('flatsome_product_box_after','giaban');
/* End Hiển thị giá bán + lượt xem */


//
function count_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
        foreach ($paragraphs as $index => $paragraph) {
                if ( trim( $paragraph ) ) {
                        $paragraphs[$index] .= $closing_p;
                }
                if ( $paragraph_id == $index + 1 ) {
                        $paragraphs[$index] .= $insertion;
                }
        }
 
        return implode( '', $paragraphs );
}

//Chèn bài liên quan vào giữa nội dung
 
add_filter( 'the_content', 'prefix_insert_post_ads' );
 
function prefix_insert_post_ads( $content ) {
 
        $related_posts= "<div class='meta-related'><span class='tham-khao-tin'>Tham khảo các tin liên quan:</span>".do_shortcode('[related_posts_by_tax title=""]')."</div>";
 
        if ( is_single() ) {
                $content .= $related_posts;
                
                if ( is_singular('product') ) {
                    $phone = get_option('nddt_phone_number', '090 298 3367');
                    $phone_clean = preg_replace('/[^0-9]/', '', $phone);
                    if (!empty($phone)) {
                        $phone_html = '<div class="nddt-phone-contact" style="margin: 20px 0; padding: 15px 20px; background: linear-gradient(135deg, #ff6b35, #f7c948); border-radius: 10px; text-align: center;">';
                        $phone_html .= '<a href="tel:' . esc_attr($phone_clean) . '" style="color: #fff; text-decoration: none; font-size: 18px; font-weight: 700; display: flex; align-items: center; justify-content: center; gap: 8px;">';
                        $phone_html .= '<span style="display:inline-flex;align-items:center;"><svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="#fff"><path d="M6.62 10.79a15.053 15.053 0 006.59 6.59l2.2-2.2a1.003 1.003 0 011.01-.24c1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.1.31.03.66-.25 1.01l-2.2 2.21z"/></svg></span> ';
                        $phone_html .= 'Liên hệ ngay: ' . esc_html($phone);
                        $phone_html .= '</a></div>';
                        $content .= $phone_html;
                    }
                }
                return $content;
        }
 
        return $content;
}
 
/* === Fix nút Kết nối Zalo - chuyển từ tel: sang zalo.me === */
add_action('wp_footer', 'nddt_fix_zalo_button_link');
function nddt_fix_zalo_button_link() {
    if (!is_product()) return;
    $phone = get_option('nddt_phone_number', '090 298 3367');
    $phone_clean = preg_replace('/[^0-9]/', '', $phone);
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Tìm nút "Kết nối Zalo" và đổi link sang zalo.me
        var links = document.querySelectorAll('a.button');
        for (var i = 0; i < links.length; i++) {
            var span = links[i].querySelector('span');
            if (span && span.textContent.trim().toLowerCase().indexOf('zalo') !== -1) {
                links[i].href = 'https://zalo.me/<?php echo esc_js($phone_clean); ?>';
                links[i].target = '_blank';
            }
        }
    });
    </script>
    <?php
}


function devvn_ux_builder_element(){
    add_ux_builder_shortcode('devvn_viewnumber', array(
        'name'      => __('Search cho Danh mục'),
        'category'  => __('Content'),
        'priority'  => 1,
        'options' => array(
            'textbox'    =>  array(
                'type' => 'textfield',
                'heading' => 'Nhập danh mục',
                'default' => '',
             
                //'max'   => 2
            ),
        ),
    ));
}
add_action('ux_builder_setup', 'devvn_ux_builder_element');
 
function devvn_viewnumber_func($atts){
    return ndt_search_form_shortcode_render();
}
add_shortcode('devvn_viewnumber', 'devvn_viewnumber_func');


function gia_num_forvietnamese( $num = false ) {
    $num = trim($num);
    if (!$num || !is_numeric($num)) return $num;
    
    $num = (float) $num;
    
    // >= 1 tỷ: hiển thị X.XX tỷ
    if ($num >= 1000000000) {
        $ty = $num / 1000000000;
        // Làm tròn 2 chữ số, bỏ số 0 thừa
        $formatted = rtrim(rtrim(number_format($ty, 2, '.', ''), '0'), '.');
        return $formatted . ' tỷ ';
    }
    
    // >= 1 triệu: hiển thị X triệu
    if ($num >= 1000000) {
        $trieu = $num / 1000000;
        $formatted = rtrim(rtrim(number_format($trieu, 1, '.', ''), '0'), '.');
        return $formatted . ' triệu ';
    }
    
    return number_format($num, 0, '.', ',') . ' ';
}

function Gia_goc() {
    global $product;
    if( $product->is_on_sale() ) {
        return $product->get_regular_price();
    }else{
        return $product->get_regular_price();
    }
   
}

/* === NDT Search Form - Thanh tim kiem BDS === */

/* === Register Loại Bất Động Sản Taxonomy === */
add_action('init', 'ndt_register_loai_bds_taxonomy');
function ndt_register_loai_bds_taxonomy() {
    $labels = array(
        'name'              => 'Loại bất động sản',
        'singular_name'     => 'Loại bất động sản',
        'search_items'      => 'Tìm kiếm',
        'all_items'         => 'Tất cả Loại BĐS',
        'parent_item'       => 'Loại BĐS cha',
        'parent_item_colon' => 'Loại BĐS cha:',
        'edit_item'         => 'Sửa Loại BĐS',
        'update_item'       => 'Cập nhật',
        'add_new_item'      => 'Thêm Loại BĐS mới',
        'new_item_name'     => 'Tên mới',
        'menu_name'         => 'Loại bất động sản',
    );
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'loai-bds'),
    );
    register_taxonomy('loai_bds', array('product'), $args);
}

/* === Move "Tham khảo các tin liên quan" to bottom (shortcode position) === */

// Shortcode outputs a placeholder + JS to move the "Tham khảo" block here
add_shortcode('nk_loan_calculator', function() {
    return '<div id="nddt-tham-khao-target"></div>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        var source = document.querySelector(".meta-related");
        var target = document.getElementById("nddt-tham-khao-target");
        if (source && target) {
            target.appendChild(source);
        }
    });
    </script>';
});

/* === Fix typo: Bắt → Bất động sản === */
add_filter('the_content', 'ndt_fix_bat_dong_san_typo');
function ndt_fix_bat_dong_san_typo($content) {
    return str_replace('Bắt động sản', 'Bất động sản', $content);
}

// CSS
function ndt_search_form_styles() {
?>
<style>
/* ===================================================
   Product Card Attributes - Canh trái/giữa/phải
   =================================================== */
ul.list-pro {
    display: flex !important;
    justify-content: space-between !important;
    align-items: center !important;
    width: 100% !important;
    padding: 0 !important;
    margin-top: 10px !important;
    list-style: none !important;
    box-sizing: border-box !important;
}
ul.list-pro li {
    display: flex !important;
    align-items: center !important;
    padding: 0 !important;
    margin: 0 !important;
    white-space: nowrap !important;
    flex: 1 !important;
}
/* Diện tích - canh trái */
ul.list-pro li:first-child {
    justify-content: flex-start !important;
}
/* Phòng ngủ - canh giữa */
ul.list-pro li:nth-child(2) {
    justify-content: center !important;
}
/* WC - canh phải */
ul.list-pro li:last-child {
    justify-content: flex-end !important;
}

/* ===================================================
   Banner Full Width & Height Fix
   =================================================== */
/* Force banner section full-width - targets the wrapper section */
#section_1480909809,
.section-tim-kiem {
    width: 100vw !important;
    max-width: 100vw !important;
    margin-left: calc(-50vw + 50%) !important;
    margin-right: calc(-50vw + 50%) !important;
}

/* ===================================================
   Price Display - Larger for readability
   =================================================== */

.gia-ban {
    padding: 6px 12px 6px !important;
    margin: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: space-between !important;
    flex-wrap: nowrap !important;
}
.gia-ban .left {
    color: #1a6e3a !important;
    flex-shrink: 0;
}
.gia-ban .left .gia-label {
    font-size: 18px !important;
    font-weight: bold !important;
    color: #1a6e3a !important;
}
.gia-ban .left span:not(.gia-label) {
    font-size: 18px !important;
    font-weight: 800 !important;
    color: #d32f2f !important;
}
/* Lượt xem styling */
.nddt-view-count {
    display: flex;
    align-items: center;
    gap: 2px;
    color: #888 !important;
    font-size: 12px !important;
    font-weight: 500 !important;
    white-space: nowrap;
    flex-shrink: 0;
}
.nddt-view-count svg {
    color: #999;
    flex-shrink: 0;
}
.nddt-view-count span {
    font-size: 12px !important;
    font-weight: 500 !important;
    color: #888 !important;
}
@media (max-width: 767px) {
    .gia-ban .left .gia-label {
        font-size: 16px !important;
    }
    .gia-ban .left span:not(.gia-label) {
        font-size: 16px !important;
    }
    .nddt-view-count {
        font-size: 11px !important;
    }
    .nddt-view-count span {
        font-size: 11px !important;
    }
}

/* ===================================================
   "NHÀ BÁN GẤP" Section Title Styling
   =================================================== */

.div-title-home {
    padding: 8px 0 8px 18px;
    border-left: 4px solid #1a6e3a;
    margin-bottom: 10px;
}
.div-title-home p {
    font-size: 13px !important;
    color: #1a6e3a !important;
    font-weight: 600 !important;
    text-transform: uppercase;
    letter-spacing: 2px;
    margin-bottom: 2px !important;
}
.div-title-home h2 {
    font-size: 28px !important;
    font-weight: 800 !important;
    color: #222 !important;
    letter-spacing: 1px;
    margin: 0 !important;
    line-height: 1.2 !important;
    background: linear-gradient(135deg, #1a6e3a 0%, #2a9d5c 50%, #1a6e3a 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}
@media (max-width: 549px) {
    .div-title-home h2 {
        font-size: 22px !important;
    }
    .div-title-home p {
        font-size: 11px !important;
        letter-spacing: 1.5px;
    }
    .div-title-home {
        padding-left: 12px;
        border-left-width: 3px;
    }
}

/* ===================================================
   Banner Full Width & Height Fix
   =================================================== */

/* Force banner section full-width - targets the wrapper section */
#section_1480909809,
.section-tim-kiem,
body.home #content > .section:first-child {
    width: 100vw !important;
    max-width: 100vw !important;
    margin-left: calc(-50vw + 50%) !important;
    margin-right: calc(-50vw + 50%) !important;
    box-sizing: border-box !important;
    overflow: hidden !important;
}

/* Banner height = 400px (80% of 500px) */
#banner-1759085012,
#banner-1759085012 .banner-inner,
#banner-1101671428,
#banner-1101671428 .banner-inner,
.section-tim-kiem .banner,
.section-tim-kiem .banner-inner {
    min-height: 400px !important;
    height: 400px !important;
}

/* Banner bg fill also needs to respect height */
#banner-1759085012 .banner-bg,
#banner-1101671428 .banner-bg,
.section-tim-kiem .banner-bg {
    min-height: 400px !important;
    height: 400px !important;
}

/* Ensure the section content also respects height */
.section-tim-kiem .section-content,
#section_1480909809 .section-content {
    min-height: 400px !important;
}
/* Mobile banner height = 240px (60% of 400px) */
@media (max-width: 549px) {
    #banner-1759085012,
    #banner-1759085012 .banner-inner,
    #banner-1101671428,
    #banner-1101671428 .banner-inner,
    .section-tim-kiem .banner,
    .section-tim-kiem .banner-inner {
        min-height: 240px !important;
        height: 240px !important;
    }
    #banner-1759085012 .banner-bg,
    #banner-1101671428 .banner-bg,
    .section-tim-kiem .banner-bg {
        min-height: 240px !important;
        height: 240px !important;
    }
    .section-tim-kiem .section-content,
    #section_1480909809 .section-content {
        min-height: 240px !important;
    }
    /* ===== HIDE GREEN BAR ON MOBILE ===== */
    
    /* 1. Override banner padding-top to match height */
    .section-tim-kiem .banner,
    .section-tim-kiem .banner.has-hover {
        padding-top: 240px !important;
        overflow: hidden !important;
    }
    
    /* 2. Section background → white (removes green) */
    .section-tim-kiem {
        background-color: #ffffff !important;
        background: #ffffff !important;
    }
    
    /* 3. Section-bg overlay → hide (this is the green layer) */
    .section-tim-kiem > .bg.section-bg,
    .section-tim-kiem > .section-bg {
        display: none !important;
    }
    
    /* 4. Section content background → white */
    .section-tim-kiem .section-content {
        background-color: #ffffff !important;
    }
    
    /* 5. Banner overlay transparent (dark overlay on banner image) */
    .section-tim-kiem .banner .overlay,
    .section-tim-kiem .video-overlay {
        background-color: transparent !important;
    }
    
    /* 6. Clip banner to prevent overflow */
    .section-tim-kiem .banner-inner {
        overflow: hidden !important;
    }

}

/* ===================================================
   NDDT Search Filter Bar - CSS (Restored 12:30 PM)
   =================================================== */

.nddt-filter-bar {
    width: 100%;
    max-width: 960px;
    margin: 15px auto 0;
    padding: 0;
    box-sizing: border-box;
}

.nddt-filter-row {
    display: flex;
    align-items: stretch;
    gap: 0;
    background: #ffffff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.nddt-filter-item {
    flex: 1;
    position: relative;
    border-right: 1px solid #e0e0e0;
}

.nddt-filter-item:last-child {
    border-right: none;
}

.nddt-filter-item input {
    width: 100%;
    height: 50px;
    padding: 10px 15px;
    border: none;
    outline: none;
    background: #ffffff;
    font-size: 14px;
    box-shadow: none;
}

.nddt-filter-item select {
    width: 100%;
    height: 50px;
    padding: 10px 35px 10px 15px;
    border: none;
    outline: none;
    background: #ffffff;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    appearance: none;
    -webkit-appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='%23666' d='M1.41 0L6 4.58 10.59 0 12 1.41l-6 6-6-6z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    box-sizing: border-box;
    margin: 0;
    border-radius: 0;
    box-shadow: none;
}

.nddt-filter-btn-wrap {
    flex: 0 0 auto;
    min-width: 130px;
}

.nddt-filter-search-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 50px;
    padding: 10px 20px;
    background-color: #1a6e3a;
    color: #ffffff;
    border: none;
    outline: none;
    font-size: 15px;
    font-weight: 700;
    cursor: pointer;
    box-sizing: border-box;
    margin: 0;
    border-radius: 0;
}

@media (max-width: 849px) {
    .nddt-filter-bar { max-width: 95%; margin-top: 12px; }
    .nddt-filter-row { flex-wrap: wrap; border-radius: 8px; }
    /* Keyword input - full width */
    .nddt-filter-item.nddt-filter-keyword {
        flex: 1 1 100%;
        border-right: none;
        border-bottom: 1px solid #e0e0e0;
    }
    /* Ngân sách (2nd) & Khu vực (3rd) - side by side */
    .nddt-filter-item:nth-child(2) {
        flex: 1 1 50%;
        border-right: 1px solid #e0e0e0;
        border-bottom: 1px solid #e0e0e0;
    }
    .nddt-filter-item:nth-child(3) {
        flex: 1 1 50%;
        border-right: none;
        border-bottom: 1px solid #e0e0e0;
    }
    /* Loại BĐS (4th) - full width */
    .nddt-filter-item:nth-child(4) {
        flex: 1 1 100%;
        border-right: none;
        border-bottom: none;
    }
    /* Tìm kiếm button - full width */
    .nddt-filter-btn-wrap {
        flex: 1 1 100%;
        min-width: 100%;
    }
    .nddt-filter-search-btn {
        border-radius: 0 0 8px 8px;
    }
}

@media (max-width: 549px) {
    .nddt-filter-bar { max-width: 92%; margin-top: 10px; }
    .nddt-filter-row { flex-wrap: wrap; border-radius: 10px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); }
    /* Keyword input - full width */
    .nddt-filter-item.nddt-filter-keyword {
        flex: 1 1 100%;
        border-right: none;
        border-bottom: 1px solid #e0e0e0;
    }
    .nddt-filter-item.nddt-filter-keyword input {
        height: 48px;
        font-size: 15px;
        padding: 10px 15px;
    }
    /* Ngân sách & Khu vực - side by side 50% each */
    .nddt-filter-item:nth-child(2) {
        flex: 1 1 50%;
        border-right: 1px solid #e0e0e0;
        border-bottom: 1px solid #e0e0e0;
    }
    .nddt-filter-item:nth-child(3) {
        flex: 1 1 50%;
        border-right: none;
        border-bottom: 1px solid #e0e0e0;
    }
    /* Loại BĐS - full width */
    .nddt-filter-item:nth-child(4) {
        flex: 1 1 100%;
        border-right: none;
        border-bottom: none;
    }
    .nddt-filter-item select {
        height: 48px;
        font-size: 14px;
        padding: 10px 35px 10px 15px;
    }
    /* Tìm kiếm button - full width */
    .nddt-filter-btn-wrap {
        flex: 1 1 100%;
        min-width: 100%;
    }
    .nddt-filter-search-btn {
        height: 50px;
        font-size: 16px;
        font-weight: 700;
        border-radius: 0 0 10px 10px;
        letter-spacing: 0.5px;
    }
}
</style>
<?php
}
add_action('wp_head', 'ndt_search_form_styles');

function ndt_parse_items_for_dropdown($raw) {
    $lines = explode("\n", str_replace("\r", "", $raw));
    $res = array();
    foreach($lines as $line) {
        $line = trim($line);
        if(empty($line)) continue;
        $parts = explode('|', $line);
        if(count($parts) >= 2) {
            $res[] = array('name' => trim($parts[0]), 'slug' => trim($parts[1]));
        } else {
            $res[] = array('name' => trim($parts[0]), 'slug' => sanitize_title(trim($parts[0])));
        }
    }
    return $res;
}

function ndt_search_form_shortcode_render() {
    $ns_raw = get_option('nddt_ngan_sach_items', "Dưới 3 tỷ|duoi-3-ty\n3 - 5 tỷ|3-5-ty\n5 - 7 tỷ|5-7-ty\n7 - 10 tỷ|7-10-ty\n10 - 15 tỷ|10-15-ty\nTrên 15 tỷ|tren-15-ty");
    
    $ns_cats = ndt_parse_items_for_dropdown($ns_raw);
    
    // Fetch from the new loai_bds taxonomy
    $lb_cats = get_terms(array('taxonomy'=>'loai_bds','hide_empty'=>false,'orderby'=>'name')); 
    if(is_wp_error($lb_cats)) $lb_cats = array();

    $kv_terms = get_terms(array('taxonomy'=>'dia-diem','hide_empty'=>false,'orderby'=>'name','parent'=>0));
    if(is_wp_error($kv_terms)) $kv_terms = array();

    $cur_s = isset($_GET['s']) ? esc_attr($_GET['s']) : '';
    $cur_ns = isset($_GET['ngan_sach']) ? sanitize_text_field($_GET['ngan_sach']) : '';
    $cur_kv = isset($_GET['khu_vuc']) ? sanitize_text_field($_GET['khu_vuc']) : '';
    $cur_lb = isset($_GET['loai_bds']) ? sanitize_text_field($_GET['loai_bds']) : '';

    ob_start();
    ?>
    <form method="get" action="<?php echo esc_url(home_url('/')); ?>" class="nddt-filter-bar-form">
        <input type="hidden" name="post_type" value="product" />
        <div class="nddt-filter-bar">
            <div class="nddt-filter-row">
                <div class="nddt-filter-item nddt-filter-keyword">
                    <input type="text" name="s" value="<?php echo esc_attr($cur_s); ?>" placeholder="Nhập địa điểm, tuyến đường, giá..." class="nddt-filter-input" />
                </div>
                <div class="nddt-filter-item">
                    <select name="ngan_sach">
                        <option value="">Ngân sách</option>
                        <?php foreach($ns_cats as $c): ?>
                        <option value="<?php echo esc_attr($c['slug']); ?>" <?php selected($cur_ns,$c['slug']); ?>><?php echo esc_html($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="nddt-filter-item">
                    <select name="khu_vuc">
                        <option value="">Khu vực</option>
                        <?php foreach($kv_terms as $t): ?>
                        <option value="<?php echo esc_attr($t->slug); ?>" <?php selected($cur_kv,$t->slug); ?>><?php echo esc_html($t->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="nddt-filter-item">
                    <select name="loai_bds">
                        <option value="">Loại bất động sản</option>
                        <?php foreach($lb_cats as $c): ?>
                        <option value="<?php echo esc_attr($c->slug); ?>" <?php selected($cur_lb,$c->slug); ?>><?php echo esc_html($c->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="nddt-filter-item nddt-filter-btn-wrap">
                    <button type="submit" class="nddt-filter-search-btn">Tìm kiếm</button>
                </div>
            </div>
        </div>
    </form>
    <?php
    return ob_get_clean();
}

function ndt_handle_search_filter($query) {
    if(is_admin() || !$query->is_main_query()) return;
    $tax_query = array();
    $meta_query = array();

    if(!empty($_GET['khu_vuc'])){
        $tax_query[] = array('taxonomy'=>'dia-diem','field'=>'slug','terms'=>sanitize_text_field($_GET['khu_vuc']));
    }
    if(!empty($_GET['loai_bds'])){
        $tax_query[] = array('taxonomy'=>'loai_bds','field'=>'slug','terms'=>sanitize_text_field($_GET['loai_bds']));
    }

    if(!empty($_GET['ngan_sach'])){
        $meta_query[] = array('key'=>'_nddt_ngan_sach','value'=>sanitize_text_field($_GET['ngan_sach']),'compare'=>'=');
    }

    if(!empty($tax_query)){
        $tax_query['relation'] = 'AND';
        $existing = $query->get('tax_query');
        if(!empty($existing) && is_array($existing)){
            $tax_query = array_merge(array('relation'=>'AND'), $existing, $tax_query);
        }
        $query->set('tax_query', $tax_query);
    }

    if(!empty($meta_query)){
        $meta_query['relation'] = 'AND';
        $existing = $query->get('meta_query');
        if(!empty($existing) && is_array($existing)){
            $meta_query = array_merge(array('relation'=>'AND'), $existing, $meta_query);
        }
        $query->set('meta_query', $meta_query);
    }
    
    if(!empty($tax_query) || !empty($meta_query)) {
        $query->set('post_type', 'product');
    }
}
add_action('pre_get_posts', 'ndt_handle_search_filter');

/* === Custom Meta Box for Ngân Sách (Right Sidebar) === */
add_action('add_meta_boxes', 'ndt_add_ngan_sach_meta_box');
function ndt_add_ngan_sach_meta_box() {
    add_meta_box(
        'nddt_ngan_sach_box',
        'Ngân sách (Lọc tìm kiếm)',
        'ndt_render_ngan_sach_meta_box',
        'product',
        'side',
        'core'
    );
}

function ndt_render_ngan_sach_meta_box($post) {
    $val = get_post_meta($post->ID, '_nddt_ngan_sach', true);
    
    $ns_raw = get_option('nddt_ngan_sach_items', "Dưới 3 tỷ|duoi-3-ty\n3 - 5 tỷ|3-5-ty\n5 - 7 tỷ|5-7-ty\n7 - 10 tỷ|7-10-ty\n10 - 15 tỷ|10-15-ty\nTrên 15 tỷ|tren-15-ty");
    $ns_cats = ndt_parse_items_for_dropdown($ns_raw);
    
    echo '<select name="_nddt_ngan_sach" style="width:100%;">';
    echo '<option value="">-- Không thiết lập --</option>';
    foreach($ns_cats as $c) {
        $selected = ($val == $c['slug']) ? 'selected="selected"' : '';
        echo '<option value="' . esc_attr($c['slug']) . '" ' . $selected . '>' . esc_html($c['name']) . '</option>';
    }
    echo '</select>';
    echo '<p class="description" style="margin-top:10px;">Chọn khoảng ngân sách để khách hàng có thể tìm thấy sản phẩm này trên bộ lọc trang chủ.</p>';
}

add_action('save_post_product', 'ndt_save_ngan_sach_meta_box');
function ndt_save_ngan_sach_meta_box($post_id) {
    if (array_key_exists('_nddt_ngan_sach', $_POST)) {
        update_post_meta($post_id, '_nddt_ngan_sach', sanitize_text_field($_POST['_nddt_ngan_sach']));
    }
}

/* === Admin Settings for Search Filter === */
add_action('admin_menu', 'ndt_search_filter_menu');
function ndt_search_filter_menu() {
    add_options_page('Tùy chọn Bộ lọc', 'Bộ lọc tìm kiếm', 'manage_options', 'ndt-search-filter', 'ndt_search_filter_page');
}

add_action('admin_init', 'ndt_search_filter_settings');
function ndt_search_filter_settings() {
    register_setting('ndt_search_filter_group', 'nddt_ngan_sach_items');
    register_setting('ndt_search_filter_group', 'nddt_goi_y_title');
    register_setting('ndt_search_filter_group', 'nddt_phone_number', array(
        'sanitize_callback' => 'sanitize_text_field',
        'default' => '090 298 3367',
    ));
}

function ndt_search_filter_page() {
    ?>
    <div class="wrap">
        <h1>Cài đặt Tùy chọn Bộ lọc Tìm kiếm</h1>
        <form method="post" action="options.php">
            <?php settings_fields('ndt_search_filter_group'); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Danh sách Ngân sách<br><small>(Hiển thị ở trang chủ & lúc đăng bài)</small></th>
                    <td>
                        <textarea name="nddt_ngan_sach_items" rows="8" style="width:100%;max-width:500px;"><?php echo esc_textarea(get_option('nddt_ngan_sach_items', "Dưới 3 tỷ|duoi-3-ty\n3 - 5 tỷ|3-5-ty\n5 - 7 tỷ|5-7-ty\n7 - 10 tỷ|7-10-ty\n10 - 15 tỷ|10-15-ty\nTrên 15 tỷ|tren-15-ty")); ?></textarea>
                        <p class="description">Mỗi dòng một mục. Định dạng: <code>Tên hiển thị|slug</code> (Ví dụ: <code>Dưới 3 tỷ|duoi-3-ty</code>)</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Tiêu đề mục Gợi ý<br><small>(Hiển thị dưới thanh tìm kiếm trang chủ)</small></th>
                    <td>
                        <input type="text" name="nddt_goi_y_title" value="<?php echo esc_attr(get_option('nddt_goi_y_title', '🏠 Gợi ý cho bạn')); ?>" style="width:100%;max-width:500px;" />
                        <p class="description">Nhập tiêu đề hiển thị phía trên danh sách sản phẩm gợi ý. Ví dụ: 🏠 Gợi ý cho bạn</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Số điện thoại liên hệ<br><small>(Hiển thị ở trang chi tiết sản phẩm)</small></th>
                    <td>
                        <input type="text" name="nddt_phone_number" value="<?php echo esc_attr(get_option('nddt_phone_number', '090 298 3367')); ?>" style="width:100%;max-width:500px;" placeholder="Ví dụ: 090 298 3367" />
                        <p class="description">Số điện thoại sẽ hiển thị ở cuối mô tả trang chi tiết sản phẩm dưới dạng: <strong>"Liên hệ ngay: 090 298 3367"</strong></p>
                    </td>
                </tr>
            </table>
            <?php submit_button('Lưu thay đổi'); ?>
        </form>
    </div>
    <?php
}


/* === Move Search Form Below Banner === */
add_action('wp_footer', 'ndt_move_search_form_js');
function ndt_move_search_form_js() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        var $form = $('.nddt-filter-bar-form');
        var $banner = $form.closest('.banner, .has-banner'); // Find the closest Flatsome banner
        if ($form.length && $banner.length) {
            // Move it directly below the banner
            $banner.after($form);
            // Add some margin so it doesn't touch the edges
            $form.css({
                'margin-top': '20px',
                'margin-bottom': '10px',
                'position': 'relative',
                'z-index': '99'
            });
        }
    });
    </script>
    <?php
}

/* === Random 5 Products Below Search Bar === */
add_action('wp_head', 'ndt_random_products_styles');
function ndt_random_products_styles() {
    if (!is_front_page() && !is_home()) return;
    ?>
    <style>
    /* Random Products - Full Width Marquee */
    .nddt-random-products {
        width: 100vw;
        margin-left: calc(-50vw + 50%);
        margin-right: calc(-50vw + 50%);
        overflow: hidden;
        padding: 0;
        margin-bottom: -15px; /* Giảm khoảng trắng bên dưới */
    }
    .nddt-random-products .nddt-rp-title {
        font-size: 20px;
        font-weight: 800;
        color: #1a6e3a;
        margin: 0 0 14px 0;
        text-align: left;
        padding-left: 22px;
        letter-spacing: 1px;
        text-transform: uppercase;
        border-left: 4px solid #1a6e3a;
        line-height: 1.3;
        background: linear-gradient(135deg, #1a6e3a 0%, #2a9d5c 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    .nddt-random-products .nddt-rp-track {
        display: flex;
        gap: 16px;
        animation: nddt-scroll 20s linear infinite;
        width: max-content;
    }
    .nddt-random-products:hover .nddt-rp-track {
        animation-play-state: paused;
    }
    @keyframes nddt-scroll {
        0% { transform: translateX(-50%); }
        100% { transform: translateX(0); }
    }
    .nddt-random-products .nddt-rp-card {
        flex: 0 0 220px;
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 1px 6px rgba(0,0,0,0.08);
        transition: transform 0.2s, box-shadow 0.2s;
        text-decoration: none;
        color: inherit;
        display: block;
    }
    .nddt-random-products .nddt-rp-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.15);
    }
    .nddt-random-products .nddt-rp-img {
        width: 100%;
        height: auto;
        object-fit: cover;
        display: block;
    }
    .nddt-random-products .nddt-rp-info {
        padding: 8px 10px 10px;
    }
    .nddt-random-products .nddt-rp-name {
        font-size: 13px;
        font-weight: 600;
        color: #333;
        line-height: 1.35;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin: 0 0 4px;
    }
    .nddt-random-products .nddt-rp-price {
        font-size: 13px;
        font-weight: 700;
        color: #1a6e3a;
        margin: 0;
    }
    @media (max-width: 849px) {
        .nddt-random-products .nddt-rp-card { flex: 0 0 200px; }
        .nddt-random-products .nddt-rp-track { gap: 12px; animation-duration: 15s; }
    }
    @media (max-width: 549px) {
        .nddt-random-products { margin-bottom: 12px; }
        .nddt-random-products .nddt-rp-card { flex: 0 0 160px; }
        .nddt-random-products .nddt-rp-track { gap: 10px; animation-duration: 12s; }
        .nddt-random-products .nddt-rp-name { font-size: 12px; }
        .nddt-random-products .nddt-rp-price { font-size: 12px; }
        .nddt-random-products .nddt-rp-info { padding: 6px 8px 8px; }
        .nddt-random-products .nddt-rp-title { padding-left: 16px; font-size: 16px; border-left-width: 3px; }
    }
    </style>
    <?php
}

add_action('wp_footer', 'ndt_random_products_render');
function ndt_random_products_render() {
    if (!is_front_page() && !is_home()) return;
    
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 4,
        'orderby'        => 'rand',
        'post_status'    => 'publish',
    );
    $products = new WP_Query($args);
    
    if (!$products->have_posts()) return;
    
    // Build cards HTML first so we can duplicate for seamless loop
    $cards_html = '';
    while ($products->have_posts()) {
        $products->the_post();
        $thumb = get_the_post_thumbnail_url(get_the_ID(), 'medium');
        if (!$thumb) $thumb = wc_placeholder_img_src('medium');
        $product = wc_get_product(get_the_ID());
        $price = '';
        if ($product) {
            $price = $product->get_price_html();
        }
        $cards_html .= '<a href="' . esc_url(get_the_permalink()) . '" class="nddt-rp-card">';
        $cards_html .= '<img src="' . esc_url($thumb) . '" alt="' . esc_attr(get_the_title()) . '" class="nddt-rp-img" loading="lazy" />';
        $cards_html .= '<div class="nddt-rp-info">';
        $cards_html .= '<p class="nddt-rp-name">' . esc_html(get_the_title()) . '</p>';
        if ($price) {
            $cards_html .= '<p class="nddt-rp-price">' . $price . '</p>';
        }
        $cards_html .= '</div></a>';
    }
    wp_reset_postdata();
    
    ?>
    <div id="nddt-random-products-container" style="display:none;">
        <div class="nddt-random-products">
            <p class="nddt-rp-title"><?php echo esc_html(get_option('nddt_goi_y_title', '🏠 Gợi ý cho bạn')); ?></p>
            <div class="nddt-rp-track">
                <?php echo $cards_html; // First set ?>
                <?php echo $cards_html; // Duplicate for seamless loop ?>
            </div>
        </div>
    </div>
    <script>
    jQuery(document).ready(function($) {
        var $rp = $('#nddt-random-products-container');
        var $form = $('.nddt-filter-bar-form');
        if ($rp.length && $form.length) {
            $form.after($rp);
            $rp.show();
        }
    });
    </script>
    <?php
}





if ( isset( $_GET['purge_lscache_now'] ) ) {
    do_action( 'litespeed_purge_all' );
    echo "LSCache Purged";
    exit;
}



add_action('wp_footer', 'nddt_add_nha_ban_gap_class');
function nddt_add_nha_ban_gap_class() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        $('.section').each(function() {
            var heading = $(this).find('.div-title-home h2').text().toUpperCase();
            if (heading.indexOf('BAN G') !== -1 || heading.indexOf('BÁN G') !== -1) {
                // Add exactly to the first 3 product titles
                $(this).find('.product-title a').slice(0, 3).addClass('nddt-highlight-red-title');
            }
        });
    });
    </script>
    <style>
    .nddt-highlight-red-title {
        font-size: 120% !important;
        color: #ff0000 !important;
    }
    </style>
    <?php
}


/* ===================================================================
   FAQ Section - Thay thế "Cảm nhận của khách hàng" trên trang chủ
   =================================================================== */
add_action('wp_footer', 'nddt_faq_section_replace_testimonials');
function nddt_faq_section_replace_testimonials() {
    // Only show on homepage - check multiple conditions
    $is_homepage = is_front_page() || is_home() || is_page('trang-mau') || is_page(2);
    if (!$is_homepage) return;
    ?>
    <style>
    /* Ẩn section "Cảm nhận của khách hàng" - cả desktop và mobile */
    #section_35713467,
    .section4 {
        display: none !important;
    }

    /* === FAQ Section Styling === */
    .nddt-faq-section {
        padding: 50px 0 60px;
        background: linear-gradient(135deg, #f8fdf9 0%, #eaf7ee 50%, #f5faf6 100%);
        position: relative;
        overflow: hidden;
    }
    .nddt-faq-section::before {
        content: '';
        position: absolute;
        top: -80px;
        right: -80px;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(26,110,58,0.06) 0%, transparent 70%);
        border-radius: 50%;
    }
    .nddt-faq-section::after {
        content: '';
        position: absolute;
        bottom: -60px;
        left: -60px;
        width: 160px;
        height: 160px;
        background: radial-gradient(circle, rgba(42,157,92,0.05) 0%, transparent 70%);
        border-radius: 50%;
    }
    .nddt-faq-container {
        max-width: 850px;
        margin: 0 auto;
        padding: 0 20px;
        position: relative;
        z-index: 1;
    }
    .nddt-faq-header {
        text-align: center;
        margin-bottom: 40px;
    }
    .nddt-faq-header .nddt-faq-subtitle {
        font-size: 13px;
        color: #1a6e3a;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 2.5px;
        margin-bottom: 8px;
        display: block;
    }
    .nddt-faq-header h2 {
        font-size: 32px;
        font-weight: 800;
        color: #222;
        margin: 0 0 12px;
        line-height: 1.3;
        background: linear-gradient(135deg, #1a6e3a 0%, #2a9d5c 50%, #1a6e3a 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    .nddt-faq-header p {
        color: #666;
        font-size: 15px;
        max-width: 550px;
        margin: 0 auto;
        line-height: 1.6;
    }

    /* FAQ Items */
    .nddt-faq-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    .nddt-faq-item {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(26,110,58,0.06);
        border: 1px solid rgba(26,110,58,0.08);
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .nddt-faq-item:hover {
        box-shadow: 0 4px 16px rgba(26,110,58,0.12);
        border-color: rgba(26,110,58,0.15);
    }
    .nddt-faq-item.nddt-faq-active {
        box-shadow: 0 6px 24px rgba(26,110,58,0.14);
        border-color: rgba(26,110,58,0.2);
    }
    .nddt-faq-question {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 18px 24px;
        cursor: pointer;
        user-select: none;
        gap: 16px;
        transition: background 0.2s ease;
    }
    .nddt-faq-question:hover {
        background: rgba(26,110,58,0.02);
    }
    .nddt-faq-question span {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        line-height: 1.5;
        flex: 1;
    }
    .nddt-faq-icon {
        width: 32px;
        height: 32px;
        min-width: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #eaf7ee 0%, #d4f0dc 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
    }
    .nddt-faq-icon svg {
        width: 14px;
        height: 14px;
        stroke: #1a6e3a;
        stroke-width: 2.5;
        fill: none;
        transition: transform 0.3s ease;
    }
    .nddt-faq-active .nddt-faq-icon {
        background: linear-gradient(135deg, #1a6e3a 0%, #2a9d5c 100%);
    }
    .nddt-faq-active .nddt-faq-icon svg {
        stroke: #fff;
        transform: rotate(180deg);
    }
    .nddt-faq-answer {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.4s ease, padding 0.3s ease;
    }
    .nddt-faq-active .nddt-faq-answer {
        max-height: 300px;
    }
    .nddt-faq-answer-inner {
        padding: 0 24px 20px;
        color: #555;
        font-size: 15px;
        line-height: 1.7;
        border-top: 1px solid rgba(26,110,58,0.08);
        padding-top: 16px;
    }

    /* CTA */
    .nddt-faq-cta {
        text-align: center;
        margin-top: 36px;
        padding-top: 28px;
        border-top: 1px solid rgba(26,110,58,0.1);
    }
    .nddt-faq-cta p {
        color: #555;
        font-size: 15px;
        margin-bottom: 14px;
    }
    .nddt-faq-cta a {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 28px;
        background: linear-gradient(135deg, #1a6e3a 0%, #2a9d5c 100%);
        color: #fff !important;
        border-radius: 50px;
        font-size: 15px;
        font-weight: 600;
        text-decoration: none !important;
        box-shadow: 0 4px 14px rgba(26,110,58,0.3);
        transition: all 0.3s ease;
    }
    .nddt-faq-cta a:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(26,110,58,0.4);
    }

    /* Responsive */
    @media (max-width: 767px) {
        .nddt-faq-section {
            padding: 35px 0 45px;
        }
        .nddt-faq-header h2 {
            font-size: 24px;
        }
        .nddt-faq-header .nddt-faq-subtitle {
            font-size: 11px;
            letter-spacing: 1.5px;
        }
        .nddt-faq-header p {
            font-size: 14px;
        }
        .nddt-faq-question {
            padding: 14px 16px;
        }
        .nddt-faq-question span {
            font-size: 14px;
        }
        .nddt-faq-answer-inner {
            padding: 0 16px 16px;
            padding-top: 12px;
            font-size: 14px;
        }
        .nddt-faq-icon {
            width: 28px;
            height: 28px;
            min-width: 28px;
        }
        .nddt-faq-icon svg {
            width: 12px;
            height: 12px;
        }
    }
    </style>

    <div id="nddt-faq-placeholder" style="display:none;">
        <section class="nddt-faq-section">
            <div class="nddt-faq-container">
                <div class="nddt-faq-header">
                    <span class="nddt-faq-subtitle">Hỗ trợ khách hàng</span>
                    <h2>Câu hỏi thường gặp</h2>
                    <p>Giải đáp những thắc mắc phổ biến khi mua bán nhà đất, giúp bạn an tâm trong mọi giao dịch.</p>
                </div>
                <div class="nddt-faq-list">
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Quy trình mua nhà qua Nhà Đất Duy Tân như thế nào?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Bạn chỉ cần liên hệ hotline hoặc gửi yêu cầu, chúng tôi sẽ tư vấn miễn phí, đưa bạn đi xem nhà phù hợp, hỗ trợ thương lượng giá, kiểm tra pháp lý và đồng hành đến khi hoàn tất công chứng sang tên.</div>
                        </div>
                    </div>
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Mua nhà cần chuẩn bị những giấy tờ gì?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Người mua cần chuẩn bị CMND/CCCD, sổ hộ khẩu, giấy đăng ký kết hôn (nếu có). Ngoài ra, nên kiểm tra kỹ sổ hồng/sổ đỏ, giấy phép xây dựng và tình trạng thế chấp của bất động sản trước khi giao dịch.</div>
                        </div>
                    </div>
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Chi phí mua bán nhà gồm những khoản nào?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Ngoài giá nhà, bạn cần chuẩn bị thêm phí công chứng (khoảng 0.1%), thuế thu nhập cá nhân (2%), lệ phí trước bạ (0.5%), và phí đăng bộ sang tên. Chúng tôi sẽ tư vấn chi tiết từng khoản để bạn nắm rõ.</div>
                        </div>
                    </div>
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Có hỗ trợ vay ngân hàng mua nhà không?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Có, chúng tôi hỗ trợ kết nối với các ngân hàng uy tín để bạn được vay với lãi suất ưu đãi, thời gian giải ngân nhanh. Thông thường có thể vay đến 70% giá trị căn nhà với thời hạn lên đến 25 năm.</div>
                        </div>
                    </div>
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Làm sao để kiểm tra pháp lý nhà đất trước khi mua?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Chúng tôi hỗ trợ kiểm tra sổ hồng tại Văn phòng đăng ký đất đai, xác minh tình trạng thế chấp, quy hoạch, tranh chấp. Mọi bất động sản đăng trên website đều được chúng tôi thẩm định pháp lý trước khi giới thiệu đến khách hàng.</div>
                        </div>
                    </div>
                    <div class="nddt-faq-item">
                        <div class="nddt-faq-question" onclick="nddt_toggleFaq(this)">
                            <span>Tôi muốn bán nhà thì có được hỗ trợ không?</span>
                            <div class="nddt-faq-icon"><svg viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg></div>
                        </div>
                        <div class="nddt-faq-answer">
                            <div class="nddt-faq-answer-inner">Chúng tôi hỗ trợ đăng tin, chụp ảnh chuyên nghiệp, định giá hợp lý và tìm khách mua phù hợp. Phí dịch vụ cạnh tranh, cam kết bán nhanh với giá tốt nhất thị trường. Liên hệ ngay để được tư vấn miễn phí!</div>
                        </div>
                    </div>
                </div>
                <div class="nddt-faq-cta">
                    <p>Bạn còn thắc mắc khác? Liên hệ ngay để được tư vấn miễn phí!</p>
                    <a href="tel:0902983367">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                        090 298 3367
                    </a>
                </div>
            </div>
        </section>
    </div>

    <script>
    function nddt_toggleFaq(el) {
        var item = el.parentElement;
        var wasActive = item.classList.contains('nddt-faq-active');
        // Close all
        var allItems = document.querySelectorAll('.nddt-faq-item');
        for (var i = 0; i < allItems.length; i++) {
            allItems[i].classList.remove('nddt-faq-active');
        }
        // Toggle clicked
        if (!wasActive) {
            item.classList.add('nddt-faq-active');
        }
    }
    // Inject FAQ section in place of testimonials
    jQuery(document).ready(function($) {
        var $faq = $('#nddt-faq-placeholder');
        if (!$faq.length) return;
        
        var faqHtml = $faq.html();
        var inserted = false;
        
        // Method 1: Find testimonials section by ID
        var $testimonialMobile = $('#section_35713467');
        if ($testimonialMobile.length) {
            $testimonialMobile.after(faqHtml);
            $testimonialMobile.remove();
            inserted = true;
        }
        
        // Method 2: Find section4 class (both desktop and mobile)
        if (!inserted) {
            var $section4 = $('.section4').first();
            if ($section4.length) {
                $section4.after(faqHtml);
                $section4.remove();
                inserted = true;
            }
        }
        
        // Method 3: Find by section6 (tin tức) and insert before it
        if (!inserted) {
            var $section6 = $('#section_1737627268');
            if ($section6.length) {
                $section6.before(faqHtml);
                inserted = true;
            }
        }
        
        // Method 4: Find by section6 class and insert before it
        if (!inserted) {
            var $section6cls = $('.section6').first();
            if ($section6cls.length) {
                $section6cls.before(faqHtml);
                inserted = true;
            }
        }
        
        // Method 5: Insert before footer as last resort
        if (!inserted) {
            var $footer = $('#footer');
            if ($footer.length) {
                $footer.before(faqHtml);
                inserted = true;
            }
        }
        
        // Also hide any remaining section4 elements (desktop testimonials)
        $('.section4').not('.nddt-faq-section').hide();
        
        $faq.remove();
    });
    </script>
    <?php
}


/* === FIX ZALO OG:IMAGE === */
add_action('wp_head', 'nddt_force_zalo_og_image', 1);
function nddt_force_zalo_og_image() {
    if (is_single()) {
        $post_id = get_the_ID();
        $title = get_the_title($post_id);
        $excerpt = get_the_excerpt($post_id);
        $url = get_permalink($post_id);
        $img = get_the_post_thumbnail_url($post_id, 'full');
        
        echo "\n";
    }
}

// Ngan Flatsome chen the Open Graph trung lap voi Yoast SEO
function disable_flatsome_open_graph() {
	remove_action( 'wp_head', 'flatsome_open_graph', 5 );
}
add_action( 'init', 'disable_flatsome_open_graph' );

// Fix for the gap below random products
add_action('wp_head', function() {
    echo '<style>
        .nddt-random-products { max-height: 320px !important; overflow: hidden !important; }
        .nddt-rp-card:empty { display: none !important; }
        @media (max-width: 767px) {
            .nddt-random-products { max-height: 320px !important; overflow: hidden !important; }
        }
    </style>';
});

/* === RUT GON LINK BO LOC NHA DAT === */
add_action('init', 'custom_shorten_search_url', 1);

function custom_shorten_search_url() {
    if (isset($_GET['sq']) && !empty($_GET['sq'])) {
        $hash = sanitize_text_field($_GET['sq']);
        $saved_query = get_transient('short_url_' . $hash);

        if ($saved_query && is_array($saved_query)) {
            foreach ($saved_query as $key => $value) {
                $_GET[$key] = $value;
                $_REQUEST[$key] = $value;
            }
            $_SERVER['QUERY_STRING'] = http_build_query($_GET);
        }
        return; 
    }

    if (is_admin() || (defined('DOING_AJAX') && DOING_AJAX)) return;

    if (empty($_GET)) return;

    if (isset($_GET['post_type']) && $_GET['post_type'] === 'product') {
        $keys = array_keys($_GET);
        $filter_keys = array_diff($keys, ['post_type', 's']);
        
        if (!empty($filter_keys) && !isset($_GET['sq'])) {
            $hash = substr(md5(uniqid(rand(), true)), 0, 6);
            set_transient('short_url_' . $hash, $_GET, 86400); 
            
            $clean_url = remove_query_arg($keys); 
            $short_url = add_query_arg('sq', $hash, $clean_url);
            
            wp_safe_redirect($short_url);
            exit;
        }
    }
}

add_action('wp_footer', 'force_short_url_js', 999);
function force_short_url_js() {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        let lastUrl = location.href; 
        new MutationObserver(() => {
            const url = location.href;
            if (url !== lastUrl) {
                lastUrl = url;
                if(url.includes('?post_type=product') && url.includes('&')) {
                    window.location.href = url;
                }
            }
        }).observe(document, {subtree: true, childList: true});
        
        const originalPushState = history.pushState;
        history.pushState = function(state, title, url) {
            originalPushState.apply(this, arguments);
            if(url && url.includes('?post_type=product') && url.includes('&')) {
                 window.location.href = url;
            }
        };
    });
    </script>
    <?php
}

/* === SPEED OPTIMIZATION: Disable Cart Fragments === */
add_action('wp_enqueue_scripts', 'nddt_disable_cart_fragments', 99);
function nddt_disable_cart_fragments() {
    wp_dequeue_script('wc-cart-fragments');
}

/* === NANG CAP TIM KIEM MAC DINH CUA WORDPRESS === */
// Join bảng dữ liệu Taxonomy vào truy vấn tìm kiếm
add_filter('posts_join', 'nddt_advanced_search_join');
function nddt_advanced_search_join($join) {
    global $wpdb;
    $s = get_query_var('s');
    // Chỉ áp dụng ở ngoài frontend, khi đang search và có từ khóa
    if (is_search() && !is_admin() && !empty($s)) {
        $join .= " LEFT JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id ";
        $join .= " LEFT JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id ";
        $join .= " LEFT JOIN {$wpdb->terms} ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id ";
    }
    return $join;
}

// Bổ sung điều kiện tìm kiếm vào thuộc tính (Đường, Phường, v.v.)
add_filter('posts_where', 'nddt_advanced_search_where');
function nddt_advanced_search_where($where) {
    global $wpdb;
    $s = get_query_var('s');
    if (is_search() && !is_admin() && !empty($s)) {
        $where = preg_replace(
            "/\(\s*{$wpdb->posts}.post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "({$wpdb->posts}.post_title LIKE $1) OR ({$wpdb->terms}.name LIKE $1)",
            $where
        );
    }
    return $where;
}

// Tránh kết quả bị lặp trùng lặp (Duplicate)
add_filter('posts_distinct', 'nddt_advanced_search_distinct');
function nddt_advanced_search_distinct($where) {
    $s = get_query_var('s');
    if (is_search() && !is_admin() && !empty($s)) {
        return "DISTINCT";
    }
    return $where;
}

/* === Custom UX Products Pagination for Homepage === */
function nddt_custom_ux_products_shortcode($atts, $content = null, $tag = '') {
    $is_main = is_front_page() && isset($atts['products']) && $atts['products'] == '12';
    $paged = 1;
    
    if ( $is_main ) {
        $paged = (get_query_var('paged')) ? get_query_var('paged') : ((get_query_var('page')) ? get_query_var('page') : 1);
        if(!is_array($atts)) $atts = array();
        $atts['page_number'] = $paged;
    }
    
    // Call original function
    $output = ux_products($atts, $content, $tag);
    
    if ( $is_main ) {
        $query_args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 12,
            'paged' => $paged,
            'fields' => 'ids',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_visibility',
                    'field'    => 'name',
                    'terms'    => array('exclude-from-catalog', 'exclude-from-search'),
                    'operator' => 'NOT IN',
                ),
            ),
        );
        $products_query = new WP_Query($query_args);
        $total_pages = $products_query->max_num_pages;
        
        if ($total_pages > 1) {
            $big = 999999999;
            $pagination = paginate_links( array(
                'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                'format'    => '?paged=%#%',
                'current'   => $paged,
                'total'     => $total_pages,
                'prev_text' => '<i class="icon-angle-left"></i>',
                'next_text' => '<i class="icon-angle-right"></i>',
                'type'      => 'list',
                'end_size'  => 3,
                'mid_size'  => 3
            ) );
            
            if ($pagination) {
                $pagination = str_replace("<ul class='page-numbers'>", "<ul class='page-numbers nav-pagination links text-center'>", $pagination);
                $output .= '<div class="container"><div class="row"><div class="col small-12"><div class="nddt-pagination" style="width:100%; text-align:center; padding: 20px 0;">' . $pagination . '</div></div></div></div>';
            }
        }
    }
    
    return $output;
}
add_action('wp_loaded', function() {
    remove_shortcode('ux_products');
    add_shortcode('ux_products', 'nddt_custom_ux_products_shortcode');
}, 99);




add_action('wp_head', 'nddt_badge_ban_gap_css');
function nddt_badge_ban_gap_css() {
    ?>
    <style>
        .box-image:has(.badge-container) { overflow: visible !important; }
        .slider-wrapper .flickity-viewport { overflow: hidden !important; padding: 30px !important; margin: -30px !important; }
        .badge-container {
            top: 0 !important;
            left: 0 !important;
            right: auto !important;
            margin: 0 !important;
            padding: 0 !important;
        }
        .onsale.nddt-ban-gap-badge {
            background: linear-gradient(135deg, rgba(255,0,0,0.7), rgba(160,0,0,0.7)) !important;
            color: #ffff00 !important;
            font-size: 16px !important;
            font-weight: 800 !important;
            text-transform: uppercase !important;
            padding: 0 !important;
            margin: 0 !important;
            width: 55px !important;
            height: 55px !important;
            line-height: 55px !important;
            border-radius: 50% !important;
            box-shadow: 0 4px 10px rgba(0,0,0,0.4), inset 0 0 5px rgba(255,255,255,0.4) !important;
            border: 2px dashed #ffff00 !important;
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
            z-index: 99 !important;
            transform: rotate(-15deg) !important;
            backdrop-filter: blur(2px) !important;
            -webkit-backdrop-filter: blur(2px) !important;
            animation: pulse-gap 1.5s infinite !important;
        }
        @keyframes pulse-gap {
            0% { transform: rotate(-15deg) scale(0.95); box-shadow: 0 0 0 0 rgba(255,0,0, 0.7); }
            70% { transform: rotate(-15deg) scale(1.05); box-shadow: 0 0 0 10px rgba(255,0,0, 0); }
            100% { transform: rotate(-15deg) scale(0.95); box-shadow: 0 0 0 0 rgba(255,0,0, 0); }
        }
    </style>
    <?php
}



/* === Sửa lỗi layout section title - SAFE VERSION === */
add_action('wp_head', 'nddt_fix_section_layout_css');
function nddt_fix_section_layout_css() {
    ?>
    <style>
        .nddt-fixed-section .section-content > p, .nddt-fixed-section .row > p {
            display: none !important;
            margin-bottom: 0 !important;
            padding-bottom: 0 !important;
        }
        .nddt-fixed-section .div-title-home h2 {
            margin-bottom: 0 !important;
            padding-bottom: 0 !important;
            position: relative;
            top: 5px;
        }
        .nddt-title-row-bg {
            position: relative;
            padding-top: 15px !important;
            padding-bottom: 10px !important;
            margin-bottom: 20px !important;
        }
        .nddt-title-row-bg > .col {
            padding-bottom: 0 !important;
        }
        .nddt-title-row-bg::before {
            content: '';
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 100vw;
            height: 100%;
            background-color: inherit;
            z-index: -1;
        }
    </style>
    <?php
}

add_action('wp_footer', 'nddt_fix_section_layout_js', 999);
function nddt_fix_section_layout_js() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        $('.section').each(function() {
            var $title = $(this).find('.div-title-home');
            if ($title.length > 0 && $title.text().toUpperCase().indexOf('BẤT ĐỘNG SẢN') !== -1) {
                $(this).addClass('nddt-fixed-section');
                $(this).find('.section-content > p, .row > p').remove();
                var sectionBg = $(this).css('background-color');
                if (sectionBg && sectionBg !== 'rgba(0, 0, 0, 0)' && sectionBg !== 'transparent') {
                    $(this).css({'background-color': 'transparent', 'padding-top': '0', 'padding-bottom': '0'});
                    $(this).find('> .section-bg').hide();
                    var $titleRow = $title.closest('.row');
                    $titleRow.addClass('nddt-title-row-bg');
                    $titleRow.css('background-color', sectionBg);
                }
            }
        });
    });
    </script>
    <?php
}