<?php

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

class Rdg_Blocks_Sport_Betting_Odds extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_SPORT_BETTING_ODDS;
    private $block_folder_name = BLOCK_RDG_SPORT_BETTING_ODDS;
    protected $block_title = 'RDG Sport Betting Odds';
    private $block_description = 'The block present in a dynamic form the info of the sport betting odds, it allow to edit the title, if the info is dynamic or custom, the sport category and the number of items displayed';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sport', 'betting', 'odd', '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 Sport Betting Odds';
    protected $config_menu_title = 'Sport Betting Odds';
    protected $interval_field = 'sport_betting_odds_interval';

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

        add_filter('acf/load_value/name=sport_betting_odds_block_id', [$this, 'setUniqueBlockId'], 10, 3);


    }

    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_sport_betting_odds.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_sport_betting_odds_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-sport-betting-odds/assets/js/rdg-sport-betting-odds.js', array('jquery'), '1.0.8', true);
                    wp_enqueue_script('rdg_sport_betting_odds_script');
                    wp_localize_script('rdg_sport_betting_odds_script','rdg_sport_betting_odds_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                    wp_localize_script('rdg_sport_betting_odds_script','rdg_blocks',['cache_dir' => CACHE_MAINTENANCE_FOLDER_URI]);
                },
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-sport-betting-odds-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() : [];
        
        // order sports alphabetically by value
        if (!empty($sports) && is_array($sports)) {
            asort($sports);
        }

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_sport_betting_odds',
                'title' => 'Block_rdg_sport_betting_odds',
                'fields' => array(
                    array(
                        'key' => 'field_64baa30e241a9',
                        'label' => 'Quantity',
                        'name' => 'number_of_items',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                        'allow_in_bindings' => 0,
                    ),

                    array(
                        'key' => 'key_sport_betting_odds_block_id',
                        'label' => 'ID',
                        'name' => 'sport_betting_odds_block_id',
                        'aria-label' => '',
                        'type' => 'acfe_hidden',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_sports',
                        'label' => 'Sports',
                        'name' => 'sport_betting_odds_sports',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => 'sports_hierarchy',
                            'id' => '',
                            'data-level' => 1,
                            'data-parent-id' => 'null',
                        ),
                        'choices' => [0 => 'Choose an option'] + $sports,
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_league',
                        'label' => 'League',
                        'name' => 'sport_betting_odds_league',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 1,
                        '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_sport_betting_odds_game_part',
                        'label' => 'Game Part',
                        'name' => 'sport_betting_odds_game_part',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        '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_sport_betting_odds_date_type',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        '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_sport_betting_odds_from_day',
                        'label' => 'From day',
                        'name' => 'sport_betting_odds_from_day',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_sport_betting_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_sport_betting_odds_to_day',
                        'label' => 'To day',
                        'name' => 'sport_betting_odds_to_day',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_sport_betting_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_sport_betting_odds_specific_date',
                        'label' => 'Specific Date',
                        'name' => 'sport_betting_odds_specific_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_sport_betting_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,
                    ),

                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-sport-betting-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_sport_betting_odds',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_sport_betting_odds_url',
                        'label' => 'URL',
                        'name' => 'sport_betting_odds_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_sport_betting_odds_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'sport_betting_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' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_token',
                        'label' => 'Token',
                        'name' => 'sport_betting_odds_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-sport-betting-odds',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function setUniqueBlockId($value, $post_id, $field) {
        $value = str_replace('block_', '', $post_id);

        return $value;
    }

    public function setBlockId($field) {
        global $_POST;

        try {
            if (isset($_POST['clientId'])) {
                $field['wrapper']['class'] = 'block-id-'.$_POST['clientId'];
            }
        } catch (\exception $exception) {
            error_log(print_r([
                'message' => 'RDG Sport Betting Odds: Error set block ID.',
                'field' => $field,
                'post' => $_POST,
                'exception' => $exception->getMessage(),
            ], true));
        }

        return $field;
    }

    public function loadLeagues($field) {
        if ($field['key'] == 'key_sport_betting_odds_league') {
            $sport = get_field_object('key_sport_betting_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 loadCategoriesHierarchy($field) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
        $sub_fields = [];

        global $_POST;

        try {
            if (isset($_POST['clientId'])) {
                $field['wrapper']['class'] = 'block-id-'.$_POST['clientId'];
            }

            if (!isset($_POST['block'])) {
                return $field;
            }

            $block = json_decode(stripslashes($_POST['block']), true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                error_log(print_r([
                    'message' => 'RDG Sport Betting Odds: Error trying to decode block information.',
                    'field' => $field,
                    'post' => $_POST,
                ], true));

                return $field;
            }

            if (isset($block['data']['sport_betting_odds_category'])) {
                $categories = $block['data']['sport_betting_odds_category'];
                $categories_array = $this->getShowCategories($categories);
                $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

                if (!is_array($sports) || count($sports) == 0) {
                    error_log(print_r([
                        'message' => 'RDG Sport Betting Odds: Error loading sports from shMappingHierarchySports.',
                        'field' => $field,
                        'post' => $_POST,
                    ], true));

                    return $field;
                }

                if (!isset($sports[$block['data']['sport_betting_odds_sports']])) {
                    return $field;
                }

                if (!is_array($categories_array) || (is_array($categories_array) && count($categories_array) == 0)) {
                    $categories_array = $this->getShowCategories($block['data']['sport_betting_odds_sports']);
                }

                $i = 1;
                $categories_name[$i] = $sports[$block['data']['sport_betting_odds_sports']];

                foreach ($categories_array as $category) {
                    $sport = $categories_name[$i];
                    $select = [
                        'key' => 'key-category-item-'.$i,
                        'label' => 'Category: '.$sport,
                        'name' => 'category-item-'.$i,
                        '_name' => 'category-item-'.$i,
                        'type' => 'select',
                        'choices' => [],
                        'wrapper' => array(
                            'width' => '',
                            'class' => 'category-item',
                            'id' => 'category-'.$i,
                            'data-level' => $i,
                            'data-parent-id' => $i,
                        ),
                        'default_value' => '0',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'multiple' => 0,
                    ];

                    $parent_id = '';
                    $option_selected = '';
                    foreach ($category as $cat_field) {
                        $select['choices'][$cat_field['id']] = $cat_field['value'];

                        if ($cat_field['selected'] == 1) {
                            $categories_name[$i + 1] = $cat_field['value'];
                            $option_selected = $cat_field['id'];
                            
                            $tem_parent = explode('-', str_replace('-child', '', $cat_field['id']));
                            unset($tem_parent[count($tem_parent) - 1]);
                            $parent_id = implode('-', $tem_parent);
                        }
                    }

                    $select['default_value'] = $option_selected;
                    $select['wrapper']['data-parent-id'] = $parent_id;
                    $sub_fields[] = $select;
                    $i++;
                }
            } else {
                # It is a new block, it has not been saved yet.

                return $field;
            }
        } catch (\exception $exception) {
            error_log(print_r([
                'message' => 'RDG Sport Betting Odds: Error loading saved categories.',
                'field' => $field,
                'post' => $_POST,
                'exception' => $exception->getMessage(),
            ], true));

            return $field;
        }

        $field['sub_fields'] = $sub_fields;

        return $field;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('sport_betting_odds_url', 'option');
        $api_token = get_field('sport_betting_odds_token', 'option');
        $cache_refresh = get_field('sport_betting_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;
        $api_url .= '&completeGames=1';

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

        // Date Type logic (like Scores and Odds)
        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 .= '&hierarchy='.$league;
        } else if (isset($attributes['sports']) && !empty($attributes['sports'])) {
            // Fallback to sport for backward compatibility with old blocks
            $sport = preg_replace('/\D/', '', $attributes['sports']);
            $api_url .= '&hierarchy='.$sport;
        } else {
            // League selection is required - return null if missing
            return null;
        }

        // Add token at the end (like Scores and Odds)
        $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' => 'sport_betting_odds_sports',
            'league' => 'sport_betting_odds_league',
            'game_part' => 'sport_betting_odds_game_part',
            'date_type' => 'date_type',
            '_to_transform_' => [
                [
                    'key' => 'specific',
                    'function' => 'formatDate',
                    'params' => ['sport_betting_odds_specific_date'],
                    'fields_date' => ['sport_betting_odds_specific_date'],
                ],[
                    'key' => 'from_day',
                    'function' => 'formatDate',
                    'params' => ['sport_betting_odds_from_day'],
                    'fields_date' => ['sport_betting_odds_from_day'],
                ],[
                    'key' => 'to_day',
                    'function' => 'formatDate',
                    'params' => ['sport_betting_odds_to_day'],
                    'fields_date' => ['sport_betting_odds_to_day'],
                ],
            ],
        ];
    }

    public function formatDate($date) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;

        return $rdgb_helpers->getValidDate($date);
    }

    public function getFieldsValidate() {
        return [
            'money_line_home_odds' => ['required', 'notnull'],
            'money_line_visitor_odds' => ['required', 'notnull'],
            'total_over_points' => ['required', 'notnull'],
            'total_over_odds' => ['required', 'notnull'],
            'total_under_points' => ['required', 'notnull'],
            'total_under_odds' => ['required', 'notnull'],
            'spread_home_points' => ['required', 'notnull'],
            'spread_home_odds' => ['required', 'notnull'],
            'spread_visitor_points' => ['required', 'notnull'],
            'spread_visitor_odds' => ['required', 'notnull'],
        ];
    }

    public function getValidData($data) {
        $tem = 0;
        $valid = 0;
        $last_group = '';
        $fields = $this->getFieldsValidate();
        $group_fields = ['current_game_odds', 'opener_game_odds'];

        foreach ($group_fields as $group) {
            if (empty($data[$group]) || (!is_array($data[$group][0]))) continue;
            $tem = $this->validateFields($fields, $data[$group][0]);
            if ($tem > $valid) {
                $valid = $tem;
                $last_group = $group;
            }
        }
        
        return $data[$last_group][0];
    }

    public function validateFields($fields, $data) {
        $count = 0;

        if (is_array($fields) && count($fields) > 0) {
            foreach ($fields as $field => $validations) {
                if (in_array('required', $validations) && !isset($data[$field])) continue;
                if (in_array('notnull', $validations) && isset($data[$field]) && empty($data[$field])) continue;
                $count++;
            }
        }

        return $count;
    }

    public function setDataFormat($value, $sign = true) {
        if ($value === null) return null;
        if ($sign) {
            if (strpos($value, '-') === false) {
                $value = '+'.$value;
            }
        }

        if (strpos($value, '.') !== false) {
            $parts = explode('.', $value);
            $value = $parts[0].'½';
        }

        return $value;
    }

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

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-sport-betting-odds-title','slug' => 'color-sport-betting-odds-title','color' => '#ffffff'],
            ['name' => 'color-sport-betting-odds-title-bg','slug' => 'color-sport-betting-odds-title-bg','color' => '#0160ac'],
            ['name' => 'color-sport-betting-odds-headers','slug' => 'color-sport-betting-odds-headers','color' => '#DADCDE'],
            ['name' => 'color-sport-betting-odds-item-odd','slug' => 'color-sport-betting-odds-item-odd','color' => '#F6F7F8'],
            ['name' => 'color-sport-betting-odds-item-even','slug' => 'color-sport-betting-odds-item-even','color' => '#EBECEC'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-sport-betting-odds .odds .title',
                'fontSize' => '.9rem',
                'fontWeight' =>'600',
            ],
            [
                'customSelector' => '.rdg-sport-betting-odds .odd-item .team .name-team',
                'fontSize' => '.85rem',
                'fontWeight' =>'700',
            ],
            [
                'customSelector' => '.rdg-sport-betting-odds .odds .odds-headers .stats',
                'fontSize' => '.8rem',
                'fontWeight' =>'600',
            ],
            [
                'customSelector' => '.rdg-sport-betting-odds .odds .odds-list .stats',
                'fontSize' => '.8rem',
                'fontWeight' =>'600',
            ],
        ];
    }

    public function getShowCategories($category) {
        $categories = [];
        $new_cat = '';

        if (!empty($category) && function_exists('shMappingHierarchyFamily')) {
            $i = 0;
            $level = 0;
            $categories_parts = explode('-', $category);
            $categories_valid = $categories_parts;

            if (!strpos($category, '-')) {
                $children = shMappingHierarchyFamily($category);

                if (is_array($children) && count($children) > 0) {
                    // order alphabetically by value
                    asort($children);
                    
                    $categories[$i][] = ['id' => 0,'class' => '', 'selected' => 0, 'value' => 'All sub-categories'];
                    foreach ($children as $key => $child) {
                        $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                        $categories[$i][] = ['id' => $category.'-'.$key,'class' => $class, 'selected' => 0, 'value' => $child];
                    }
                }

                return $categories;
            }

            if (is_array($categories_parts) && count($categories_parts) > 0) {
                foreach ($categories_valid as $part) {
                    if (empty($new_cat)) {
                        $new_cat = $part;
                    } else {
                        $new_cat .= '-'.$part;
                    }

                    if (isset($categories_parts[$level + 1])) {
                        $option_selected = $new_cat.'-'.$categories_parts[$level + 1];
                    }

                    $level++;

                    $children = shMappingHierarchyFamily($new_cat);
                    if (is_array($children) && count($children) > 0) {
                        // order alphabetically by value
                        asort($children);
                        
                        $categories[$i][] = ['id' => 0,'class' => '', 'selected' => 0, 'value' => 'All sub-categories'];
                        foreach ($children as $key => $child) {
                            $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                            $selected = ($new_cat.'-'.str_replace('-child', '', $key) == $option_selected) ? 1 : 0;
                            $categories[$i][] = ['id' => $new_cat.'-'.$key,'class' => $class, 'selected' => $selected, 'value' => $child];
                        }
                    }

                    $i++;
                }
            }
        }
        
        return $categories;
    }
}

add_action('wp_ajax_nopriv_load_sport_betting_odds_options','getSportBettingOddsOptions');
add_action('wp_ajax_load_sport_betting_odds_options','getSportBettingOddsOptions');

function getSportBettingOddsOptions() {
    $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();
}

// LEGACY: AJAX handler for old dynamic categories system (sport_betting_odds_sports_categories field)
// Kept for backward compatibility with existing saved blocks that still use the old field structure
add_action('wp_ajax_nopriv_load_ajax_sports_family','sport_betting_odds_sports_family');
add_action('wp_ajax_load_ajax_sports_family','sport_betting_odds_sports_family');

function sport_betting_odds_sports_family() {
    $sport = $_POST['sport'];
    $categories = [];

    if (!empty($sport) && function_exists('shMappingHierarchyFamily')) {
        $sport = (strpos($sport, '-child')) ? str_replace('-child', '', $sport) : $sport;
        
        // Try with direct ID first
        $children = shMappingHierarchyFamily($sport);
        
        // If no results, try with "G" prefix
        if (empty($children) || !is_array($children) || count($children) == 0) {
            $sport_with_prefix = 'G' . $sport;
            $children = shMappingHierarchyFamily($sport_with_prefix);
        }

        if (is_array($children) && count($children) > 0) {
            // order alphabetically by value
            asort($children);
            
            $categories[] = ['id' => 0, 'class' => '', 'value' => 'All sub-categories'];
            foreach ($children as $key => $child) {
                $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                $categories[] = ['id' => $sport.'-'.$key,'class' => $class, 'value' => $child];
            }
        }
    }
    
    echo json_encode($categories);

    wp_die();
}

// LEGACY: AJAX handler to restore saved categories on page load for old blocks
// Kept for backward compatibility with existing saved blocks that still use the old field structure
add_action('wp_ajax_nopriv_load_categories_hierarchy','sportBettingOddsCategoriesHierarchy');
add_action('wp_ajax_load_categories_hierarchy','sportBettingOddsCategoriesHierarchy');

function sportBettingOddsCategoriesHierarchy() {
    $sport = $_POST['sport'];
    $categories = $_POST['categories'];
    $block_id = $_POST['block_id'];

    $rdg_betting_odds = new Rdg_Blocks_Sport_Betting_Odds();
    $categories_array = $rdg_betting_odds->getShowCategories($categories);
    $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

    if (!is_array($categories_array) || (is_array($categories_array) && count($categories_array) == 0)) {
        $categories_array = $rdg_betting_odds->getShowCategories($sport);
    }

    $i = 1;
    $selects = '';
    $categories_name[$i] = $sports[$sport];

    foreach ($categories_array as $category) {
        $sport = $categories_name[$i];

        $selects .= "<div id='category-$i' class='acf-field acf-field-select acf-field-key-category-item-$i category-item' data-name='category-item-$i' data-type='select' data-key='key-category-item-$i' data-level='$i' data-parent-id='#parentID'>";
        $selects .= "<div class='acf-label'>";
        $selects .= "<label for='acf-#blockID-key_sport_betting_odds_sports_categories-key-category-item-$i'>Category: ".trim($sport)."</label>";
        $selects .= "</div>";
        $selects .= "<div class='acf-input'>";
        $selects .= "<select id='acf-#blockID-key_sport_betting_odds_sports_categories-key-category-item-$i' name='acf-#blockID-[key_sport_betting_odds_sports_categories][key-category-item-$i]' data-ui='0' data-ajax='0' data-multiple='0' data-placeholder='Select' data-allow_null='0' data-dashlane-classification='date,day'>";

        $parent_id = '';
        foreach ($category as $cat_field) {
            if ($cat_field['selected'] == 1) {
                $selects .= "<option value='".$cat_field['id']."' selected='selected'>".$cat_field['value']."</option>";
                $categories_name[$i + 1] = $cat_field['value'];
                
                $tem_parent = explode('-', str_replace('-child', '', $cat_field['id']));
                unset($tem_parent[count($tem_parent) - 1]);
                $parent_id = implode('-', $tem_parent);
            } else {
                $selects .= "<option value='".$cat_field['id']."'>".$cat_field['value']."</option>";
            }
        }

        $selects = str_replace('#parentID', $parent_id, $selects);
        $selects = str_replace('#blockID', $block_id, $selects);
        $selects .= "</select>";
        $selects .= "</div>";
        $selects .= "</div>";

        $i++;
    }

    echo $selects;

    wp_die();
}

$rdg_sport_betting_odds_class = new Rdg_Blocks_Sport_Betting_Odds();
$rdg_sport_betting_odds_class->init();

return $rdg_sport_betting_odds_class;
