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

define('PLATFORM', true);

if (!PLATFORM){
    require_once __DIR__ . '/vendor/oscarotero/env/src/Env.php';
    require_once __DIR__ . '/vendor/oscarotero/env/src/env_function.php';
}

use function Env\env;

// 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.2.31');

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

// Images Maintenance Path
define('IMAGES_MAINTENANCE_FOLDER', wp_upload_dir()['basedir'].'/'.RDGBLOCKS_NAME_SLUG.'/images/');

// Cache Maintenance Path
define('CACHE_MAINTENANCE_FOLDER', wp_upload_dir()['basedir'].'/'.RDGBLOCKS_NAME_SLUG.'/');

// 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');
define('BLOCK_RDG_PICKS_LIST', 'rdg-picks-list');
define('BLOCK_RDG_FAQ', 'rdg-faq');
define('BLOCK_RDG_BUTTONS', 'rdg-buttons');
define('BLOCK_RDG_LOGO_TEAM', 'rdg-logo-team');
define('BLOCK_RDG_ODD_BETTING_SELECT', 'rdg-odd-betting-select');
define('BLOCK_RDG_ODD_BETTING_DATE', 'rdg-odd-betting-date');
define('BLOCK_RDG_SPORTS_PICKS_VS', 'rdg-sports-picks-vs');
define('BLOCK_RDG_PARAGRAPH_CUSTOM', 'rdg-paragraph-custom');
define('BLOCK_RDG_POSTS_LIST', 'rdg-posts-list');
define('BLOCK_RDG_NEW_PARAGRAPH_CUSTOM', 'rdg-new-paragraph-custom');
define('BLOCK_RDG_PICKS_VS', 'rdg-picks-vs');
define('BLOCK_RDG_PICKS_VS_CATEGORIES', 'rdg-picks-vs-categories');
define('BLOCK_RDG_MAIN_PROMOTIONS', 'rdg-main-promotions');
define('BLOCK_RDG_TOP_CAPPERS', 'rdg-top-cappers');
define('BLOCK_RDG_FAVORITE_CAPPERS', 'rdg-favorite-cappers');
define('BLOCK_RDG_LEADER_BOARD', 'rdg-leader-board');
define('BLOCK_RDG_LOGO_RANKING', 'rdg-logo-ranking');
define('BLOCK_RDG_TABLE', 'rdg-table');
define('BLOCK_RDG_ADMIN_CAPPERS_SIMPLE', 'rdg-admin-cappers-simple');
define('BLOCK_RDG_TABLE_LEAGUES', 'rdg-table-leagues');
define('BLOCK_RDG_COLUMNS_PICKS', 'rdg-columns-picks');
define('BLOCK_RDG_SEPARATOR', 'rdg-separator');
define('BLOCK_RDG_SINGLE_PICK', 'rdg-single-pick');
define('BLOCK_RDG_PARAGRAPH_COLOR', 'rdg-paragraph-color');
define('BLOCK_RDG_LOGIN', 'rdg-login');
define('BLOCK_RDG_REGISTER', 'rdg-register');
define('BLOCK_RDG_BOX_LIST', 'rdg-box-list');
define('BLOCK_RDG_SOCIALS_ICONS', 'rdg-socials-icons');
define('BLOCK_RDG_CONSENSUS', 'rdg-consensus');
define('BLOCK_RDG_POSTS_AJAX', 'rdg-posts-ajax');
define('BLOCK_RDG_EXPERTS_BANNER', 'rdg-experts-banner');
define('BLOCK_RDG_PREVIEWS_AND_PREDICTIONS', 'rdg-previews-and-predictions');
define('BLOCK_RDG_SECONDARY_BANNER', 'rdg-secondary-banner');
define('BLOCK_RDG_BUTTONS_COLUMN', 'rdg-buttons-column');
define('BLOCK_RDG_RANKING_BOOKIE', 'rdg-ranking-bookie');
define('BLOCK_RDG_BOOKIE_LOGO', 'rdg-bookie-logo');
define('BLOCK_RDG_PRODUCT_REPORT', 'rdg-product-report');
define('BLOCK_RDG_BEST_PPH', 'rdg-best-pph');
define('BLOCK_RDG_SINGLE_TOP_HANDICAPPERS', 'rdg-single-top-handicappers');
define('BLOCK_RDG_SIMPLE_POST_LIST', 'rdg-simple-post-list');
define('BLOCK_RDG_HEADING', 'rdg-heading');
define('BLOCK_RDG_PROS_CONS', 'rdg-pros-cons');
define('BLOCK_RDG_HEADING_PARAGRAPH', 'rdg-heading-paragraph');
define('BLOCK_RDG_MEMBERSHIPS', 'rdg-memberships');
define('BLOCK_RDG_BOOKIE_SUMMARY', 'rdg-bookie-summary');
define('BLOCK_RDG_QUICK_LINKS', 'rdg-quick-links');
define('BLOCK_RDG_BOOKIE_SUMMARY_SIDEBAR', 'rdg-bookie-summary-sidebar');
define('BLOCK_RDG_QUICK_LINKS_SIDEBAR', 'rdg-quick-links-sidebar');
define('BLOCK_RDG_CPT_LIST', 'rdg-cpt-list');
define('BLOCK_RDG_BEST_PPH_SITES', 'rdg-best-pph-sites');
define('BLOCK_RDG_GAMBLING_CENTER', 'rdg-gambling-center');
define('BLOCK_RDG_BOOKIE_SELECTOR', 'rdg-bookie-selector');
define('BLOCK_RDG_BANNER_SIDEBAR', 'rdg-banner-sidebar');
define('BLOCK_RDG_SPORT_INFORMATION', 'rdg-sport-information');
define('BLOCK_RDG_MEMBERSHIP_INFO', 'rdg-membership-info');
define('BLOCK_RDG_PROMOTE_SITE', 'rdg-promote-site');

define('BLOCK_RDG_TYPE_LATEST', 'latest');
define('BLOCK_RDG_TYPE_SPECIFIC', 'specific');
define('BLOCK_RDG_TYPE_EXTERNAL', 'external');

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

// API DATE TYPE
define('API_DATE_TYPE_YESTERDAY', 'yesterday');
define('API_DATE_TYPE_NOW', 'now');
define('API_DATE_TYPE_TOMORROW', 'tomorrow');
define('API_DATE_TYPE_RANGE', 'range');

// REDIS
define('REDIS_GROUP_BLOCKS', 'blocks');
define('REDIS_TIMEOUT', env('WP_REDIS_TIMEOUT') ?: 3600);

# RDG PLUGIN REVIEWS LIST
define('RDG_BLOCKS_REVIEWS', env('RDG_BLOCKS_REVIEWS') ?: 'pph-review,sportsbook-review');

/**
 * 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);
        $jquery_load = (isset(get_field('rdg_resource_jquery_group', 'option')['jquery_versions'])) ? get_field('rdg_resource_jquery_group', 'option')['jquery_versions'] : 'none';

        if ($jquery_load != 'none') {
            $path = 'core/includes/assets/js/jquery/';
            $jquery_dir = RDGBLOCKS_PLUGIN_DIR.$path;
            $jquery_uri = RDGBLOCKS_PLUGIN_URL.$path;

            if (file_exists($jquery_dir.$jquery_load)) {
                wp_enqueue_script('rdgblocks-'.$jquery_load, $jquery_uri.$jquery_load, [], RDGBLOCKS_VERSION, false);
            } else {
                error_log(print_r([
                    'message' => 'The requested jquery file does not exist.',
                    'jquery_load' => $jquery_load,
                    'jquery_dir' => $jquery_dir,
                    'jquery_uri' => $jquery_uri,
                ], true));
            }
        }

        // wp_enqueue_script('rdgblocks-bootstrap-custom', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/bootstrap_custom.js', [], RDGBLOCKS_VERSION, false);
        // wp_enqueue_script('rdgblocks-backend-scripts', RDGBLOCKS_PLUGIN_URL.'core/includes/assets/js/backend-scripts.js', [], RDGBLOCKS_VERSION, false);

        if (is_admin()) {
            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);
                    $current_block = $rdgb->settings->get_block($block_name);
                    $api_attributes = $current_block->get_api_attributes($items, $block['api_params']);

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

                    $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) use ($rdgb) {
        global $post;

        if (!isset($attributes['data']['custom_id'])) {
            $attributes['data']['custom_id'] = 'block-'.uniqid();
        }

        if (!empty($post->ID)) {
            $attributes['data']['post_id'] = $post->ID;
        }

        return $attributes;
    });

    return $rdgb;
}

$rdgb = RDGBLOCKS();

include 'blocks/rdg-team-schedules/rdg-team-schedules.php';
include 'blocks/rdg-top-sites/rdg-top-sites.php';
