<?php
/**
 * RDG-Blocks
 *
 * @package       RDGBLOCKS
 * @author        RDGCorp
 * @version 1.0.25
 *
 * @wordpress-plugin
 * Plugin Name:   RDG-Blocks
 * Plugin URI:    https://www.rdgcorp.com
 * Description:   Custom Gutenberg Blocks
 * Version: 1.0.25
 * Author:        RDGCorp
 * Author URI:    https://www.rdgcorp.com
 * Text Domain:   rdg-blocks
 * Domain Path:   /languages
 */

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

/**
 * HELPER COMMENT START
 * 
 * This file contains the main information about the plugin.
 * It is used to register all components necessary to run the plugin.
 * 
 * The comment above contains all information about the plugin 
 * that are used by WordPress to differenciate the plugin and register it properly.
 * It also contains further PHPDocs parameter for a better documentation
 * 
 * The function RDGBLOCKS() is the main function that you will be able to 
 * use throughout your plugin to extend the logic. Further information
 * about that is available within the sub classes.
 * 
 * HELPER COMMENT END
 */

// Plugin name
define('RDGBLOCKS_NAME', 'RDG-Blocks');
define('RDGBLOCKS_NAME_SLUG', 'rdg-blocks');

// Plugin version
define('RDGBLOCKS_VERSION', '1.0.25');

// Plugin Root File
define('RDGBLOCKS_PLUGIN_FILE', __FILE__);

// Plugin base
define('RDGBLOCKS_PLUGIN_BASE', plugin_basename(RDGBLOCKS_PLUGIN_FILE));

// Plugin Folder Path
define('RDGBLOCKS_PLUGIN_DIR', plugin_dir_path(RDGBLOCKS_PLUGIN_FILE));

// Plugin Folder URL
define('RDGBLOCKS_PLUGIN_URL', plugin_dir_url(RDGBLOCKS_PLUGIN_FILE));

// Plugin Blocks Folder URL
define('RDGBLOCKS_PLUGIN_BLOCKS_DIR', plugin_dir_path(RDGBLOCKS_PLUGIN_FILE).'blocks/');

// Block List Const
define('BLOCK_RDG_CALL_TO_ACTION', 'rdg-call-to-action');
define('BLOCK_RDG_IMAGE_COLUMN', 'rdg-image-column');
define('BLOCK_RDG_MAIN_BANNER', 'rdg-main-banner');
define('BLOCK_RDG_SPORTS_PICKS', 'rdg-sports-picks');
define('BLOCK_RDG_TITLE', 'rdg-title');
define('BLOCK_RDG_TOP_WINNERS', 'rdg-top-winners');
define('BLOCK_RDG_ADMIN_CAPPERS', 'rdg-admin-cappers');
define('BLOCK_RDG_NEXT_GAME', 'rdg-next-game');
define('BLOCK_RDG_SLIDER_LATEST_POST', 'rdg-slider-latest-post');
define('BLOCK_RDG_LATEST_POST', 'rdg-latest-post');

// Source Data Const
define('SOURCE_DATA_MANUAL', 'manual');
define('SOURCE_DATA_API', 'api');

/**
 * Load the main class for the core functionality
 */
require_once RDGBLOCKS_PLUGIN_DIR.'core/class-rdg-blocks.php';

/**
 * Load the mase class for the blocks functionality
 */
require_once RDGBLOCKS_PLUGIN_BLOCKS_DIR."rdg-blocks-base.php";
require_once RDGBLOCKS_PLUGIN_BLOCKS_DIR."rdg-blocks-api-request.php";

/**
 * The main function to load the only instance
 * of our master class.
 *
 * @author  RDGCorp
 * @since   1.0.0
 * @return  object|Rdg_Blocks
 */
function RDGBLOCKS() {
    $rdgb = Rdg_Blocks::instance();
    $rdg_base_style = $rdgb->helpers->webpack('rdg_base_style.css');

    add_action('init', function () use ($rdg_base_style) {
        wp_enqueue_style('rdg_base_style', $rdg_base_style, [], true);
        wp_enqueue_script('rdgblocks-backend-scripts', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/backend-scripts.js', [], RDGBLOCKS_VERSION, false);
    });

    add_action('init', function() {
        remove_filter('acf_the_content', 'wpautop');
    });

    add_action('edit_post', function($post_id) use ($rdgb) {
        $post_content = get_post($post_id)->post_content;
        $blocks = $rdgb->settings->get_blocks();
        $blocks_caching = $rdgb->helpers->get_blocks_caching($blocks, $_POST, $post_content);

        if (count($blocks_caching) > 0) {
            foreach ($blocks_caching as $block) {
                $block_name = $block['name'];
                $items = $block['items'];
                $block_custom_id = $block['custom_id'];
                $rdgb->helpers->clear_cache($block_name, $post_id);

                try {
                    $cache_file = $rdgb->helpers->get_cache_name($block_name, $post_id, $block_custom_id, true);
                    $set_cache_file = $rdgb->helpers->set_cache_file($block_name, $cache_file);
                    $api_attributes = $rdgb->settings->get_block($block_name)->get_api_attributes($items);

                    $response = $rdgb->helpers->get_api_request(
                        $api_attributes['request'],
                        $api_attributes['method'],
                        $api_attributes['headers']
                    );

                    if ($response->http_code != 200) {
                        $rdgb->helpers->get_api_error($response->http_code, [
                            'block_name' => $block_name,
                            'http_code' => $response->http_code,
                            'set_cache_file' => $set_cache_file,
                            'api_attributes' => $api_attributes
                        ]);

                        continue;
                    }

                    $response_json = $rdgb->helpers->is_json($response->data);
                    
                    if ($response_json == null) {
                        $rdgb->helpers->get_api_error('json_response', [
                            'block_name' => $block_name,
                            'code' => 'json_response',
                            'set_cache_file' => $set_cache_file,
                            'api_attributes' => $api_attributes
                        ]);

                        continue;
                    }

                    if (count($response_json) != intval($api_attributes['items'])) {
                        array_pop($response_json);
                    }

                    $cache = fopen($set_cache_file->cache_file, "w");
                    fwrite($cache, serialize($response_json));
                    fclose($cache);

                    $rdgb->helpers->get_api_error(200, ['block_name' => $block_name]);
                } catch (Exception $exception) {
                    $rdgb->helpers->get_api_error('', [
                        'block_name' => $block_name,
                        'set_cache_file' => $set_cache_file,
                        'api_attributes' => $api_attributes,
                        'exception' => [
                            'file' => $exception->getFile(),
                            'line' => $exception->getLine(),
                            'message' => $exception->getMessage(),
                        ],
                    ]);
                }
            }
        }
    });

    add_filter('acf/pre_save_block', function($attributes) {
        if (!isset($attributes['data']['custom_id'])) {
            $attributes['data']['custom_id'] = 'block-'.uniqid();
        }
    
        return $attributes;
    });

    return $rdgb;
}

$rdgb = RDGBLOCKS();
