<?php
//Lấy lượt xem 
function getPostViews($postID)
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "01 lượt xem";
    }
    return $count . ' lượt xem';
}
//Dếm lượt xem
function setPostViews($postID)
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
//Hiển thị số lượt xem bài viết trong Dashboard
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2);
function posts_column_views($defaults)
{
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id)
{
    if ($column_name === 'post_views') {
        echo getPostViews(get_the_ID());
    }
}

function wpb_track_post_views($post_id)
{
    if (!is_single())
        return; // Tính lượt đọc cho trang

    $count_key = 'post_views_count';
    $count = get_post_meta($post_id, $count_key, true);

    if ($count === '') {
        $count = 0;
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
    } else {
        $count++;
        update_post_meta($post_id, $count_key, $count);
    }
}
add_action('wp_head', 'wpb_track_post_views');


//Hàm tùy chỉnh số lượt xem 
function getPostViewsNumber($postID)
{
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    return $count;
}








// Tạo widget danh muc bai viet
class Category_Posts_Widget extends WP_Widget
{

    // Constructor function
    public function __construct()
    {
        parent::__construct(
            'category_posts_widget',
            'Danh Mục Bài Viết',
            array('description' => 'Hiển thị danh mục bài viết')
        );
    }

    // Hiển thị nội dung widget
// Hiển thị nội dung widget
    public function widget($args, $instance)
    {
        $title = apply_filters('widget_title', $instance['title']);

        echo $args['before_widget'];
        if (!empty($title)) {
            echo $args['before_title'] . $title . $args['after_title'];
        }

        // Lấy tất cả các danh mục
        $categories = get_categories(
            array(
                'hide_empty' => 0,
                // hiển thị cả danh mục không có bài viết nào
            )
        );

        echo '<div>';
        foreach ($categories as $category) {
            // Kiểm tra xem danh mục có danh mục con hay không và không phải là chuyên mục cha và không phải là "Chưa phân loại"
            $is_parent = get_categories(
                array(
                    'hide_empty' => 0,
                    'parent' => $category->term_id,
                )
            );

            if (empty($is_parent) && $category->term_id !== get_option('default_category') && $category->category_parent != 0) {
                // Lấy số bài viết trong chuyên mục
                $category_info = get_term($category->term_id, 'category');
                $post_count = $category_info->count;

                echo '<p class="cac"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a><div class="pont">' . $post_count . '</div></p>';
            }
        }
        echo '</div>';

        echo $args['after_widget'];
    }



    public function form($instance)
    {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">Tiêu đề:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

        return $instance;
    }
}

function register_category_posts_widget()
{
    register_widget('Category_Posts_Widget');
}
add_action('widgets_init', 'register_category_posts_widget');












// Bai viet xem nhieu
class Popular_Posts_Widget extends WP_Widget
{

    public function __construct()
    {
        parent::__construct(
            'popular_posts_widget',
            'Widget Bài viết xem nhiều',
            // Tên widget
            array(
                'description' => 'Hiển thị 5 bài viết xem nhiều nhất và tùy chỉnh CSS cho bài viết đầu tiên.',
            )
        );
    }

    public function widget($args, $instance)
    {

        $title = apply_filters('widget_title', $instance['title']);
        $num_posts = isset($instance['num_posts']) ? absint($instance['num_posts']) : 5;

        echo $args['before_widget'];

        if (!empty($title)) {
            echo $args['before_title'] . $title . $args['after_title'];
        }

        $popular_posts = new WP_Query(
            array(
                'post_type' => 'post',
                'posts_per_page' => $num_posts,
                'meta_key' => 'post_views_count',
                'orderby' => 'meta_value_num',
                'order' => 'DESC',
            )
        );

        if ($popular_posts->have_posts()) {
            echo '<div class="popular-posts-widget">';
            $first_post = 0;
            while ($popular_posts->have_posts()) {
                $popular_posts->the_post();
                $post_classes = $first_post ? 'other-popular-post' : 'first-popular-post';
                $first_post++;
                ?>
                <div class="<?php echo esc_attr($post_classes); ?>">
                    <?php if ($first_post == 1): ?>
                        <div class="post-number">
                            <?php echo $first_post; ?>
                        </div>
                        <div class="txt">
                            <h3><a href="<?php the_permalink(); ?>">
                                    <?php the_title(); ?>
                                </a></h3>
                        </div>
                        <!-- <div class="published-time">
                                <p>
                                    <?php echo get_the_time('d/m/Y'); ?>
                                </p>
                            </div> -->
                    <?php else: ?>
                        <div class="post-number">
                            <?php echo $first_post; ?>
                        </div>
                        <div class="txt">
                            <h3><a href="<?php the_permalink(); ?>">
                                    <?php the_title(); ?>
                                </a></h3>
                        </div>
                        <!-- <div class="published-time">
                                <p>
                                    <?php echo get_the_time('d/m/Y'); ?>
                                </p>
                            </div> -->

                    <?php endif; ?>
                </div>
                <?php
            }
            echo '</div>';
            wp_reset_postdata();
        }

        echo $args['after_widget'];
    }

    public function form($instance)
    {
        $title = isset($instance['title']) ? esc_attr($instance['title']) : '';
        $num_posts = isset($instance['num_posts']) ? absint($instance['num_posts']) : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">Tiêu đề:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('num_posts'); ?>">Số lượng bài viết:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('num_posts'); ?>"
                name="<?php echo $this->get_field_name('num_posts'); ?>" type="number" min="1"
                value="<?php echo $num_posts; ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['num_posts'] = absint($new_instance['num_posts']);
        return $instance;
    }
}

function register_popular_posts_widget()
{
    register_widget('Popular_Posts_Widget');
}

add_action('widgets_init', 'register_popular_posts_widget');



add_filter('gettext', 'change_search_text');
function change_search_text($translated_text)
{
    if ('Search' === $translated_text) {
        $translated_text = 'Tìm kiếm';
    }
    return $translated_text;
}






// Tạo một widget mới để gọi form tìm kiếm của Flatsome
class Flatsome_Search_Widget extends WP_Widget
{

    function __construct()
    {
        parent::__construct(
            'flatsome_search_widget', // ID của widget
            __('Flatsome Search', 'text_domain'), // Tên của widget
            array('description' => __('Display Flatsome search form', 'text_domain'), ) // Mô tả của widget
        );
    }

    public function widget($args, $instance)
    {
        echo $args['before_widget'];
        echo get_search_form();
        echo $args['after_widget'];
    }
}

function register_flatsome_search_widget()
{
    register_widget('Flatsome_Search_Widget');
}
add_action('widgets_init', 'register_flatsome_search_widget');

/*
 * Chống spam cho contact form 7
 * Author: levantoan
 * */
/*Thêm 1 field ẩn vào form cf7*/
add_filter('wpcf7_form_elements', 'devvn_check_spam_form_cf7');
function devvn_check_spam_form_cf7($html){
    $html = '<div style="display: none"><p><span class="wpcf7-form-control-wrap" data-name="devvn"><input size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false" value="" type="text" name="devvn"></span></p></div>' . $html;
    return $html;
}
/*Kiểm tra form đó mà được nhập giá trị thì là spam*/
add_action('wpcf7_posted_data', 'devvn_check_spam_form_cf7_vaild');
function devvn_check_spam_form_cf7_vaild($posted_data) {
    $submission = WPCF7_Submission::get_instance();
    if (!empty($posted_data['devvn'])) {
        $submission->set_status( 'spam' );
        $submission->set_response( 'You are Spamer' );
    }
    unset($posted_data['devvn']);
    return $posted_data;
}