<?php

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

class Rdg_Blocks_Leader_Board extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_LEADER_BOARD;
    private $block_folder_name = 'rdg-leader-board';
    protected $block_title = 'RDG Leader Board';
    private $block_description = 'The block allow to structure a table with info about the leader board using as a parameter a category and a date range';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'leader', 'board', 'api'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Leader Board';
    protected $config_menu_title = 'Leader Board';
    protected $interval_field = 'leader_board_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_leader_board.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_leader_board_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-leader-board/assets/js/rdg-leader-board.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_leader_board_script');
                    wp_localize_script('rdg_leader_board_script','rdg_leader_board_var',['ajaxurl' => admin_url('admin-ajax.php')]);

                    wp_register_script('rdg_leader_board_sortable', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-leader-board/assets/js/sortable.min.js', [], '1', true);
                    wp_enqueue_script('rdg_leader_board_sortable');
                },
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-leader-board-template-preview.jpg",
                        ),
                    ),
                ),
                '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_leader_board_block',
                'title' => 'Block_rdg_leader_board',
                'fields' => array(
                    array(
                        'key' => 'key_rdg_leader_board_sport',
                        'label' => 'Sport',
                        'name' => 'rdg_leader_board_sport',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $sports,
                        'default_value' => '',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_leader_board_league',
                        'label' => 'League',
                        'name' => 'rdg_leader_board_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_leader_board_bet_type',
                        'label' => 'Bet Type',
                        'name' => 'rdg_leader_board_bet_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => ['' => 'Choose an option'] + $this->getLeaderBoardBetType(),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_leader_board_date_range',
                        'label' => 'Date Range',
                        'name' => 'rdg_leader_board_date_range',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $this->get_leader_board_date_range(),
                        'default_value' => '',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_leader_board_picks_range',
                        'label' => 'Picks Range',
                        'name' => 'rdg_leader_board_picks_range',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => $this->getLeaderBoardPicksRange(),
                        'default_value' => '',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_rdg_leader_board_items_per_page',
                        'label' => 'Items per page',
                        'name' => 'items_per_page',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 10,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-leader-board',
                        ),
                    ),
                ),
                '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_leader_board_block_sdfw34fs2332',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_leader_board_api_url',
                        'label' => 'URL',
                        'name' => 'leader_board_api_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_leader_board_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'leader_board_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' => '',
                    ),
                    array(
                        'key' => 'key_leader_board_api_token',
                        'label' => 'Token',
                        'name' => 'leader_board_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_leader_board_date_range',
                        'label' => 'Date Range',
                        'name' => 'leader_board_date_range',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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' => 'key_value',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_date_range',
                            ),
                            array(
                                'key' => 'key_title',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_date_range',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'key_leader_board_bet_type',
                        'label' => 'Bet Type',
                        'name' => 'leader_board_bet_type',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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' => 'key_value',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_bet_type',
                            ),
                            array(
                                'key' => 'key_title',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_bet_type',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'key_leader_board_picks_range',
                        'label' => 'Picks Range',
                        'name' => 'leader_board_picks_range',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        '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' => 'key_value',
                                'label' => 'Value',
                                'name' => 'value',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_picks_range',
                            ),
                            array(
                                'key' => 'key_title',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '50',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'key_leader_board_picks_range',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-leader-board',
                        ),
                    ),
                ),
                '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_leader_board_league') {
            $sport = get_field_object('key_rdg_leader_board_sport');
            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 get_leader_board_date_range() {
        $date_range = ['' => 'Choose an option'];
        $ranges = get_field('leader_board_date_range', 'option');

        if (is_array($ranges) && count($ranges) > 0) {
            foreach ($ranges as $range) {
                $date_range[$range['value']] = $range['title'];
            }
        }

        return $date_range;
    }

    public function getLeaderBoardBetType() {
        $bet_type = ['' => 'Choose an option'];
        $types = get_field('leader_board_bet_type', 'option');

        if (is_array($types) && count($types) > 0) {
            foreach ($types as $type) {
                $bet_type[$type['value']] = $type['title'];
            }
        }

        return $bet_type;
    }

    public function getLeaderBoardPicksRange() {
        $picks_range = ['' => 'Choose an option'];
        $ranges = get_field('leader_board_picks_range', 'option');

        if (is_array($ranges) && count($ranges) > 0) {
            foreach ($ranges as $range) {
                $picks_range[$range['value']] = $range['title'];
            }
        }

        return $picks_range;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('leader_board_api_url', 'option');
        $api_token = get_field('leader_board_api_token', 'option');
        $cache_refresh = get_field('leader_board_interval', 'option');
        $items = (!empty($items)) ? $items : 10;
        $duration = (isset($attributes['duration']) && !empty($attributes['duration'])) ? $attributes['duration'] : 365;
        $page = (isset($attributes['page']) && !empty($attributes['page'])) ? $attributes['page'] : 1;

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

        $api_url .= '?perPage='.$items;
        $api_url .= '&pageSelected='.$page;

        if (isset($attributes['sport']) && !empty($attributes['sport'])) {
            $sport = preg_replace('/\D/', '', $attributes['sport']);
            $api_url .= '&group='.$sport;
        }

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

        if (isset($attributes['bet_type']) && !empty($attributes['bet_type'])) {
            $api_url .= "&betType='".$attributes['bet_type']."'";
        }

        if (isset($attributes['duration']) && !empty($attributes['duration'])) {
            $api_url .= '&duration='.$attributes['duration'];
        } else if (isset($attributes['pick_range']) && !empty($attributes['pick_range'])) {
            $api_url .= '&pickRange='.$attributes['pick_range'];
        }
        
        $api_request = $api_url.'&api_token='.$api_token;

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

        return $request;
    }

    public function getApiParams() {
        return [
            'sport' => 'rdg_leader_board_sport',
            'league' => 'rdg_leader_board_league',
            'duration' => 'rdg_leader_board_date_range',
            'page' => 1,
            'bet_type' => 'rdg_leader_board_bet_type',
            'pick_range' => 'rdg_leader_board_picks_range',
        ];
    }

    public function getResourcesAjax($request) {
        $data = new StdClass();
        $data->json = '';
        $data->message = '';

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $leader_board = $rdgb_helpers->getApiDataAjax($this->block_name, $request);

        if (!empty($leader_board->message)) {
            $data->message = $leader_board->message;
        
            return $data;
        }

        $data->json = $leader_board->json;

        return $data;
    }

    public function getFieldsValidate() {
        return [
            'rank' => ['required', 'notnull'],
            //'id_handicapper' => ['required', 'notnull'],
            'name' => ['required', 'notnull'],
            //'slug' => ['required', 'notnull'],
            'win' => ['required'],
            'loss' => ['required'],
            'push' => ['required'],
            'risk_amount' => ['required'],
            'win_amount' => ['required'],
            //'lost_amount' => ['required', 'notnull'],
            'win_percentaje' => ['required'],
            'net' => ['required'],
            'total_bets' => ['required'],
            //'image_url' => ['required', 'notnull'],
            //'handicapper_detail_url' => ['required', 'notnull'],
        ];
    }

    public function getPreSavedData($data, $attributes = [])
    {
        return $data;
    }

    public function getColorsToloadGeneratePress()
    {
        return [
            [
                'name' => 'color-rdg-leader-board-table-filter',
                'slug' => 'color-rdg-leader-board-table-filter',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-table-filter-bg',
                'slug' => 'color-rdg-leader-board-table-filter-bg',
                'color' => '#03467d'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-border',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-border',
                'color' => '#cadae5'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-scrollbar',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-scrollbar',
                'color' => '#dedede'
            ],
            [
                'name' => 'color-rdg-leader-board-list-item-table-wrapper-static-column',
                'slug' => 'color-rdg-leader-board-list-item-table-wrapper-static-column',
                'color' => '#262626'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-before',
                'slug' => 'color-rdg-leader-board-sortable-th-before',
                'color' => 'transparent'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-after',
                'slug' => 'color-rdg-leader-board-sortable-th-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-hover-after',
                'slug' => 'color-rdg-leader-board-sortable-th-hover-after',
                'color' => '#03467d'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-dir-d-after',
                'slug' => 'color-rdg-leader-board-sortable-dir-d-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-dir-u-after',
                'slug' => 'color-rdg-leader-board-sortable-dir-u-after',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-hover-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-hover-before',
                'color' => 'inherit'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-dir-d-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-dir-d-before',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-indicador-left-dir-u-before',
                'slug' => 'color-rdg-leader-board-sortable-indicador-left-dir-u-before',
                'color' => '#0160ac'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th',
                'slug' => 'color-rdg-leader-board-sortable-th',
                'color' => '#344767'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-th-bg',
                'slug' => 'color-rdg-leader-board-sortable-th-bg',
                'color' => '#f8f8f8'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-td-bg',
                'slug' => 'color-rdg-leader-board-sortable-td-bg',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-sortable-td-name',
                'slug' => 'color-rdg-leader-board-sortable-td-name',
                'color' => '#344767'
            ],
            [
                'name' => 'color-rdg-leader-board-button',
                'slug' => 'color-rdg-leader-board-button',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-button-bg',
                'slug' => 'color-rdg-leader-board-button-bg',
                'color' => '#ffffff'
            ],
            [
                'name' => 'color-rdg-leader-board-button-border',
                'slug' => 'color-rdg-leader-board-button-border',
                'color' => '#E9ECEF'
            ],
        ];
    }

    public function getStylesToloadGeneratePress()
    {
        return [
            [
                'customSelector' => '.rdg-leader-board .table .table-filter .filter .filter-option',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .list',
                'fontSize' => '1rem',
                'fontSizeTablet' => '.875rem',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable th::after, .rdg-leader-board .sortable th::before',
                'fontSize' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable th',
                'fontWeight' => '600',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .filter-option select',
                'fontSize' => '.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .table-filter .filter .filter-option',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .table .list .list-items',
                'fontSize' => '.9rem',
                'fontWeight' => '400',
            ],
            [
                'customSelector' => '.rdg-leader-board .list-pagination button',
                'fontSize' => '.9rem',
                'fontWeight' => '400',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable td.name',
                'fontWeight' => '600',
            ],
            [
                'customSelector' => '.rdg-leader-board .sortable td.group',
                'fontWeight' => '600',
            ],
        ];
    }
}

add_action('wp_ajax_nopriv_load_leader_board','get_leader_board_data');
add_action('wp_ajax_load_leader_board','get_leader_board_data');

function get_leader_board_data() {
    $items = $_POST['items'];
    $duration = $_POST['duration'];
    $id_sub_category = $_POST['id_sub_category'];
    $page = $_POST['page'];

    $message = null;
    $api_url = get_field('leader_board_api_url', 'option');
    $api_token = get_field('leader_board_api_token', 'option');

    if (!empty($api_url) && !empty($api_token)) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

        $block_name = BLOCK_RDG_LEADER_BOARD;
        $block_leader_board = $rdgb->settings->getBlock($block_name);
        $api_attributes = $block_leader_board->getApiAttributes($items, ['category' => $id_sub_category, 'duration' => $duration, 'page' => $page]);
        $response = $block_leader_board->getResourcesAjax($api_attributes);

        if (empty($response->message)) {
            $page = (isset($response->json['page_selected'])) ? $response->json['page_selected'] : 1;
            unset($response->json['page_selected']);
            $total_pages = (isset($response->json['total_pages'])) ? $response->json['total_pages'] : 1;
            unset($response->json['total_pages']);

            $leaders = $response->json;
        } else {
            $leaders = null;
            $message = $response->message;
        }
    } else {
        $message = 'Configure API connection correctly.';
    }

    if (!empty($message)) {
        $message = 'Leaders with these characteristics were not found.';
        require 'partials/message.php';
        wp_die();
    }

    require 'partials/api.php';

    wp_die();
}

add_action('wp_ajax_nopriv_load_leader_board_leagues','getLeaderBoardLeagues');
add_action('wp_ajax_load_leader_board_leagues','getLeaderBoardLeagues');

function getLeaderBoardLeagues() {
    $items = $_POST['items'] ?? 10;
    $sport = $_POST['sport'] ?? null;
    $league = $_POST['league'] ?? null;
    $duration = $_POST['duration'] ?? 365;
    $bet_type = $_POST['bet_type'] ?? '';
    $pick_range = $_POST['pick_range'] ?? '';
    $page = $_POST['page'] ?? 1;

    $data['leagues'] = [];
    $data['data'] = [];

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

    $members_default = '';
    $leagues = (function_exists('shMappingHierarchyFamily')) ? shMappingHierarchyFamily($sport) : [];
    $members = (function_exists('shMappingMembershipsData')) ? shMappingMembershipsData() : [];
    $members_logic = (function_exists('shMappingGetMembershipsLogic')) ? shMappingGetMembershipsLogic() : [];

    if (isset($members_logic[0][0]['name']) && !empty($members_logic[0][0]['name'])) {
        $members_default = $members_logic[0][0]['name'];
    }

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

    $leaders = [];
    $api_url = get_field('leader_board_api_url', 'option');
    $api_token = get_field('leader_board_api_token', 'option');

    if (!empty($api_url) && !empty($api_token)) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

        $block_name = BLOCK_RDG_LEADER_BOARD;
        $block_leader_board = $rdgb->settings->getBlock($block_name);
        $api_attributes = $block_leader_board->getApiAttributes($items, [
            'sport' => $sport, 
            'league' => $league, 
            'duration' => $duration, 
            'page' => $page,
            'bet_type' => $bet_type,
            'pick_range' => $pick_range,
        ]);

        $response = $block_leader_board->getResourcesAjax($api_attributes);
        $total_pages = (isset($response->json['total_pages'])) ? $response->json['total_pages'] : 1;
        unset($response->json['total_pages']);

        if (empty($response->message)) {
            $leaders = $response->json;
        }
    }

    $data['leagues'] = ['' => 'Choose an option'] + $leagues;
    $data['members'] = $members;
    $data['members_default'] = $members_default;
    $data['total_pages'] = $total_pages;
    $data['data'] = $leaders;

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

add_action('wp_ajax_nopriv_load_leader_board_leagues_options','getLeaderBoardLeaguesOptions');
add_action('wp_ajax_load_leader_board_leagues_options','getLeaderBoardLeaguesOptions');

function getLeaderBoardLeaguesOptions() {
    $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_leader_board_class = new Rdg_Blocks_Leader_Board();
$rdg_leader_board_class->init();

return $rdg_leader_board_class;
