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

class FTM_Blocks_List_Posts
{
    private $block_name             = 'ftm-list-posts';
    private $block_folder_name      = 'ftm-list-posts';
    private $block_css_manifest_key = 'ftm_list_posts';
    private $block_title            = 'FTM List Posts';
    private $block_description      = '';
    private $block_icon             = 'editor-table';
    private $block_keywords         = ['ftm', 'custom', 'list', 'posts'];
    private $block_mode             = 'preview';
    private $block_category         = "ftm-blocks";
    protected $block_id             = '';

    /* The property below stores all the necessary customizations for this block and this is what
    *  will be consider to generate the CSS based on the block id
    */
    private $css_generate_fields = [];

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

        //The previous code won't run on the admin so this way we can render the block correctly on the admin

        add_action('admin_init', function () {
            $this->register_block();
            $this->register_fields();
        });
    }

    public function get_block_name()
    {
        return $this->block_name;
    }

    public function load_assets()
    {
        $ftm_blocks_helper = new Ftm_Blocks_Helpers();
        wp_enqueue_style('ftm_latest-posts', $ftm_blocks_helper->webpack($this->block_css_manifest_key . '.css'));
    }

    private function get_post_type_taxonomies()
    {

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

        unset($post_types['attachment']);
        $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) && count($taxonomies))
                $data['taxonomies'][$post_type->name] = $taxonomies[0];
        }
        return $data;
    }

    private function register_block()
    {
        if (function_exists('acf_register_block_type')) {
            $ftm_blocks_helper = new Ftm_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' => FTMBLOCKS_PLUGIN_DIR . "/blocks/" . $this->block_folder_name . "/render.php",
                'enqueue_assets' => [$this, 'load_assets'],
                'supports' => [
                    'jsx' => true,
                    'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
                'example'  => [
                    'attributes' => [
                        'mode' => 'preview',
                        'data' => [
                            'preview_image_help' => FTMBLOCKS_PLUGIN_URL . "/blocks/" . $this->block_folder_name . "/preview.jpg",
                        ]
                    ]
                ],
                'class' => $this,
                'ftm_id' => 'block-' . uniqid()
            ]);
        }
    }

    public function register_fields()
    {

        $post_types = $this->get_post_type_taxonomies();

        $fields = [
            array(
                'key' => 'field_6530a2e619123',
                'label' => 'Layout',
                'name' => 'layout',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'vertical' => 'Vertical',
                    'horizontal' => 'Horizontal',
                ),
                'default_value' => 'post',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
            array(
                'key' => 'field_65309fbc9f1bf',
                'label' => 'Title',
                'name' => 'title',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 'Related posts',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            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',
                ),
                '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' => 'Category Criteria',
                'name' => 'category_criteria',
                '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' => '',
            ),
        ];

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

        if (function_exists('acf_add_local_field_group')) :
            acf_add_local_field_group(array(
                'key' => 'group_650a284a94a43',
                'title' => 'FTM Posts List',
                'fields' => $fields,
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/ftm-list-posts',
                        ),
                    ),
                ),
                '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', 1400, 390, true);
    }

    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;
    }
}

$ftm_blocks_latest_posts_class = new FTM_Blocks_List_Posts();
$ftm_blocks_latest_posts_class->init();

return $ftm_blocks_latest_posts_class;
