<?php

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

define('BLOCK_RDG_LATEST_TYPE_LATEST', 'latest');
define('BLOCK_RDG_LATEST_TYPE_SPECIFIC', 'specific');
define('BLOCK_RDG_LATEST_TYPE_EXTERNAL', 'external');

class Rdg_Blocks_Latest_Post extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_LATEST_POST;
    private $block_folder_name = 'rdg-latest-post';
    private $block_title = 'RDG Latest Post';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'latest', 'post'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = false;
    protected $is_config = true;
    protected $config_page_title = 'RDG Latest Post';
    protected $config_menu_title = 'Latest Post';
    protected $config_menu_order = 4;

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

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

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

        if (function_exists('acf_add_local_field_group')):
            $fields = [
                array(
                    'key' => 'field_63b4e20db55d9',
                    'label' => 'Separator',
                    'name' => 'separator',
                    'aria-label' => '',
                    'type' => 'group',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => 0,
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'layout' => 'block',
                    'sub_fields' => array(
                        array(
                            'key' => 'field_63b4e236b55da',
                            'label' => 'Show Separator',
                            'name' => 'show',
                            'aria-label' => '',
                            'type' => 'radio',
                            'instructions' => '',
                            'required' => 1,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'choices' => array(
                                'show' => 'Show',
                                'hide' => 'Hide',
                            ),
                            'default_value' => 'show',
                            'return_format' => 'value',
                            'allow_null' => 0,
                            'other_choice' => 0,
                            'layout' => 'horizontal',
                            'save_other_choice' => 0,
                        ),
                        array(
                            'key' => 'field_63b4e295b55db',
                            'label' => 'Color Separator',
                            'name' => 'color',
                            'aria-label' => '',
                            'type' => 'color_picker',
                            'instructions' => '',
                            'required' => 1,
                            'conditional_logic' => array(
                                array(
                                    array(
                                        'field' => 'field_63b4e236b55da',
                                        'operator' => '==',
                                        'value' => 'show',
                                    ),
                                ),
                            ),
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'default_value' => '#CCC',
                            'enable_opacity' => 0,
                            'return_format' => 'string',
                        ),
                        array(
                            'key' => 'field_63b4e2e7b55dc',
                            'label' => 'Width Separator',
                            'name' => 'width',
                            'aria-label' => '',
                            'type' => 'number',
                            'instructions' => '',
                            'required' => 1,
                            'conditional_logic' => array(
                                array(
                                    array(
                                        'field' => 'field_63b4e236b55da',
                                        'operator' => '==',
                                        'value' => 'show',
                                    ),
                                ),
                            ),
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'default_value' => 1,
                            'min' => 1,
                            'max' => 20,
                            'placeholder' => '',
                            'step' => '',
                            'prepend' => '',
                            'append' => '',
                        ),
                    ),
                ),
                array(
                    'key' => 'field_63b71e1b177d3',
                    'label' => 'Presentation',
                    'name' => 'presentation',
                    'aria-label' => '',
                    'type' => 'radio',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => 0,
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'choices' => array(
                        'small' => 'Small',
                        'full' => 'Full',
                    ),
                    'default_value' => 'small',
                    'return_format' => 'value',
                    'allow_null' => 0,
                    'other_choice' => 0,
                    'layout' => 'horizontal',
                    'save_other_choice' => 0,
                ),
                array(
                    'key' => 'field_64f3962573e03',
                    '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_63b4dc15a0709',
                    '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' => '',
                ),
                array(
                    'key' => 'field_63b4dc15a414a',
                    'label' => 'Select Category Type',
                    'name' => 'select_category_type',
                    'aria-label' => '',
                    'type' => 'select',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a0709',
                                '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' => '',
                )
            ];

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

            $last_fields = [
                array(
                    'key' => 'field_63b4dc15af20e',
                    'label' => 'Quantity',
                    'name' => 'quantity',
                    'aria-label' => '',
                    'type' => 'number',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a0709',
                                'operator' => '==',
                                'value' => 'latest',
                            ),
                        ),
                    ),
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'default_value' => 1,
                    'min' => 1,
                    'max' => 12,
                    'placeholder' => '',
                    'step' => '',
                    'prepend' => '',
                    'append' => '',
                ),
                array(
                    'key' => 'field_63b4dc15b6669',
                    'label' => 'List External Post',
                    'name' => 'elements_external',
                    'aria-label' => '',
                    'type' => 'repeater',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a0709',
                                '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,
                    'sub_fields' => array(
                        array(
                            'key' => 'field_63b4dc15dc45d',
                            'label' => 'Image',
                            'name' => 'image',
                            'aria-label' => '',
                            'type' => 'image',
                            'instructions' => '',
                            'required' => 1,
                            'conditional_logic' => array(
                                array(
                                    array(
                                        'field' => 'field_63b4dc15a0709',
                                        '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',
                            'parent_repeater' => 'field_63b4dc15b6669',
                        ),
                        array(
                            'key' => 'field_63b4dc15dfffd',
                            '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_63b4dc15b6669',
                        ),
                        array(
                            'key' => 'field_63b4dc15e3c55',
                            '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' => '',
                            'parent_repeater' => 'field_63b4dc15b6669',
                        ),
                        array(
                            'key' => 'field_63b4ead0161c3',
                            '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_63b4dc15b6669',
                        ),
                        array(
                            'key' => 'field_63b4dc15e776a',
                            '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_63b4dc15b6669',
                        ),
                    ),
                ),
            ];

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

            acf_add_local_field_group(array(
                'key' => 'group_rdg_latest_post_block_dd53f4123',
                'title' => 'Block_rdg_latest_post',
                'fields' => $fields,
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-latest-post',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'api_configuration_latest_post_block_asdasdsadsaad',
                'title' => 'RDG Latest Post',
                'fields' => array(
                    array(
                        'key' => 'field_64f665cd6bfba',
                        'label' => 'Post Types',
                        'name' => 'latest_post_post_types',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'pagination' => 0,
                        'min' => 0,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Row',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'field_64f665fe6bfbb',
                                'label' => 'Post Type Slug',
                                'name' => 'latest_post_post_type_slug',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '35',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'required_message' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64f665cd6bfba',
                            ),
                            array(
                                'key' => 'field_64f666316bfbc',
                                'label' => 'Post Type Label',
                                'name' => 'latest_post_post_type_label',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '35',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64f665cd6bfba',
                            ),
                            array(
                                'key' => 'field_64f66f6902a8d',
                                'label' => 'Taxonomy',
                                'name' => 'latest_post_taxonomy',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '30',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64f665cd6bfba',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-latest-post',
                        ),
                    ),
                ),
                '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('latest-post', 1400, 390, 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_LATEST_TYPE_SPECIFIC == $show) {
            return $fields['elements'];
        }

        if (BLOCK_RDG_LATEST_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;
        $options = unserialize(get_option('latest_post_options'));

        if (is_array($options) && count($options) > 0) {
            foreach ($options as $option) {
                if (isset($option['slug']) && $post_type == $option['slug'] && !empty($option['taxonomy'])) {
                    $taxonomy = $option['taxonomy'];
                    break;
                }
            }
        }

        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, 'latest-post');
    
        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() {
        $options = unserialize(get_option('latest_post_options'));

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

        if (!is_array($options) || (is_array($options) && count($options) == 0)) {
            return $data;
        }

        $post_type = [];
        $taxonomies = [];
        foreach ($options as $option) {
            $post_type[$option['slug']] = $option['label'];
            $taxonomies[$option['slug']] = $option['taxonomy'];
        }

        return [
            'post_types' => $post_type,
            'taxonomies' => $taxonomies,
        ];
    }

    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_63b4dc15a7c19_'.$slug,
                    'label' => 'Category Include',
                    'name' => 'category_include',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a414a',
                                'operator' => '==',
                                'value' => 'include',
                            ),
                            array(
                                'field' => 'field_64f3962573e03',
                                '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_63b4dc15ab656_'.$slug,
                    'label' => 'Category Exclude',
                    'name' => 'category_exclude',
                    'aria-label' => '',
                    'type' => 'taxonomy',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a414a',
                                'operator' => '==',
                                'value' => 'exclude',
                            ),
                            array(
                                'field' => 'field_64f3962573e03',
                                '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_63b4dc15b2b80_'.$slug,
                    'label' => 'Elements',
                    'name' => 'elements',
                    'aria-label' => '',
                    'type' => 'relationship',
                    'instructions' => '',
                    'required' => 1,
                    'conditional_logic' => array(
                        array(
                            array(
                                'field' => 'field_63b4dc15a0709',
                                'operator' => '==',
                                'value' => 'specific',
                            ),
                            array(
                                'field' => 'field_64f3962573e03',
                                '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' => 12,
                    'elements' => array(
                        0 => 'featured_image',
                    ),
                ];
            }
        }

        return $fields;
    }

    public function save_post_latest_post_options() {
        $option = (isset($_GET['page'])) ? $_GET['page'] : null;

        if (!empty($option) && $option == 'acf-options-latest-post' && isset($_POST['acf'])) {
            $options = [];
            $post_types = current($_POST['acf']);

            if (is_array($post_types) && count($post_types) > 0) {
                foreach ($post_types as $key => $post_type) {
                    $slug = current($post_type);
                    $label = next($post_type);
                    $taxonomy = next($post_type);

                    $pt = get_post_type_object($slug);

                    if (!empty($pt)) {
                        $taxonomy_check = get_taxonomy($taxonomy);
                        if (empty($taxonomy_check)) $taxonomy = '';

                        $options[] = [
                            'slug' => $slug,
                            'label' => $label,
                            'taxonomy' => $taxonomy,
                        ];
                    }
                }

                update_option('latest_post_options', serialize($options));
            }
        }
    }
}

$rdg_latest_post_class = new Rdg_Blocks_Latest_Post();
$rdg_latest_post_class->init();

return $rdg_latest_post_class;
