<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;

class Rdg_Blocks_Sh_Query_Posts extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_SH_QUERY_POSTS;
    private $block_folder_name = BLOCK_RDG_SH_QUERY_POSTS;
    protected $block_title = 'SH Query Posts';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'query', 'post'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_styles_load = true;

    public function init() {
        $this->register_block();
        add_action('init', [$this, 'register_fields'], 2000);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
                'enqueue_style' => $rdg_helpers->webpack('sh_query_posts.css'),
                'enqueue_assets' => function() {
                    wp_register_script('sh_query_posts_script', RDGBLOCKS_PLUGIN_URL.'blocks/sh-query-posts/assets/js/sh-query-posts.js', [], '1', true);
                    wp_enqueue_script('sh_query_posts_script');
                    wp_localize_script('sh_query_posts_script','sh_query_posts_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                },
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        $post_types = $this->getPostTypeTaxonomies();

        $fields = [
            array(
                'key' => 'key_sh_query_posts_type',
                'label' => 'Post Type',
                'name' => 'post_type',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => $post_types['post_types'] + ['all' => 'All Custom Post Type'],
                'default_value' => 'post',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
            array(
                'key' => 'key_sh_query_posts_show',
                'label' => 'Show',
                'name' => 'show',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_sh_query_posts_type',
                            'operator' => '!=',
                            'value' => 'all',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'latest' => 'Latest Posts',
                    'specific' => 'Specific Posts',
                    'external' => 'External Posts',
                ),
                'default_value' => 'latest',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
            array(
                'key' => 'key_sh_query_posts_show_all',
                'label' => 'Show',
                'name' => 'show',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_sh_query_posts_type',
                            'operator' => '==',
                            'value' => 'all',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'specific' => 'Specific Posts',
                    'external' => 'External Posts',
                ),
                'default_value' => 'latest',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
        ];

        $fields = $this->generateTaxonomiesFields($post_types, $fields);
        $fields = $this->generateElementsFields($post_types, $fields);

        $last_fields = [
            array(
                'key' => 'key_sh_query_posts_quantity',
                'label' => 'Quantity',
                'name' => 'quantity',
                'aria-label' => '',
                'type' => 'number',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_sh_query_posts_show',
                            'operator' => '==',
                            'value' => 'latest',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 1,
                'min' => 1,
                'max' => 12,
                'placeholder' => '',
                'step' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'key_sh_query_posts_elements_external',
                'label' => 'List External Post',
                'name' => 'elements_external',
                'aria-label' => '',
                'type' => 'repeater',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_sh_query_posts_show',
                            'operator' => '==',
                            'value' => 'external',
                        ),
                    ),
                    array(
                        array(
                            'field' => 'key_sh_query_posts_show_all',
                            'operator' => '==',
                            'value' => 'external',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'layout' => 'block',
                'pagination' => 0,
                'min' => 0,
                'max' => 0,
                'collapsed' => '',
                'button_label' => 'Add Row',
                'rows_per_page' => 20,
                'acfe_repeater_stylised_button' => 0,
                'sub_fields' => array(
                    array(
                        'key' => 'key_sh_query_posts_elements_image',
                        'label' => 'Image',
                        'name' => 'image',
                        'aria-label' => '',
                        'type' => 'image',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                        'library' => 'all',
                        'min_width' => '',
                        'min_height' => '',
                        'min_size' => '',
                        'max_width' => '',
                        'max_height' => '',
                        'max_size' => '',
                        'mime_types' => '',
                        'preview_size' => 'medium',
                        'uploader' => '',
                        'acfe_thumbnail' => 0,
                        'upload_folder' => '',
                        'parent_repeater' => 'key_sh_query_posts_elements_external',
                    ),
                    array(
                        'key' => 'key_sh_query_posts_elements_title',
                        'label' => 'Title',
                        'name' => 'title',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                        'parent_repeater' => 'key_sh_query_posts_elements_external',
                    ),
                    array(
                        'key' => 'key_sh_query_posts_elements_content',
                        'label' => 'Content',
                        'name' => 'content',
                        'aria-label' => '',
                        'type' => 'textarea',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'rows' => '',
                        'placeholder' => '',
                        'new_lines' => '',
                        'acfe_textarea_code' => 0,
                        'parent_repeater' => 'key_sh_query_posts_elements_external',
                    ),
                    array(
                        'key' => 'key_sh_query_posts_elements_date',
                        'label' => 'Date / Time',
                        'name' => 'date',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '2023-01-01 10:59:00',
                        'prepend' => '',
                        'append' => '',
                        'parent_repeater' => 'key_sh_query_posts_elements_external',
                    ),
                    array(
                        'key' => 'key_sh_query_posts_elements_link',
                        'label' => 'Link Post',
                        'name' => 'link_post',
                        'aria-label' => '',
                        'type' => 'link',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                        'parent_repeater' => 'key_sh_query_posts_elements_external',
                    ),
                ),
            ),
        ];

        $fields = array_merge($fields, $last_fields);

        $fields[] = [
            'key' => 'key_sh_query_posts_elements_all',
            'label' => 'Elements',
            'name' => 'elements',
            'aria-label' => '',
            'type' => 'relationship',
            'instructions' => '',
            'required' => 1,
            'conditional_logic' => array(
                array(
                    array(
                        'field' => 'key_sh_query_posts_show_all',
                        'operator' => '==',
                        'value' => 'specific',
                    ),
                    array(
                        'field' => 'key_sh_query_posts_type',
                        'operator' => '==',
                        'value' => 'all',
                    ),
                ),
            ),
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'post_type' => $this->getAllPostTypes($post_types),
            'taxonomy' => '',
            'filters' => array(
                0 => 'search',
            ),
            'return_format' => 'object',
            'min' => 1,
            'max' => 20,
            'elements' => array(
                0 => 'featured_image',
            ),
        ];

        if (function_exists('acf_add_local_field_group')):
            acf_add_local_field_group(array(
                'key' => 'group_sh_query_posts_123456',
                'title' => 'SH Query Posts',
                'fields' => $fields,
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/sh-query-posts',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    private function getAllPostTypes($post_types) {
        $cpts = [];

        foreach ($post_types['post_types'] as $key => $post_type) {
            $cpts[] = $key;
        }

        return $cpts;
    }

    public function getPostTypeTaxonomies() {
        $post_types = get_post_types(['public' => true], 'object');

        unset($post_types['attachment']);
        unset($post_types['kaliforms_submitted']);

        $data = [
            'post_types' => [],
            'taxonomies' => [],
        ];

        foreach ($post_types as $post_type) {
            $data['post_types'][$post_type->name] = $post_type->label;
            $taxonomies = get_object_taxonomies($post_type->name);

            if (is_array($taxonomies) && isset($taxonomies[0])) {
                $data['taxonomies'][$post_type->name] = $taxonomies[0];
            }
        }

        return $data;
    }

    private function generateTaxonomiesFields($post_types, $fields) {
        if (is_array($post_types['post_types']) && count($post_types['post_types']) > 0) {
            foreach ($post_types['post_types'] as $slug => $post_type) {
                if (empty($post_types['taxonomies'][$slug])) continue;

                $fields[] = [
                    'key' => 'key_sh_query_posts_category_type_'.$slug,
                    'label' => 'Select Category Type',
                    'name' => 'select_category_type',
                    'aria-label' => '',
                    'type' => 'select',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'key_sh_query_posts_show',
                                'operator' => '==',
                                'value' => 'latest',
                            ),
                            array(
                                'field' => 'key_sh_query_posts_type',
                                'operator' => '==',
                                'value' => $slug,
                            ),
                        ),
                    ),
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'choices' => array(
                        'include' => 'Include Category',
                        'exclude' => 'Exclude Category',
                    ),
                    'default_value' => 'include',
                    'return_format' => 'value',
                    'multiple' => 0,
                    'allow_null' => 0,
                    'ui' => 0,
                    'ajax' => 0,
                    'placeholder' => '',
                ];

                $fields[] = [
                    'key' => 'key_sh_query_posts_category_include_'.$slug,
                    'label' => 'Category Include',
                    'name' => 'category_include',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'key_sh_query_posts_category_type_'.$slug,
                                'operator' => '==',
                                'value' => 'include',
                            ),
                            array(
                                'field' => 'key_sh_query_posts_type',
                                'operator' => '==',
                                'value' => $slug,
                            ),
                        ),
                    ),
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'taxonomy' => $post_types['taxonomies'][$slug],
                    'add_term' => 1,
                    'save_terms' => 0,
                    'load_terms' => 0,
                    'return_format' => 'id',
                    'field_type' => 'multi_select',
                    'allow_null' => 1,
                    'multiple' => 0,
                ];

                $fields[] = [
                    'key' => 'key_sh_query_posts_category_exclude_'.$slug,
                    'label' => 'Category Exclude',
                    'name' => 'category_exclude',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'key_sh_query_posts_category_type_'.$slug,
                                'operator' => '==',
                                'value' => 'exclude',
                            ),
                            array(
                                'field' => 'key_sh_query_posts_type',
                                'operator' => '==',
                                'value' => $slug,
                            ),
                        ),
                    ),
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'taxonomy' => $post_types['taxonomies'][$slug],
                    'add_term' => 1,
                    'save_terms' => 0,
                    'load_terms' => 0,
                    'return_format' => 'id',
                    'field_type' => 'multi_select',
                    'allow_null' => 1,
                    'multiple' => 0,
                ];
            }
        }

        return $fields;
    }

    private function generateElementsFields($post_types, $fields) {
        if (is_array($post_types['post_types']) && count($post_types['post_types']) > 0) {
            foreach ($post_types['post_types'] as $slug => $post_type) {
                $fields[] = [
                    'key' => 'key_sh_query_posts_elements_'.$slug,
                    'label' => 'Elements',
                    'name' => 'elements',
                    'aria-label' => '',
                    'type' => 'relationship',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'key_sh_query_posts_show',
                                'operator' => '==',
                                'value' => 'specific',
                            ),
                            array(
                                'field' => 'key_sh_query_posts_type',
                                'operator' => '==',
                                'value' => $slug,
                            ),
                        ),
                    ),
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'post_type' => array(
                        0 => $slug,
                    ),
                    'taxonomy' => '',
                    'filters' => array(
                        0 => 'search',
                        1 => 'taxonomy',
                    ),
                    'return_format' => 'object',
                    'min' => 1,
                    'max' => 20,
                    'elements' => array(
                        0 => 'featured_image',
                    ),
                ];
            }
        }

        return $fields;
    }

    public function getElementsType($fields) {
        $show = (!empty($fields['show'])) ? $fields['show'] : 'latest';
        $post_type = (!empty($fields['post_type'])) ? $fields['post_type'] : 'post';

        if (BLOCK_RDG_TYPE_SPECIFIC == $show) {
            return $fields['elements'];
        }

        if (BLOCK_RDG_TYPE_EXTERNAL === $show) {
            return $fields['elements_external'];
        }

        $get_quantity = (!empty($fields['quantity'])) ? $fields['quantity'] : null;
        $quantity = $get_quantity ? $get_quantity : 1;

        $category = '';
        $operator = 'IN';
        $select_category_type = (!empty($fields['select_category_type'])) ? $fields['select_category_type'] : null;

        if (!empty($select_category_type)) {
            if ('include' == $select_category_type && isset($fields['category_include']) && is_array($fields['category_include']) && count($fields['category_include']) > 0) {
                $category = $fields['category_include'];
            } elseif ('exclude' == $select_category_type && isset($fields['category_exclude']) && is_array($fields['category_exclude']) && count($fields['category_exclude']) > 0) {
                $operator = 'NOT IN';
                $category = $fields['category_exclude'];
            }
        }

        $args = [
            'post_type' => $post_type,
            'post_status' => 'publish',
            'posts_per_page' => $quantity,
        ];

        $taxonomy = null;
        $taxonomies = get_object_taxonomies($post_type);

        if (is_array($taxonomies) && count($taxonomies) > 0) {
            $taxonomy = $taxonomies[0];
        }

        if (is_array($category) && count($category) > 0 && !empty($taxonomy)) {
            $args['tax_query'] = [
                [
                    'taxonomy' => $taxonomy,
                    'field' => 'id',
                    'terms' => $category,
                    'operator' => $operator
                ]
            ];
        }

        $elements = (new WP_Query($args))->posts;
        wp_reset_postdata();

        return $elements;
    }

    public function getImage($image_id) {
        $post_thumbnail_id = get_post_thumbnail_id($image_id);

        if (empty($post_thumbnail_id)) {
            return plugins_url('assets/img/image-not-found.png', __FILE__);
        }

        $attachment = wp_get_attachment_image_src($post_thumbnail_id, 'posts-list');

        if (isset($attachment[0])) return $attachment[0];

        return plugins_url('assets/img/image-not-found.png', __FILE__);
    }

    public function getTaxonomy($post) {
        $term = null;
        $terms = null;
        $cpt_taxonomies = $this->getPostTypeTaxonomies();

        if (!isset($cpt_taxonomies['taxonomies'][$post->post_type])) return null;

        $terms = get_the_terms($post->ID, $cpt_taxonomies['taxonomies'][$post->post_type]);
        if (!is_array($terms)) {

            return null;
        }

        if (count($terms) == 1 ) return $terms[0];

        $parent = null;
        $terms_ids = [];

        foreach ($terms as $term) {
            $terms_ids[] = $term->term_id;

            if ($term->parent == 0 && $term->slug !== 'uncategorized') {
                $parent = $term;
            }
        }

        if ($parent !== null) {
            return $parent;
        }

        foreach ($terms as $term) {
            if (!in_array($term->parent, $terms_ids)) {
                return $term;
            }
        }

        return end($terms);
    }

    public function getAuthors($cpt = 'post') {
        global $wpdb;

        $query = "SELECT DISTINCT u.ID, u.display_name, u.user_email
            FROM $wpdb->users u
            INNER JOIN $wpdb->usermeta um ON u.ID = um.user_id
            INNER JOIN $wpdb->posts p ON u.ID = p.post_author
            WHERE um.meta_key = '{$wpdb->prefix}capabilities'
            AND (um.meta_value LIKE '%author%' OR um.meta_value LIKE '%administrator%' OR um.meta_value LIKE '%editor%')
            AND p.post_type = %s
            AND p.post_status = 'publish'";

        $author_array = [];
        $authors = $wpdb->get_results($wpdb->prepare($query, $cpt));

        foreach ($authors as $author) {
            $author_array[$author->ID] = ucfirst(strtolower(trim($author->display_name)));
        }

        asort($author_array);

        return $author_array;
    }

    public function getTermsFromTaxonomy($taxonomy) {
        if (empty($taxonomy)) return [];

        global $wpdb;
        $query = "SELECT t.term_id, t.name, tt.count
            FROM $wpdb->terms t
            INNER JOIN $wpdb->term_taxonomy tt ON t.term_id = tt.term_id
            INNER JOIN $wpdb->term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
            INNER JOIN $wpdb->posts p ON tr.object_id = p.ID
            WHERE tt.taxonomy = %s
            AND p.post_status = 'publish'
            GROUP BY t.term_id
            HAVING COUNT(p.ID) > 0";

        $terms = $wpdb->get_results($wpdb->prepare($query, $taxonomy));

        $terms_array = [];
        $term_uncategorized = get_term_by('slug', 'uncategorized', $taxonomy);

        if ($term_uncategorized instanceof WP_Term) {
            $terms_array[$term_uncategorized->term_id] = $term_uncategorized->name;
        }

        if (!is_array($terms) || count($terms) == 0) {
            if (count($terms_array) == 0) return [];
        }

        if (!is_wp_error($terms)) {
            foreach ($terms as $term) {
                $terms_array[$term->term_id] = trim($term->name);
            }
        }

        asort($terms_array);

        return $terms_array;
    }

    public function getTermsFromConfigure($taxonomy, $type, $configure_terms) {
        if (empty($taxonomy)) return [];

        $arg = [
            'taxonomy'   => $taxonomy,
            'hide_empty' => true,
        ];

        $arg[$type] = $configure_terms;
        $terms = get_terms($arg);

        $terms_array = [];
        if (!is_array($terms) || count($terms) == 0) {
            return [];
        }

        if (!is_wp_error($terms)) {
            foreach ($terms as $term) {
                $terms_array[$term->term_id] = trim($term->name);
            }
        }

        asort($terms_array);

        return $terms_array;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'sh-query-posts-author-date','slug' => 'sh-query-posts-author-date','color' => '#878787'],
            ['name' => 'sh-query-posts-author-by','slug' => 'sh-query-posts-author-by','color' => '#878787'],
            ['name' => 'sh-query-posts-author-separator','slug' => 'sh-query-posts-author-separator','color' => '#878787'],
            ['name' => 'sh-query-posts-input-bg','slug' => 'sh-query-posts-input-bg','color' => '#F6F7F8'],
            ['name' => 'sh-query-posts-input-border','slug' => 'sh-query-posts-input-border','color' => '#E5E5E5'],
            ['name' => 'sh-query-posts-input-hover','slug' => 'sh-query-posts-input-hover','color' => '#f75858'],
            ['name' => 'sh-query-posts-input-hover-c','slug' => 'sh-query-posts-input-hover-c','color' => '#ffffff'],
            ['name' => 'sh-query-posts-title','slug' => 'sh-query-posts-title','color' => '#0160ac'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.sh-query-posts .container-query-posts a',
                'textDecoration' => 'underline',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-title',
                'fontSize' => '1.7rem',
                'fontWeight' => '700',
                'fontFamily' => 'Helvetica',
                'lineHeight' => '2.1rem',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-title a',
                'textDecoration' => 'none',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-author',
                'fontSize' => '.8rem',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-author .author-name',
                'fontWeight' => '700',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-author .post-categories',
                'fontWeight' => '700',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-description',
                'fontSize' => '1rem',
                'fontWeight' => '400',
                'lineHeight' => '1.9rem',
                'fontFamily' => 'Helvetica',
            ],
            [
                'customSelector' => '.sh-query-posts .query-post .post-description a',
                'fontWeight' => '700',
            ],
            [
                'customSelector' => '.sh-query-posts .query-lists .query-post .post-title',
                'fontSize' => '1rem',
                'lineHeight' => '1.3rem',
            ],
            [
                'customSelector' => '.sh-query-posts .query-lists .query-post .post-description',
                'fontSize' => '.8rem',
                'lineHeight' => '1.3rem',
            ],

        ];
    }

    public function getPostsAjax($fields) {
        $post_type = (!empty($fields['post_type'])) ? $fields['post_type'] : 'post';
        $quantity = (!empty($fields['quantity'])) ? $fields['quantity'] : 1;

        $args = [
            'post_type' => $post_type,
            'post_status' => 'publish',
            'posts_per_page' => $quantity,
        ];

        if (isset($fields['author']) && !empty($fields['author'])) {
            $args['author'] = $fields['author'];
        }

        if (isset($fields['search']) && !empty($fields['search'])) {
            $args['s'] = $fields['search'];
        }

        if (isset($fields['taxonomy']) && !empty($fields['taxonomy']) && isset($fields['term']) && !empty($fields['term'])) {
            $args['tax_query'] = [
                [
                    'taxonomy' => $fields['taxonomy'],
                    'field' => 'id',
                    'terms' => $fields['term'],
                    'operator' => 'IN',
                ]
            ];
        } else {
            if (isset($fields['category_type']) && $fields['category_type'] == 'include' && isset($fields['category_include']) && !empty($fields['category_include'])) {
                $args['tax_query'] = [
                    [
                        'taxonomy' => $fields['taxonomy'],
                        'field' => 'id',
                        'terms' => explode(',', $fields['category_include']),
                        'operator' => 'IN',
                    ]
                ];
            } elseif (isset($fields['category_type']) && $fields['category_type'] == 'exclude' && isset($fields['category_exclude']) && !empty($fields['category_exclude'])) {
                $args['tax_query'] = [
                    [
                        'taxonomy' => $fields['taxonomy'],
                        'field' => 'id',
                        'terms' => explode(',', $fields['category_exclude']),
                        'operator' => 'NOT IN',
                    ]
                ];
            }
        }

        if (isset($fields['category']) && !empty($fields['category'])) {
            $args['post_parent'] = $fields['category'];
        }

        $posts = (new WP_Query($args))->posts;
        wp_reset_postdata();

        return $posts;
    }

    public function getNameCptGame() {
        if (!empty(get_option('shg_slug'))) {
            return get_option('shg_slug');
        }

        global $shg;
        if(isset($shg->slug)) {
            return $shg->slug['slug'];
        }
        
        return null;
    }

    public function getContentDescription($content) {
        $blocks = parse_blocks($content);
        $count_words = 0;
        $description = '';

        foreach ($blocks as $key => $block) {
            if ($block['blockName'] == 'core/paragraph' && !empty($block['innerHTML'])) {
                $words = wp_trim_words($block['innerHTML'], 120, false);
                
                if (!empty($words)) {
                    $count_words += count(explode(' ', $words));
                    $description .= $words. ' ';

                    if ($count_words < 120) {
                        continue;
                    } else {
                        break;
                    }
                }
            }
        }

        return $description;
    }
}

add_action('wp_ajax_nopriv_load_query_posts','getQueryPosts');
add_action('wp_ajax_load_query_posts','getQueryPosts');

function getQueryPosts() {
    $search = isset($_POST['search']) ? $_POST['search'] : null;
    $author = isset($_POST['author']) ? $_POST['author'] : null;
    $term = isset($_POST['term']) ? $_POST['term'] : null;
    $category = isset($_POST['category']) ? $_POST['category'] : null;
    
    $post_type = isset($_POST['post_type']) ? $_POST['post_type'] : 'post';
    $taxonomy = isset($_POST['taxonomy']) ? $_POST['taxonomy'] : null;
    $quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 5;
    $show = isset($_POST['show']) ? $_POST['show'] : 'latest';

    $category_type = isset($_POST['category_type']) ? $_POST['category_type'] : null;
    $category_include = isset($_POST['category_include']) ? $_POST['category_include'] : null;
    $category_exclude = isset($_POST['category_exclude']) ? $_POST['category_exclude'] : null;

    $sh_query_posts = new Rdg_Blocks_Sh_Query_Posts();

    $fields = [
        'post_type' => $post_type,
        'quantity' => $quantity,
        'taxonomy' => $taxonomy,
        'search' => $search,
        'author' => $author,
        'term' => $term,
        'category' => $category,
        'category_type' => $category_type,
        'category_include' => $category_include,
        'category_exclude' => $category_exclude,
    ];

    $new_posts = [];
    $posts = $sh_query_posts->getPostsAjax($fields);

    if (is_array($posts) && count($posts) > 0) {
        $i = 0;
        foreach ($posts as $key => $post) {
            $new_posts[$i]['id'] = $post->ID;
            $new_posts[$i]['url'] = get_permalink($post);
            $new_posts[$i]['title'] = $post->post_title;
            $new_posts[$i]['image'] = $sh_query_posts->getImage($post->ID);

            $d = DateTime::createFromFormat('Y-m-d H:i:s', $post->post_date);
            $month = $d->format('F');
            $more_date = $d->format('j, Y');
            $new_posts[$i]['date'] = $month.' '.$more_date;

            $author_name = get_the_author_meta('display_name', $post->post_author);
            $author_url = get_author_posts_url($post->post_author);
            $new_posts[$i]['author_url'] = $author_url;
            $new_posts[$i]['author_name'] = ucfirst(strtolower($author_name));

            $new_posts[$i]['author_term_name'] = '';
            $new_posts[$i]['author_term_slug'] = '';
            $new_posts[$i]['author_term_taxonomy'] = '';

            $term = $sh_query_posts->getTaxonomy($post);
            if ($term instanceof WP_Term) {
                $new_posts[$i]['author_term_name'] = $term->name;
                $new_posts[$i]['author_term_slug'] = $term->slug;
                $new_posts[$i]['author_term_taxonomy'] = $term->taxonomy;
            }

            $description = $sh_query_posts->getContentDescription($post->post_content);
            $new_posts[$i]['post_excerpt'] = trim(wp_trim_words($description, 120, false));
            
            $i++;
        }
    }
    
    echo json_encode($new_posts);
    wp_die();
}

$rdg_sh_query_posts_class = new Rdg_Blocks_Sh_Query_Posts();
$rdg_sh_query_posts_class->init();

return $rdg_sh_query_posts_class;
