<?php

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

class Rdg_Blocks_Scores_And_Odds extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_SCORES_AND_ODDS;
    private $block_folder_name = BLOCK_RDG_SCORES_AND_ODDS;
    protected $block_title = 'RDG Scores and Odds';
    private $block_description = 'This block displays scores and odds for various sports events. The block can display the latest scores, scores for a specific date, or scores within a date range.';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'score', 'odd', 'api'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $is_pre_saved = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Scores and Odds';
    protected $config_menu_title = 'Scores and Odds';
    protected $interval_field = 'scores_and_odds_interval';

    public function init() {
        $this->register_block();
        add_action('acf/init', [$this, 'register_config_menu'], 20);
        add_action('acf/init', [$this, 'register_fields'], 20);
        add_filter('acf/prepare_field', [$this, 'loadLeagues']);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
                'enqueue_style' => $rdg_helpers->webpack('rdg_scores_and_odds.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_scores_and_odds_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-scores-and-odds/assets/js/rdg-scores-and-odds.js', [], '1', true);
                    wp_enqueue_script('rdg_scores_and_odds_script');
                    wp_localize_script('rdg_scores_and_odds_script','rdg_scores_and_odds_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                },
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-scores-and-odds.png",
                        ),
                    ),
                ),
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
                'render_callback' => function($block) use ($rdg_helpers) {
                    global $wp_query;
                    $loop = $wp_query->in_the_loop;
                    $template_path = RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php";

                    if ($loop) {
                        include $template_path;
                        return;
                    }

                    $trace_config = $rdg_helpers->getBacktraceConfig();
                    $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $trace_config['max_trace']);
                    $trace_valid_admin = $rdg_helpers->checkExistsTraceFunction($traces, $trace_config['max_trace'], $trace_config['functions']);

                    if (is_admin() && !$trace_valid_admin) {
                        include $template_path;
                        return;
                    }
                },
            ]);
        }
    }

    public function register_fields() {
        $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_scores_and_odds',
                'title' => 'Block_rdg_scores_and_odds',
                'fields' => array(
                    array(
                        'key' => 'key_rdg_scores_and_odds_block_type',
                        'label' => 'Block Type',
                        'name' => 'rdg_scores_and_odds_block_type',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'api' => 'API',
                            'manual' => 'Manual',
                        ),
                        'default_value' => '',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'allow_in_bindings' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_manual',
                        'label' => 'Manual',
                        'name' => 'rdg_scores_and_odds_manual',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_block_type',
                                    'operator' => '==',
                                    'value' => 'manual',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'acfe_repeater_stylised_button' => 0,
                        'layout' => 'row',
                        'pagination' => 0,
                        'min' => 1,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Row',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'key_rdg_scores_and_odds_team_a',
                                'label' => 'Team A',
                                'name' => 'rdg_scores_and_odds_team_a',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_img_team_a',
                                'label' => 'Img Team A',
                                'name' => 'rdg_scores_and_odds_img_team_a',
                                'aria-label' => '',
                                'type' => 'image',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'uploader' => '',
                                'return_format' => 'array',
                                'library' => 'all',
                                'upload_folder' => '',
                                'acfe_thumbnail' => 0,
                                'min_width' => '',
                                'min_height' => '',
                                'min_size' => '',
                                'max_width' => '',
                                'max_height' => '',
                                'max_size' => '',
                                'mime_types' => '',
                                'allow_in_bindings' => 0,
                                'preview_size' => 'medium',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_team_b',
                                'label' => 'Team B',
                                'name' => 'rdg_scores_and_odds_team_b',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'rdg_scores_and_odds_img_team_b',
                                'label' => 'Img Team B',
                                'name' => 'rdg_scores_and_odds_img_team_b',
                                'aria-label' => '',
                                'type' => 'image',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'uploader' => '',
                                'return_format' => 'array',
                                'library' => 'all',
                                'upload_folder' => '',
                                'acfe_thumbnail' => 0,
                                'min_width' => '',
                                'min_height' => '',
                                'min_size' => '',
                                'max_width' => '',
                                'max_height' => '',
                                'max_size' => '',
                                'mime_types' => '',
                                'allow_in_bindings' => 0,
                                'preview_size' => 'medium',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_manual_game_part',
                                'label' => 'Game Part',
                                'name' => 'rdg_scores_and_odds_manual_game_part',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_date',
                                'label' => 'Date',
                                'name' => 'rdg_scores_and_odds_date',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_hour',
                                'label' => 'Hour',
                                'name' => 'rdg_scores_and_odds_hour',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_score_a',
                                'label' => 'Score A',
                                'name' => 'rdg_scores_and_odds_score_a',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_score_b',
                                'label' => 'Score B',
                                'name' => 'rdg_scores_and_odds_score_b',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_spread_a',
                                'label' => 'Spread A',
                                'name' => 'rdg_scores_and_odds_spread_a',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_spread_b',
                                'label' => 'Spread B',
                                'name' => 'rdg_scores_and_odds_spread_b',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_total_a',
                                'label' => 'Total A',
                                'name' => 'rdg_scores_and_odds_total_a',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_total_b',
                                'label' => 'Total B',
                                'name' => 'rdg_scores_and_odds_total_b',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_moneyline_a',
                                'label' => 'Moneyline A',
                                'name' => 'rdg_scores_and_odds_moneyline_a',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_moneyline_b',
                                'label' => 'Moneyline B',
                                'name' => 'rdg_scores_and_odds_moneyline_b',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'allow_in_bindings' => 0,
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_previews',
                                'label' => 'Previews',
                                'name' => 'rdg_scores_and_odds_previews',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'allow_in_bindings' => 0,
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                            array(
                                'key' => 'key_rdg_scores_and_odds_picks',
                                'label' => 'Picks',
                                'name' => 'rdg_scores_and_odds_picks',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'allow_in_bindings' => 0,
                                'parent_repeater' => 'key_rdg_scores_and_odds_manual',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_sports',
                        'label' => 'Sports',
                        'name' => 'rdg_scores_and_odds_sports',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_block_type',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => [0 => 'Choose an option'] + $sports,
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'max' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_null' => 0,
                        'allow_in_bindings' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'allow_custom' => 0,
                        'search_placeholder' => '',
                        'min' => '',
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_league',
                        'label' => 'League',
                        'name' => 'rdg_scores_and_odds_league',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => ['' => 'Choose an option'],
                        'default_value' => '',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_game_part',
                        'label' => 'Game Part',
                        'name' => 'rdg_scores_and_odds_game_part',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_block_type',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'game' => 'Game'
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'max' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_null' => 0,
                        'allow_in_bindings' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'allow_custom' => 0,
                        'search_placeholder' => '',
                        'min' => '',
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_date_type',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_block_type',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'latest' => 'Latest',
                            'plus_3' => 'Next 3 days',
                            'plus_7' => 'Next 7 days',
                            'specific' => 'Specific Date',
                            'range' => 'Range',
                        ),
                        'default_value' => 'latest',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'max' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_null' => 0,
                        'allow_in_bindings' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'allow_custom' => 0,
                        'search_placeholder' => '',
                        'min' => '',
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_from_day',
                        'label' => 'From day',
                        'name' => 'rdg_scores_and_odds_from_day',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_date_type',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                        'placeholder' => '',
                        'min_date' => '',
                        'max_date' => '',
                        'no_weekends' => 0,
                        'allow_in_bindings' => 0,
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_to_day',
                        'label' => 'To day',
                        'name' => 'rdg_scores_and_odds_to_day',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_date_type',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                        'placeholder' => '',
                        'min_date' => '',
                        'max_date' => '',
                        'no_weekends' => 0,
                        'allow_in_bindings' => 0,
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_specific_date',
                        'label' => 'Specific Date',
                        'name' => 'rdg_scores_and_odds_specific_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_date_type',
                                    'operator' => '==',
                                    'value' => 'specific',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                        'placeholder' => '',
                        'min_date' => '',
                        'max_date' => '',
                        'no_weekends' => 0,
                        'allow_in_bindings' => 0,
                    ),
                    array(
                        'key' => 'key_rdg_scores_and_odds_number_of_items',
                        'label' => 'Quantity',
                        'name' => 'number_of_items',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_rdg_scores_and_odds_block_type',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'allow_in_bindings' => 0,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-scores-and-odds',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'api_configuration_scores_and_odds_block',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_scores_and_odds_api_url',
                        'label' => 'URL',
                        'name' => 'scores_and_odds_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_scores_and_odds_api_token',
                        'label' => 'Token',
                        'name' => 'scores_and_odds_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '40',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_scores_and_odds_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'scores_and_odds_interval',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-scores-and-odds',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function loadLeagues($field) {
        if ($field['key'] == 'key_rdg_scores_and_odds_league') {
            $sport = get_field_object('key_rdg_scores_and_odds_sports');
            if (!is_array($sport) || !isset($sport['value']) || empty($sport['value'])) return $field;
            $field['choices'] = ['' => 'Choose an option'];
            
            $leagues = (function_exists('shMappingHierarchyFamily')) ? shMappingHierarchyFamily($sport['value']) : [];
            if (is_array($leagues) && count($leagues) > 0) {
                $field['choices'] = ['' => 'Choose an option'] + $leagues;
            }
        }

        return $field;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('scores_and_odds_api_url', 'option');
        $api_token = get_field('scores_and_odds_api_token', 'option');
        $cache_refresh = get_field('scores_and_odds_interval', 'option');
        $items = (!empty($items)) ? intval($items) : 10;
        $today = date("Y-m-d");

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $api_url .= '?recordsQty='.$items;

        if (isset($attributes['game_part']) && $attributes['game_part'] == 'game') {
            $api_url .= '&showOnlyParents=true';
        }

        if ($attributes['date_type'] == 'specific') {
            $api_url .= '&principalDate=' .$attributes['specific'];
        } else if ($attributes['date_type'] == 'latest') {
            $api_url .= '&principalDate='. $today;
        } else if ($attributes['date_type'] == 'plus_3') {
            $api_url .= '&principalDate='.$today. '&secondaryDate='.date("Y-m-d", strtotime("+3 days"));            
        } else if ($attributes['date_type'] == 'plus_7') {
            $api_url .= '&principalDate='.$today. '&secondaryDate='.date("Y-m-d", strtotime("+7 days"));            
        } else {
            $api_url .= '&principalDate='.$attributes['from_day']. '&secondaryDate='.$attributes['to_day'];
        }

        if (isset($attributes['league']) && !empty($attributes['league'])) {
            preg_match('/\d+/', $attributes['league'], $match);
            $league = $match[0] ?? '';
            $api_url .= '&sports_hierarchy='.$league;
        } else if (isset($attributes['sports']) && !empty($attributes['sports'])) {
            $sport = preg_replace('/\D/', '', $attributes['sports']);
            $api_url .= '&sports_hierarchy='.$sport;
        }

        $api_request = $api_url.'&api_token='.$api_token; 

        return [
            'items' => $items,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
        ];
    }

    public function getApiParams() {
        return [
            'sports' => 'rdg_scores_and_odds_sports',
            'league' => 'rdg_scores_and_odds_league',
            'game_part' => 'rdg_scores_and_odds_game_part',
            'date_type' => 'date_type',
            '_to_transform_' => [
                [
                    'key' => 'specific',
                    'function' => 'formatDate',
                    'params' => ['rdg_scores_and_odds_specific_date'],
                    'fields_date' => ['rdg_scores_and_odds_specific_date'],
                ],[
                    'key' => 'from_day',
                    'function' => 'formatDate',
                    'params' => ['rdg_scores_and_odds_from_day'],
                    'fields_date' => ['rdg_scores_and_odds_from_day'],
                ],[
                    'key' => 'to_day',
                    'function' => 'formatDate',
                    'params' => ['rdg_scores_and_odds_to_day'],
                    'fields_date' => ['rdg_scores_and_odds_to_day'],
                ],
            ],
        ];
    }

    // public function getApiParams() {
    //     return [
    //         'sports' => 'rdg_scores_and_odds_sports',
    //         'league' => 'rdg_scores_and_odds_league',
    //         'game_part' => 'rdg_scores_and_odds_game_part',
    //         'date_type' => 'date_type',
    //         'specific' => 'specific',
    //         'from_day' => 'from_day',
    //         'to_day' => 'to_day',
    //     ];
    // }

    public function formatDate($date) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
    
        return $rdgb_helpers->getValidDate($date);
    }

    public function getFieldsValidate() {
        return [
            'visitor_team' => ['required', 'notnull'],
            'home_team' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
        ];
    }

    public function get_image($url_image, $attributes = []) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $url_image = $rdgb_helpers->getImageSource($url_image, $attributes);

        return $url_image;
    }

    public function get_style($type, $fields) {
        $style = [];

        if ('buttons' == $type) {
            $style[] = 'background-color: '.$fields['background_color'];
            $style[] = 'color: '.$fields['text_color'];
    
            return implode('; ', $style);
        }
    
        return '';
    }

    public function getPreviews($picks) {
        if (!is_array($picks) || count($picks) == 0) return [];

        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

        $id_previews = array_column($picks, 'id_preview');
        if (is_array($id_previews) && count($id_previews) == 0) return [];

        $previews_array = implode(', ', $id_previews);
        $game_slug = $rdgb->helpers->getShGameSlug()['slug'];

        global $wpdb;
        $query = "SELECT m2.meta_value AS shg_external_id, p.ID AS post_id
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} AS m2 ON p.ID = m2.post_id AND m2.meta_key = 'shg_external_id'
            WHERE p.post_type = '{$game_slug}' AND p.post_status = 'publish' AND m2.meta_value IN ({$previews_array})";

        $urls = [];
        $games_url = $wpdb->get_results($query, ARRAY_A);

        if (is_array($games_url) && count($games_url) > 0) {
            foreach ($games_url as $key => $game) {
                $urls[$game['shg_external_id']] = $game['post_id'];
            }
        }

        return $urls;
    }

    public function getPreSavedData($picks, $attributes = [])
    {
        $pre_saved_data = [];
        $games_previews = $this->getPreviews($picks);

        if (is_array($picks) && count($picks) > 0) {
            foreach ($picks as $key => $pick) {
                $pre_saved_data[$key] = $pick;

                if (is_array($games_previews) && isset($pick['id_preview']) 
                    && !empty($pick['id_preview']) && isset($games_previews[$pick['id_preview']]) 
                    && !empty($games_previews[$pick['id_preview']])) {
                        $pre_saved_data[$key]['local_game_id'] = $games_previews[$pick['id_preview']];
                }
            }
        }

        return $pre_saved_data;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => '--color-scores-and-odds-p','slug' => '--color-scores-and-odds-p','color' => '#67748e'],
            ['name' => '--color-scores-and-odds-wrapper-bg','slug' => '--color-scores-and-odds-wrapper-bg','color' => '#fff'],
            ['name' => '--color-scores-and-odds-header-bg','slug' => '--color-scores-and-odds-header-bg','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-header-p','slug' => '--color-scores-and-odds-header-p','color' => '#fff'],
            ['name' => '--color-scores-and-odds-black','slug' => '--color-scores-and-odds-black','color' => '#000'],
            ['name' => '--color-scores-and-odds-border','slug' => '--color-scores-and-odds-border','color' => '#E6EBF2'],
            ['name' => '--color-scores-and-odds-prev-border','slug' => '--color-scores-and-odds-prev-border','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-prev-bg','slug' => '--color-scores-and-odds-prev-bg','color' => '#fff'],
            ['name' => '--color-scores-and-odds-prev-p','slug' => '--color-scores-and-odds-prev-p','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-prev-border-hover','slug' => '--color-scores-and-odds-prev-border-hover','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-prev-bg-hover','slug' => '--color-scores-and-odds-prev-bg-hover','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-prev-p-hover','slug' => '--color-scores-and-odds-prev-p-hover','color' => '#fff'],
            ['name' => '--color-scores-and-odds-pick-border','slug' => '--color-scores-and-odds-pick-border','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-pick-bg','slug' => '--color-scores-and-odds-pick-bg','color' => '#1c4579'],
            ['name' => '--color-scores-and-odds-pick-p','slug' => '--color-scores-and-odds-pick-p','color' => '#fff'],
            ['name' => '--color-scores-and-odds-pick-border-hover','slug' => '--color-scores-and-odds-pick-border-hover','color' => '#0160ac'],
            ['name' => '--color-scores-and-odds-pick-bg-hover','slug' => '--color-scores-and-odds-pick-bg-hover','color' => '#0160ac'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-scores-and-odds .sao-container .sao-wrapper .header p ',
                'fontWeight' =>'700',
            ],
        ];
    }
}

add_action('wp_ajax_nopriv_load_scores_and_odds_options','getScoresAndOddsOptions');
add_action('wp_ajax_load_scores_and_odds_options','getScoresAndOddsOptions');

function getScoresAndOddsOptions() {
    $sport = $_POST['sport'] ?? null;
    $data['leagues'] = [];

    if (empty($sport)) {
        echo json_encode($data);
        wp_die();
    }

    $leagues = (function_exists('shMappingHierarchyFamily')) ? shMappingHierarchyFamily($sport) : [];

    if (!is_array($leagues) || count($leagues) == 0) {
        echo json_encode($data);
        wp_die();
    }

    $data['leagues'] = ['' => 'Choose an option'] + $leagues;

    echo json_encode($data);
    wp_die();
}

$rdg_scores_and_odds_class = new Rdg_Blocks_Scores_And_Odds();
$rdg_scores_and_odds_class->init();

return $rdg_scores_and_odds_class;
