<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;
/**
 * HELPER COMMENT START
 * 
 * This class contains all of the plugin related settings.
 * Everything that is relevant data and used multiple times throughout 
 * the plugin.
 * 
 * To define the actual values, we recommend adding them as shown above
 * within the __construct() function as a class-wide variable. 
 * This variable is then used by the callable functions down below. 
 * These callable functions can be called everywhere within the plugin 
 * as followed using the get_plugin_name() as an example: 
 * 
 * RDGBLOCKS->settings->get_plugin_name();
 * 
 * HELPER COMMENT END
 */

/**
 * Class Rdg_Blocks_Settings
 *
 * This class contains all of the plugin settings.
 * Here you can configure the whole plugin data.
 *
 * @package		RDGBLOCKS
 * @subpackage	Classes/Rdg_Blocks_Settings
 * @author		RDGCorp
 * @since		1.0.0
 */

class Rdg_Blocks_Settings
{
    /**
     * The plugin name
     *
     * @var		string
     * @since   1.0.0
     */

    private $plugin_name;

    /**
     * The blocks list
     *
     * @var		array
     * @since   1.0.0
     */

    private $block_list;

    /**
     * Our Rdg_Blocks_Settings constructor 
     * to run the plugin logic.
     *
     * @since 1.0.0
     */

    function __construct() {
        $this->plugin_name = RDGBLOCKS_NAME;
        $this->load_hooks();
        $this->block_list = $this->load_blocks();
    }

    /**
     * ######################
     * ###
     * #### CALLABLE FUNCTIONS
     * ###
     * ######################
     */

    /**
     * Return the plugin name
     *
     * @access	public
     * @since	1.0.0
     * @return	string The plugin name
     */

    public function get_plugin_name() {
        return apply_filters('RDGBLOCKS/settings/get_plugin_name', $this->plugin_name);
    }

    /**
     * Load plugin blocks
     *
     * @access	public
     * @since	1.0.0
     * @return	array Plugin blocks
     */

    private function load_hooks() {               
        add_filter('block_categories_all', [$this, 'custom_blocks'], 10, 2);
        add_filter('render_block', [$this, 'replace_block_class'], 10, 2);
        add_action('acf/save_post', [$this, 'save_post_rdg_images_maintenance']);
        add_action('acf/save_post', [$this, 'save_post_rdg_cache_maintenance']);
        add_action('acf/save_post', [$this, 'save_post_rdg_shortpixel']);
        add_action('acf/save_post', [$this, 'save_post_rdg_sports_categories']);
        add_action('acf/save_post', [$this, 'save_rdg_settings']);
        add_action('acfe/fields/button/name=category_maintenance_btn', array($this, 'category_maintenance_btn_ajax'), 10, 2);
        add_action( 'acf/init', array($this, 'generate_field_images_maintenance'));
        add_action( 'acf/init', array($this, 'generate_field_debug_blocks_request'));
        add_action( 'acf/init', array($this, 'generate_field_cache_maintenance'));
        add_action( 'acf/init', array($this, 'generate_field_resources'));
        add_action( 'acf/init', array($this, 'generate_field_categories_maintenance'));
        add_action( 'acf/init', array($this, 'generate_field_sports_categories'));
        add_filter('acf/load_value/name=delete_images_cache', [$this, 'load_field_delete_images_cache'], 10, 3);
        add_filter('acf/load_value/name=delete_cache_files', [$this, 'load_field_delete_images_cache'], 10, 3);
        add_filter('acf/load_value/name=delete_specific_image', [$this, 'load_field_delete_specific_image'], 10, 3);
        add_filter('acf/load_value/name=delete_specific_cache', [$this, 'load_field_delete_specific_image'], 10, 3);
        add_filter('acf/load_value/name=rdg_blocks_load_colors_styles', [$this, 'load_field_rdg_blocks_load_colors_styles'], 10, 3);
        add_filter('acf/prepare_field/name=rdg_images_maintenance', [$this, 'load_field_images_maintenance'], 10, 3);
        add_filter('acf/prepare_field/name=rdg_number_of_cache_files', [$this, 'load_field_cache_maintenance'], 10, 3);

        add_filter('cron_schedules', array( $this,'rdg_blocks_add_cron_interval'));
		add_action('rdg_blocks_cron_event', array($this, 'rdg_blocks_cron_function'));
		add_action('rdg_blocks_cron_event_shortpixel', array($this, 'rdg_blocks_cron_function_shortpixel'));
		add_action('rdg_blocks_cache_cron_event', array($this, 'rdg_blocks_cache_cron_function'));

        register_activation_hook(RDGBLOCKS_PLUGIN_FILE, [$this, 'activation_hook_callback']);
        register_deactivation_hook(RDGBLOCKS_PLUGIN_FILE, [$this, 'deactivation_hook_callback']);

        add_action('admin_notices', function() {
            if (!empty(get_user_option('show_message'))) {
                echo '<div class="acf-admin-notice notice '.get_user_option('message_type').' is-dismissible"><p>'.get_user_option('show_message').'</p></div>';
                delete_user_option(get_current_user_id(), 'show_message');
                delete_user_option(get_current_user_id(), 'message_type');
            }
        });
    }

    private function load_blocks() {
        $block_classes = [];
        foreach (glob(RDGBLOCKS_PLUGIN_DIR . "/blocks/*/main.php") as $block_file) {
            $block = include $block_file;
            $block_classes[$block->getBlockName()] = $block;
        }

        return $block_classes;
    }

    public function rdg_blocks_add_cron_interval($schedules) {
        if (!array_key_exists("two_minute", $schedules)) {
            $schedules['two_minute'] = array(
                'interval' => 60 * 2,
                'display'  => __('Every 2 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }

        if (!array_key_exists("three_minute", $schedules)) {
            $schedules['three_minute'] = array(
            'interval' => 60 * 3,
            'display'  => __('Every 3 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }

        if (!array_key_exists("five_minute", $schedules)) {
            $schedules['five_minute'] = array(
                'interval' => 60 * 5,
                'display'  => __('Every 5 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }

        if (!array_key_exists("ten_minute", $schedules)) {
            $schedules['ten_minute'] = array(
                'interval' => 60 * 10,
                'display'  => __('Every 10 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }

        if(!array_key_exists("hourly", $schedules)) {
            $schedules['hourly'] = array(
                'interval' => 60 * 60,
                'display'  => __('Every Hour', RDGBLOCKS_NAME_SLUG),
            );
        }

        if(!array_key_exists("daily", $schedules)) {
            $schedules['daily'] = array(
                'interval' => 60 * 60 * 24,
                'display'  => __('Every Day', RDGBLOCKS_NAME_SLUG),
            );
        }

        if(!array_key_exists("half_hour", $schedules)) {
            $schedules['half_hour'] = array(
                'interval' => 60 * 30,
                'display'  => __('Every 30 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }

        if(!array_key_exists("quarter_hour", $schedules)) {
            $schedules['quarter_hour'] = array(
                'interval' => 60 * 15,
                'display'  => __('Every 15 Minutes', RDGBLOCKS_NAME_SLUG),
            );
        }
        
        return $schedules;
    }

    public function rdg_blocks_cron_function() {
        // Call the WP-CLI command
        $command = 'wp rdg_blocks clear_cache';
        $output = shell_exec($command);
    }

    public function rdg_blocks_cron_function_shortpixel() {
        // Call the WP-CLI command
        $command = 'wp rdg_blocks images_optimize';
        $output = shell_exec($command);
    }

    public function rdg_blocks_cache_cron_function() {
        // Call the WP-CLI command
        $command = 'wp rdg_blocks regenerate_cache';
        #TODO: Validate if this is needed
        ini_set('max_execution_time', 300);
        $output = shell_exec($command);
    }

    public function activation_hook_callback() {
        //Create cronjob
        if (!wp_next_scheduled('rdg_blocks_cron_event')) {
            wp_schedule_event(time(), 'hourly', 'rdg_blocks_cron_event');
            update_option('rdg_blocks_cron_time', 'hourly' );
        }

        //Create cronjob shortpixel
        if (!wp_next_scheduled('rdg_blocks_cron_event_shortpixel')) {
            wp_schedule_event(time(), 'hourly', 'rdg_blocks_cron_event_shortpixel');
            update_option('rdg_blocks_cron_time_shortpixel', 'hourly');
        }

        //Create cronjob cache
        if (!wp_next_scheduled('rdg_blocks_cache_cron_event')) {
            wp_schedule_event(time(), 'five_minute', 'rdg_blocks_cache_cron_event');
            update_option('rdg_blocks_cache_cron_time', 'five_minute');
        }
    }

    public function deactivation_hook_callback() {
        wp_clear_scheduled_hook('rdg_blocks_cron_event');
        wp_clear_scheduled_hook('rdg_blocks_cron_event_shortpixel');
        wp_clear_scheduled_hook('rdg_blocks_cache_cron_event');
    }

    public function getBlocks($api = false) {
        if (!$api) return $this->block_list;

        $array_blocks = [];
        foreach ($this->block_list as $block_name => $block_reference) {
            if ($block_reference->isCaching()) {
                $array_blocks[$block_name] = $block_reference->getBlockTitle();
            }
        }

        return (count($array_blocks) > 0) ? $array_blocks : [];
    }

    public function getBlock($block = null) {
        if ($block !== null && isset($this->block_list[$block])) {
            return $this->block_list[$block];
        }

        return null;
    }

    public function custom_blocks($categories) {
        return array_merge(
            $categories,
            array(
                array(
                    'slug' => RDGBLOCKS_NAME_SLUG,
                    'title' => __('RDG Blocks', RDGBLOCKS_NAME_SLUG),
                ),
            )
        );
    }

    public function replace_block_class($block_content, $block) {
        $full_grids = ['full-screen'];
    
        if (isset($block['attrs']['className']) && !empty($block['attrs']['className'])) {
            $classes = explode(' ', $block['attrs']['className']);
    
            foreach ($classes as $class) {
                if (in_array($class, $full_grids)) {
                    $Id = '';

                    if (isset($block['attrs']['uniqueId'])) {
                        $Id = ' block-'.$block['attrs']['uniqueId'];
                    } else {
                        $classes_block = explode(' ', $block['attrs']['className']);
                        foreach ($classes_block as $block) {
                            if (strpos($block, 'block-') !== false) {
                                $Id = ' '.$block;
                            }
                        }
                    }
    
                    return '<div class="full-screen-container'.$Id.'"><div class="container-generate grid-container">'.$block_content.'</div></div>';
                }
            }
        }
    
        return $block_content;
    }

    public function load_field_images_maintenance($field) {
        $images = glob(IMAGES_MAINTENANCE_FOLDER . '*', GLOB_MARK);
        $count_files = (is_array($images)) ? count($images) : 0;

        $field['message'] = $count_files.' Files';

        return $field;
    }

    public function load_field_cache_maintenance($field) {
        $cache_files = glob(CACHE_MAINTENANCE_FOLDER . '*.json', GLOB_MARK);
        $count_files = (is_array($cache_files)) ? count($cache_files) : 0;

        $field['message'] = $count_files.' Files';

        return $field;
    }

    public function load_field_delete_images_cache($value) {
        return 'keep';
    }

    public function load_field_delete_specific_image($value) {
        return '';
    }

    public function load_field_rdg_blocks_load_colors_styles($value) {
        return 'none';
    }

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

        if (!empty($option) && $option == 'acf-options-images-maintenance' && isset($_POST['acf']) && is_array($_POST['acf']) && count($_POST['acf']) > 0) {
            $fields = [];
    
            foreach ($_POST['acf'] as $key => $value) {
                $fields[] = $value;
            }

            try {
                $images = glob(IMAGES_MAINTENANCE_FOLDER . '*', GLOB_MARK);

                if ($fields[0] == 'all') {
                    if (file_exists(IMAGES_MAINTENANCE_FOLDER)) {
                        if (is_array($images) && count($images) > 0) {
                            foreach ($images as $image) {
                                unlink($image);
                            }

                            error_log('RDG Blocks: Deleted all images from the cache.');
                            update_user_option(get_current_user_id(), 'show_message', 'Deleted all images from the cache.');
                            update_user_option(get_current_user_id(), 'message_type', 'notice-success');
                        } else {
                            error_log('RDG Blocks: Image cache is empty.');
                            update_user_option(get_current_user_id(), 'show_message', 'Image cache is empty.');
                            update_user_option(get_current_user_id(), 'message_type', 'notice-warning');
                        }
                    }
                } elseif ($fields[0] == 'single' && isset($fields[1]) && !empty($fields[1])) {
                    if (file_exists(IMAGES_MAINTENANCE_FOLDER.$fields[1])) {
                        unlink(IMAGES_MAINTENANCE_FOLDER.$fields[1]);

                        update_user_option(get_current_user_id(), 'show_message', 'Selected image was deleted.');
                        update_user_option(get_current_user_id(), 'message_type', 'notice-success');

                        error_log(print_r([
                            'message' => 'RDG Blocks: Selected image was deleted.',
                            'image' => IMAGES_MAINTENANCE_FOLDER.$fields[1],
                        ], true));
                    } else {
                        update_user_option(get_current_user_id(), 'show_message', 'The selected image does not exist.');
                        update_user_option(get_current_user_id(), 'message_type', 'notice-warning');

                        error_log(print_r([
                            'message' => 'RDG Blocks: The selected image does not exist.',
                            'image' => IMAGES_MAINTENANCE_FOLDER.$fields[1],
                        ], true));
                    }
                }
            } catch (\Exception $exception) {
                update_user_option(get_current_user_id(), 'show_message', 'An unexpected error occurred. Try again later.');
                update_user_option(get_current_user_id(), 'message_type', 'notice-error');

                error_log(print_r([
                    'message' => $exception->getMessage(),
                    'fields' => $fields,
                ], true));
            }
        }
    }

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

        if (!empty($option) && $option == 'acf-options-cache-maintenance' && isset($_POST['acf']) && is_array($_POST['acf']) && count($_POST['acf']) > 0) {
            $fields = [];

            foreach ($_POST['acf'] as $key => $value) {
                $fields[] = $value;
            }

            try {
                $original_cron = get_option('rdg_blocks_cron_time');

                if ((!empty($fields[0])) && ($original_cron != $fields[0])) {
                    wp_clear_scheduled_hook('rdg_blocks_cron_event');
                    wp_schedule_event(time(), $fields[0], 'rdg_blocks_cron_event');
                }

                update_option('rdg_blocks_cron_time', $fields[0]);

                $cache_files = glob(CACHE_MAINTENANCE_FOLDER . '*.json', GLOB_MARK);

                if ($fields[1] == 'all') {
                    if (file_exists(CACHE_MAINTENANCE_FOLDER)) {
                        if (is_array($cache_files) && count($cache_files) > 0) {
                            foreach ($cache_files as $cache_file) {
                                unlink($cache_file);
                            }

                            error_log('RDG Blocks: Deleted all cache files.');
                            update_user_option(get_current_user_id(), 'show_message', 'Deleted all cache files.');
                            update_user_option(get_current_user_id(), 'message_type', 'notice-success');
                        } else {
                            error_log('RDG Blocks: Cache files is empty.');
                            update_user_option(get_current_user_id(), 'show_message', 'Cache files is empty.');
                            update_user_option(get_current_user_id(), 'message_type', 'notice-warning');
                        }
                    }
                } elseif ($fields[1] == 'single' && isset($fields[2]) && !empty($fields[2])) {
                    if (file_exists(CACHE_MAINTENANCE_FOLDER.$fields[2])) {
                        unlink(CACHE_MAINTENANCE_FOLDER.$fields[2]);

                        update_user_option(get_current_user_id(), 'show_message', 'Selected cache file was deleted.');
                        update_user_option(get_current_user_id(), 'message_type', 'notice-success');

                        error_log(print_r([
                            'message' => 'RDG Blocks: Selected cache file was deleted.',
                            'image' => CACHE_MAINTENANCE_FOLDER.$fields[2],
                        ], true));
                    } else {
                        update_user_option(get_current_user_id(), 'show_message', 'The selected cache file does not exist.');
                        update_user_option(get_current_user_id(), 'message_type', 'notice-warning');

                        error_log(print_r([
                            'message' => 'RDG Blocks: The selected cache file does not exist.',
                            'image' => CACHE_MAINTENANCE_FOLDER.$fields[2],
                        ], true));
                    }
                }
            } catch (\Exception $exception) {
                update_user_option(get_current_user_id(), 'show_message', 'An unexpected error occurred. Try again later.');
                update_user_option(get_current_user_id(), 'message_type', 'notice-error');

                error_log(print_r([
                    'message' => $exception->getMessage(),
                    'fields' => $fields,
                ], true));
            }
        }
    }

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

        if (!empty($option) && $option == 'acf-options-resources' && isset($_POST['acf']) && is_array($_POST['acf']) && count($_POST['acf']) > 0) {
            try {
                foreach ($_POST['acf'] as $key => $value) {
                    $fields[] = $value;
                }
    
                foreach ($fields[1] as $key => $value) {
                    $fields_short_pixel[] = $value;
                }
    
                $short_pixel_active = (isset($fields_short_pixel[0])) ? $fields_short_pixel[0] : 'none';
                $short_pixel_cronjob = (isset($fields_short_pixel[2])) ? $fields_short_pixel[2] : 'hourly';

                if ($short_pixel_active == 'active') {
                    wp_clear_scheduled_hook('rdg_blocks_cron_event_shortpixel');
                    wp_schedule_event(time(), $short_pixel_cronjob, 'rdg_blocks_cron_event_shortpixel');
                    update_option('rdg_blocks_cron_time_shortpixel', $short_pixel_cronjob);
                } else {
                    wp_clear_scheduled_hook('rdg_blocks_cron_event_shortpixel');
                }
            } catch (\Exception $exception) {
                error_log(print_r([
                    'message' => $exception->getMessage(),
                ], true));
            }
        }
    }


    public function category_maintenance_btn_ajax($field, $post_id) {
        if ( have_rows('sports_categories', $post_id) ) {
            update_field('sports_categories', '', $post_id);
        }                
        $sports_url = get_field('category_maintenance_url_sports') ?? null;
        $categories_url = get_field('category_maintenance_url_categories') ?? null;
        $parts_url = get_field('category_maintenance_url_game_parts') ?? null;
        $api_token = get_field('category_maintenance_api_token') ?? null;

        if (empty($sports_url) ||
            empty($categories_url) ||
            empty($parts_url) ||
            empty($api_token)) {
                wp_send_json(['type' => 'warning', 'message'=> 'Missing parameters']);
        }

        try {
            global $rdgb;
            $url = $sports_url.'?api_token='.$api_token;
            $sports = $rdgb->helpers->rdgApiRequest($url);
    
            if ($sports === null) {
                wp_send_json(['type' => 'warning', 'message'=> 'No found sports']);
            }
    
            foreach ($sports as $sport) {
                $sport_id = $sport['id'];
                $row = [
                    'sport_id' => $sport_id,
                    'sport_title' => $sport['sport_name'],
                ];

                $url = $categories_url.'?api_token='.$api_token.'&sport='.$sport_id;
                $categories = $rdgb->helpers->rdgApiRequest($url);
    
                if ($categories !== null) {
                    foreach ($categories as $category) {
                        $category_row = [
                            'category_id' => $category['id'],
                            'category_title' => $category['description'],
                        ];
                        $row['categories'][] = $category_row;
                    }                
                }
        
                $url = $parts_url.'?api_token='.$api_token.'&sport='.$sport_id;
                $parts = $rdgb->helpers->rdgApiRequest($url);
    
                if ($parts !== null) {
                    foreach ($parts as $part) {
                        $part_row = [
                            'part_id' => $part['id'],
                            'part_title' => $part['period_description'],
                        ];
                        $row['parts'][] = $part_row;
                    }
                }
                add_row('sports_categories', $row, $post_id);
            }            
        } catch (\Exception $exception) {
            error_log(print_r([
                'message' => $exception->getMessage(),
                'parameters' => [$sports_url, $categories_url, $parts_url, $api_token],
            ], true));
        }

        wp_send_json(['type' => 'success', 'message'=> 'Completed...']);
    }

    public function generate_field_images_maintenance(){
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_sfrw4r53dr32rs2x3e',
                'title' => 'Images Maintenance',
                'fields' => array(
                    array(
                        'key' => 'field_647794d79ed7e',
                        'label' => 'Number of Images',
                        'name' => 'rdg_images_maintenance',
                        'aria-label' => '',
                        'type' => 'message',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '20',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => '',
                        'new_lines' => 'wpautop',
                        'esc_html' => 0,
                    ),
                    array(
                        'key' => 'field_6477600eebc5f',
                        'label' => 'Delete All Images cache',
                        'name' => 'delete_images_cache',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '40',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'keep' => 'Keep Images',
                            'single' => 'Delete Selected Image',
                            'all' => 'Delete All Images',
                        ),
                        'default_value' => 'keep',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_6477613febc60',
                        'label' => 'Delete specific image',
                        'name' => 'delete_specific_image',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_6477600eebc5f',
                                    'operator' => '==',
                                    'value' => 'single',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '40',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-images-maintenance',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            endif; 
    }

    public function generate_field_cache_maintenance(){
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_sfsffsdfdsfdsfdsfsf',
                'title' => 'Cache Maintenance',
                'fields' => array(
                    array(
                        'key' => 'field_647de4ef80e43',
                        'label' => 'Number of cache files',
                        'name' => 'rdg_number_of_cache_files',
                        'aria-label' => '',
                        'type' => 'message',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => '',
                        'new_lines' => 'wpautop',
                        'esc_html' => 0,
                    ),
                    array(
                        'key' => 'field_647e33cb8aa9c',
                        'label' => 'Cronjob run time',
                        'name' => 'rdg_cache_maintenance_cronjob_run_time',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'hourly' => 'Once Hourly',
                            'daily' => 'Once Daily',
                        ),
                        'default_value' => 'daily',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_647de4ef847ca',
                        'label' => 'Delete All cache files',
                        'name' => 'delete_cache_files',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'keep' => 'Keep cache',
                            'single' => 'Delete selected cache',
                            'all' => 'Delete all cache',
                        ),
                        'default_value' => 'keep',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_647de4ef883f1',
                        'label' => 'Delete specific cache',
                        'name' => 'delete_specific_cache',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_647de4ef847ca',
                                    'operator' => '==',
                                    'value' => 'single',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-cache-maintenance',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            endif;
    }

    public function save_post_rdg_sports_categories($post_id) {
        $option = (isset($_GET['page'])) ? $_GET['page'] : null;
        if (!empty($option) && $option == 'acf-options-sports-categories') {
            try {
                global $rdgb;
                $key_sports = 'rdg_blocks_sports_categories';
                $key_select = 'rdg_blocks_sports_categories_select_option';
                $key_parts_select = 'rdg_blocks_sports_parts_select_option';
    
                if ($rdgb->helpers->initRedis()) {
                    $rdgb->helpers->setRedisGroup(REDIS_GROUP_BLOCKS);

                    $rdgb->helpers->setRedis($key_sports, serialize([]), REDIS_TIMEOUT);
                    $rdgb->helpers->setRedis($key_select, serialize([]), REDIS_TIMEOUT);
                    $rdgb->helpers->setRedis($key_parts_select, serialize([]), REDIS_TIMEOUT);
                }
            } catch (\Exception $exception) {
                error_log(print_r([
                    'message' => $exception->getMessage(),
                    'keys' => [$key_sports, $key_select, $key_parts_select],
                ], true));
            }
        }
    }

    public function generate_field_resources() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_dxfserg5dsdsdwrwr',
                'title' => 'Resources',
                'fields' => array(
                    array(
                        'key' => 'field_6491a0a0d5f0c',
                        'label' => 'Jquery',
                        'name' => 'rdg_resource_jquery_group',
                        'aria-label' => '',
                        'type' => 'group',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'sub_fields' => array(
                            array(
                                'key' => 'field_6491a0c5d5f0d',
                                'label' => 'Jquery Load',
                                'name' => 'jquery_versions',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '20',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => $this->get_jquery_versions(),
                                'default_value' => 'none',
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_6491a11fd5f0e',
                        'label' => 'Short Pixel',
                        'name' => 'rdg_resource_short_pixel_group',
                        'aria-label' => '',
                        'type' => 'group',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'sub_fields' => array(
                            array(
                                'key' => 'field_6491a131d5f0f',
                                'label' => 'Short Pixel Active?',
                                'name' => 'short_pixel_active',
                                'aria-label' => '',
                                'type' => 'radio',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '20',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    'none' => 'None',
                                    'active' => 'Active',
                                ),
                                'default_value' => 'none',
                                'return_format' => 'value',
                                'allow_null' => 0,
                                'other_choice' => 0,
                                'layout' => 'horizontal',
                                'save_other_choice' => 0,
                            ),
                            array(
                                'key' => 'field_649338e879baa',
                                'label' => 'Max Chunks',
                                'name' => 'max_chunks',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_6491a131d5f0f',
                                            'operator' => '==',
                                            'value' => 'active',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '30',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    10 => '10 Images',
                                    20 => '20 Images',
                                    30 => '30 Images',
                                    40 => '40 Images',
                                    50 => '50 Images',
                                    100 => '100 Images',
                                ),
                                'default_value' => 10,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                            ),
                            array(
                                'key' => 'field_6491a1b0d5f10',
                                'label' => 'Cronjob run time',
                                'name' => 'short_pixel_cronjob_run_time',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_6491a131d5f0f',
                                            'operator' => '==',
                                            'value' => 'active',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    'quarter_hour' => 'Every 15 Minutes',
                                    'half_hour' => 'Every 30 Minutes',
                                    'hourly' => 'Once Hourly',
                                    'daily' => 'Once Daily',
                                ),
                                'default_value' => false,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-resources',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            endif;              
    }

    private function get_jquery_versions () {
        $versions = ['none' => 'None'];
        $jquery_versions_dir = RDGBLOCKS_PLUGIN_DIR.'core/includes/assets/js/jquery/';
        $jquery_versions = scandir($jquery_versions_dir);

        if (is_array($jquery_versions) && count($jquery_versions) > 2) {
            foreach ($jquery_versions as $version) {
                if ($version != '.' && $version != '..') {
                    $versions[$version] = $version;
                }
            }
        }

        return $versions;
    }

    public function generate_field_categories_maintenance() {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
  
        $fields = [
            array(
                'key' => 'field_64ee9b5e8ef9e',
                'label' => 'URL Sports',
                'name' => 'category_maintenance_url_sports',
                'aria-label' => '',
                'type' => 'text',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'acfe_save_meta' => 0,
                'default_value' => 'https://members.sportshub.com/api/leaderboardData/sports',
                'required_message' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_64ee9be68c6ff',
                'label' => 'URL Categories',
                'name' => 'category_maintenance_url_categories',
                'aria-label' => '',
                'type' => 'text',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'acfe_save_meta' => 0,
                'default_value' => 'https://members.sportshub.com/api/leaderboardData/categories',
                'required_message' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_64ee9c41ee738',
                'label' => 'URL Game Parts',
                'name' => 'category_maintenance_url_game_parts',
                'aria-label' => '',
                'type' => 'text',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'acfe_save_meta' => 0,
                'default_value' => 'https://members.sportshub.com/api/game-parts',
                'required_message' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_64f2762234a1b',
                'label' => 'Api token',
                'name' => 'category_maintenance_api_token',
                'aria-label' => '',
                'type' => 'text',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'acfe_save_meta' => 0,
                'default_value' => '',
                'required_message' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_64ee9d9ef4a0f',
                'label' => 'Extract data',
                'name' => 'category_maintenance_btn',
                'aria-label' => '',
                'type' => 'acfe_button',
                'instructions' => 'This process will take a few seconds.',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'button_value' => 'Process',
                'button_type' => 'button',
                'button_class' => 'button button-secondary',
                'button_id' => 'category_maintenance_btn_acf_proccess',
                'button_before' => '',
                'button_after' => '',
                'button_ajax' => 1,
            ),
        ];

        if (!$rdgb->helpers->isInstallAcfe()) {
            $fields = [
                array(
                    'key' => 'field_650b1328b4748',
                    'label' => 'Message',
                    'name' => 'message_categories_maintenance',
                    'aria-label' => '',
                    'type' => 'message',
                    'instructions' => '',
                    'required' => 0,
                    'conditional_logic' => 0,
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'message' => 'Advanced Custom Fields: Extended PRO needs to be installed/activated.',
                    'new_lines' => 'wpautop',
                    'esc_html' => 0,
                ),
            ];
        }

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group( array(
            'key' => 'group_64ee9b598a3e3',
            'title' => 'Categories Maintenance',
            'fields' => $fields,
            'location' => array(
                array(
                    array(
                        'param' => 'options_page',
                        'operator' => '==',
                        'value' => 'acf-options-categories-maintenance',
                    ),
                ),
            ),
            'menu_order' => 0,
            'position' => 'normal',
            'style' => 'default',
            'label_placement' => 'left',
            'instruction_placement' => 'label',
            'hide_on_screen' => '',
            'active' => true,
            'description' => '',
            'show_in_rest' => 0,
            'acfe_autosync' => '',
            'acfe_form' => 0,
            'acfe_display_title' => '',
            'acfe_meta' => '',
            'acfe_note' => '',
        ) );
    
        endif;     
    }

    public function generate_field_sports_categories() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_64b0165641eba',
                'title' => 'RDG Sports Categories',
                'fields' => array(
                    array(
                        'key' => 'field_64b01656e0de1',
                        'label' => 'Sports Categories',
                        'name' => 'sports_categories',
                        '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_64b0169de0de2',
                                'label' => 'Sport ID',
                                'name' => 'sport_id',
                                '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_64b01656e0de1',
                            ),
                            array(
                                'key' => 'field_64b01799e0de3',
                                'label' => 'Sport Title',
                                'name' => 'sport_title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '70',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64b01656e0de1',
                            ),
                            array(
                                'key' => 'field_64b017c4e0de4',
                                'label' => 'Categories',
                                'name' => 'categories',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'table',
                                'pagination' => 0,
                                'min' => 0,
                                'max' => 0,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_64b017d3e0de5',
                                        'label' => 'Category ID',
                                        'name' => 'category_id',
                                        '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_64b017c4e0de4',
                                    ),
                                    array(
                                        'key' => 'field_64b017e1e0de6',
                                        'label' => 'Category Title',
                                        'name' => 'category_title',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 0,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '80',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_64b017c4e0de4',
                                    ),
                                ),
                                'parent_repeater' => 'field_64b01656e0de1',
                            ),
                            array(
                                'key' => 'field_64b5de3d0c5c3',
                                'label' => 'Game Parts',
                                'name' => 'parts',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'table',
                                'min' => 0,
                                'max' => 0,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_64b5de3d0c5c4',
                                        'label' => 'Part ID',
                                        'name' => 'part_id',
                                        '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_64b5de3d0c5c3',
                                    ),
                                    array(
                                        'key' => 'field_64b5de3d0c5c5',
                                        'label' => 'Part Title',
                                        'name' => 'part_title',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 0,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '70',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_64b5de3d0c5c3',
                                    ),
                                ),
                                'parent_repeater' => 'field_64b01656e0de1',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-sports-categories',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));
            endif;              
    }

    public function generate_field_debug_blocks_request() {
        if( function_exists('acf_add_local_field_group') ):
            global $rdgb;
            $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

            acf_add_local_field_group(array(
                'key' => 'group_rdg_blocks_form_cron_cache',
                'title' => 'Cron Jobs Cache Settings',
                'fields' => array(
                    array(
                        'key' => 'key_rdg_blocks_cache_status',
                        'label' => 'Status',
                        'name' => 'rdg_blocks_cache_status',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '35',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'inactive' => 'Inactive',
                            'active' => 'Active',
                        ),
                        'default_value' => 'inactive',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'key_rdg_blocks_cache_cron_time',
                        'label' => 'Cronjob run time',
                        'name' => 'rdg_blocks_cache_cron_time',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_blocks_cache_status',
                                    'operator' => '==',
                                    'value' => 'active',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '35',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'two_minute' => 'Every 2 Minutes',
                            'three_minute' => 'Every 3 Minutes',
                            'five_minute' => 'Every 5 Minutes',
                            'ten_minute' => 'Every 10 Minutes',
                        ),
                        'default_value' => 'five_minute',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_blocks_cache_run_message',
                        'label' => 'Last Cache Pull Datetime',
                        'name' => 'rdg_blocks_cache_run_message',
                        'aria-label' => '',
                        'type' => 'message',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_blocks_cache_status',
                                    'operator' => '==',
                                    'value' => 'active',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'message' => get_option('rdg_blocks_cache_last_run', 'never'),
                        'new_lines' => 'wpautop',
                        'esc_html' => 0,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-settings',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            acf_add_local_field_group(array(
                'key' => 'group_sfrrev454c4tt4tvvtt',
                'title' => 'Debug Blocks',
                'fields' => array(
                    array(
                        'key' => 'rdg_blocks_debug_request',
                        'label' => 'Debug Request Active?',
                        'name' => 'rdg_blocks_debug_request',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '20',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'active' => 'Active',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'rdg_blocks_debug_cache',
                        'label' => 'Debug Cache Active?',
                        'name' => 'rdg_blocks_debug_cache',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '20',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'active' => 'Active',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'rdg_blocks_disable_block_cache',
                        'label' => 'Disable Block Cache?',
                        'name' => 'rdg_blocks_disable_block_cache',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '20',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'active' => 'Active',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'rdg_blocks_block_disable',
                        'label' => 'Block Disable',
                        'name' => 'rdg_blocks_block_disable',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_65005ad89c50d',
                                    'operator' => '==',
                                    'value' => 'active',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '40',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $this->getBlocks(true),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-settings',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

            acf_add_local_field_group(array(
                'key' => 'group_sfrrev42343242344',
                'title' => 'Block Colors and Styles',
                'fields' => array(
                    array(
                        'key' => 'rdg_blocks_load_colors_styles',
                        'label' => 'Load Colors / Styles',
                        'name' => 'rdg_blocks_load_colors_styles',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'colors' => 'Colors',
                            'styles' => 'Styles',
                            'both' => 'Both',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-settings',
                        ),
                    ),
                ),
                'menu_order' => 2,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));
        endif; 
    }

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

        if (!empty($option) && $option == 'acf-options-settings' && isset($_POST['acf']) && is_array($_POST['acf']) && count($_POST['acf']) > 0) {
            try {
                global $rdgb;
                $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
                $blocks = $rdgb->helpers->getBlocksStylesLoad();
                $load_colors_styles = (isset($_POST['acf']['rdg_blocks_load_colors_styles']) && !empty($_POST['acf']['rdg_blocks_load_colors_styles'])) ? $_POST['acf']['rdg_blocks_load_colors_styles'] : 'none';

                if ($load_colors_styles != 'none') {
                    if ($rdgb->helpers->isInstallGeneratePress()) {
                        $generatepress_options = get_option('generate_settings');

                        if (!$generatepress_options) {
                            $generatepress_options = [
                                'global_colors' => $rdgb->helpers->getDefaultColors(),
                                'typography' => [],
                            ];
                        }

                        if (!isset($generatepress_options['global_colors'])) {
                            $generatepress_options['global_colors'] = [];
                        }

                        $saved_colors = [];
                        if (is_array($generatepress_options['global_colors']) && count($generatepress_options['global_colors']) > 0) {
                            foreach ($generatepress_options['global_colors'] as $key => $color) {
                                $saved_colors[] = $color['slug'];
                            }
                        }
                
                        if (!isset($generatepress_options['typography'])) {
                            $generatepress_options['typography'] = [];
                        }

                        $saved_styles = [];
                        if (is_array($generatepress_options['typography']) && count($generatepress_options['typography']) > 0) {
                            foreach ($generatepress_options['typography'] as $key => $style) {
                                if ($style['selector'] == 'custom') {
                                    $saved_styles[] = $style['customSelector'];
                                }
                            }
                        }

                        $base_colors = $rdgb->helpers->getBaseColors();
                        $generatepress_options = $rdgb->helpers->registerGeneratePressColors($base_colors, $saved_colors, $generatepress_options);

                        foreach ($blocks as $key => $block) {
                            if (in_array($load_colors_styles, ['colors', 'both'])) {
                                $colors = $block->getColorsToloadGeneratePress();
                                if (is_array($colors) && count($colors) > 0) {
                                    $generatepress_options = $rdgb->helpers->registerGeneratePressColors($colors, $saved_colors, $generatepress_options);
                                }
                            }

                            if (in_array($load_colors_styles, ['styles', 'both'])) {
                                $styles = $block->getStylesToloadGeneratePress();
                                if (is_array($styles) && count($styles) > 0) {
                                    $generatepress_options = $rdgb->helpers->registerGeneratePressStyles($styles, $saved_styles, $generatepress_options);
                                }
                            }
                        }
                    } else {
                        foreach ($blocks as $key => $block) {
                            if (in_array($load_colors_styles, ['styles', 'both'])) {
                                $styles = $block->getStylesToloadGeneratePress();
                                if (is_array($styles) && count($styles) > 0) {
                                    $rdgb->helpers->registerStylesCss($block, $styles);
                                }
                            }
                        }
                    }
                }

                $cache_cron = '';
                $cache_status = $_POST['acf']['key_rdg_blocks_cache_status'];

                if ($cache_status == 'active') {
                    $cache_cron = $_POST['acf']['key_rdg_blocks_cache_cron_time'];
                }

                $set_option_status = (!empty($cache_status) && $cache_status == 'active') ? true : false;
                update_option('rdg_blocks_cache_status', $set_option_status, true);
                $original_cron = get_option('rdg_blocks_cache_cron_time');

                if ((!empty($cache_cron)) && ($original_cron != $cache_cron)) {
                    wp_clear_scheduled_hook('rdg_blocks_cache_cron_event');
                    wp_schedule_event(time(), $cache_cron, 'rdg_blocks_cache_cron_event');
                    update_option('rdg_blocks_cache_cron_time', $cache_cron);
                }
            } catch (\Exception $exception) {
                error_log(print_r([
                    'message' => $exception->getMessage(),
                ], true));
            }
        }
    }
}
