<?php

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

class Rdg_Blocks_Posts_List extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_POSTS_LIST;
    private $block_folder_name = BLOCK_RDG_POSTS_LIST;
    private $block_title = 'RDG Posts List';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'post', 'list'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = false;
    protected $is_config = false;

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

    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('rdg_posts_list.css'),
                'supports' => [
                    'jsx' => true,
                    'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

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

        $fields = [
            array(
                'key' => 'field_634t34ft4343t3',
                'label' => 'Display',
                'name' => 'display',
                'aria-label' => '',
                'type' => 'radio',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'acfe_save_meta' => 0,
                'choices' => array(
                    'default' => 'Default',
                    'flex' => 'Flex',
                ),
                'default_value' => 'default',
                'return_format' => 'value',
                'allow_null' => 0,
                'other_choice' => 0,
                'layout' => 'horizontal',
                'save_other_choice' => 0,
            ),
            array(
                'key' => 'field_650a284ab9567',
                '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'],
                'default_value' => 'post',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
            array(
                'key' => 'field_650a284abd21a',
                'label' => 'Show',
                'name' => 'show',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                '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' => '',
                'allow_custom' => 0,
                'search_placeholder' => '',
                'prepend' => '',
                'append' => '',
                'min' => '',
                'max' => '',
            ),
            array(
                'key' => 'field_650a284ac0e85',
                'label' => 'Select Category Type',
                'name' => 'select_category_type',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'field_650a284abd21a',
                            'operator' => '==',
                            'value' => 'latest',
                        ),
                    ),
                ),
                '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' => '',
                'allow_custom' => 0,
                'search_placeholder' => '',
                'prepend' => '',
                'append' => '',
                'min' => '',
                'max' => '',
            ),
        ];

        $fields = $this->generate_taxonomies_fields($post_types, $fields);
        $fields = $this->generate_elements_fields($post_types, $fields);

        $last_fields = [
            array(
                'key' => 'field_650a284ad3380',
                'label' => 'Quantity',
                'name' => 'quantity',
                'aria-label' => '',
                'type' => 'number',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'field_650a284abd21a',
                            'operator' => '==',
                            'value' => 'latest',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 1,
                'min' => 1,
                'max' => 12,
                'placeholder' => '',
                'step' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_1111bd2692a82',
                'label' => 'Detail',
                'name' => 'detail',
                'aria-label' => '',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_650a284ae21e1',
                'label' => 'List External Post',
                'name' => 'elements_external',
                'aria-label' => '',
                'type' => 'repeater',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'field_650a284abd21a',
                            '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' => 'field_650a284b2e3d2',
                        'label' => 'Image',
                        'name' => 'image',
                        'aria-label' => '',
                        'type' => 'image',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_650a284abd21a',
                                    'operator' => '!=empty',
                                ),
                            ),
                        ),
                        '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' => 'field_650a284ae21e1',
                    ),
                    array(
                        'key' => 'field_650a284b31f04',
                        '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' => 'field_650a284ae21e1',
                    ),
                    array(
                        'key' => 'field_650a284b3597b',
                        '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' => 'field_650a284ae21e1',
                    ),
                    array(
                        'key' => 'field_650a284b39287',
                        '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' => 'field_650a284ae21e1',
                    ),
                    array(
                        'key' => 'field_650a284b3cd8a',
                        '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' => 'field_650a284ae21e1',
                    ),
                ),
            ),
        ];

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

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

        endif;
    }

    public function register_image_size() {
        add_image_size('posts-list', 800, 500, true);
    }

    public function get_elements_type($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 get_image($image_id) {
        $post_thumbnail_id = get_post_thumbnail_id($image_id);

        if (empty($post_thumbnail_id)) {
            return '';
        }

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

        return $attachment[0];
    }

    public function get_description($element) {
        if (isset($element->post_excerpt) && !empty($element->post_excerpt)) {
            return $element->post_excerpt;
        }

        if (is_array($element) && isset($element['content']) && !empty($element['content'])) {
            return wp_strip_all_tags($element['content']);
        }

        if (isset($element->post_content) && !empty($element->post_content)) {
            return wp_strip_all_tags($element->post_content);
        }

        return '';
    }

    private function get_post_type_taxonomies() {
        $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 generate_taxonomies_fields($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' => 'field_650a284ac491d_'.$slug,
                    'label' => 'Category Include',
                    'name' => 'category_include',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_650a284ac0e85',
                                'operator' => '==',
                                'value' => 'include',
                            ),
                            array(
                                'field' => 'field_650a284ab9567',
                                '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' => 'field_650a284acbe63_'.$slug,
                    'label' => 'Category Exclude',
                    'name' => 'category_exclude',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_650a284ac0e85',
                                'operator' => '==',
                                'value' => 'exclude',
                            ),
                            array(
                                'field' => 'field_650a284ab9567',
                                '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 generate_elements_fields($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' => 'field_650a284ad6df5_'.$slug,
                    'label' => 'Elements',
                    'name' => 'elements',
                    'aria-label' => '',
                    'type' => 'relationship',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_650a284abd21a',
                                'operator' => '==',
                                'value' => 'specific',
                            ),
                            array(
                                'field' => 'field_650a284ab9567',
                                '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;
    }
}

$rdg_posts_list_class = new Rdg_Blocks_Posts_List();
$rdg_posts_list_class->init();

return $rdg_posts_list_class;
