<?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->block_list = $this->blocks_load();
    }

    /**
     * ######################
     * ###
     * #### 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 blocks_load() {
        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/init', array($this, 'generate_field_images_maintenance'));
        add_filter('acf/load_value/name=delete_images_cache', [$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/prepare_field/name=rdg_images_maintenance', [$this, 'load_field_images_maintenance'], 10, 3);

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

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

        return $block_classes;
    }

    public function get_blocks() {
        return $this->block_list;
    }

    public function get_block($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_delete_images_cache($value) {
        return 'keep';
    }

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

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

            //SBF Categories
            if( function_exists('acf_add_local_field_group') ):

                acf_add_local_field_group(array(
                    'key' => 'group_6422620ada259',
                    'title' => 'SBF Categories',
                    'fields' => array(
                        array(
                            'key' => 'field_6422620a4a276',
                            'label' => 'Category Type',
                            'name' => 'sbf_category_type',
                            'aria-label' => '',
                            'type' => 'text',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'default_value' => '',
                            'maxlength' => '',
                            'placeholder' => '',
                            'prepend' => '',
                            'append' => '',
                        ),
                    ),
                    'location' => array(
                        array(
                            array(
                                'param' => 'taxonomy',
                                'operator' => '==',
                                'value' => 'category',
                            ),
                        ),
                    ),
                    'menu_order' => 0,
                    'position' => 'normal',
                    'style' => 'default',
                    'label_placement' => 'top',
                    'instruction_placement' => 'label',
                    'hide_on_screen' => '',
                    'active' => true,
                    'description' => '',
                    'show_in_rest' => 0,
                ));
                
                endif;        
    }
}
