<?php

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

class Rdg_Blocks_Picks_Vs_Categories extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_PICKS_VS_CATEGORIES;
    private $block_folder_name = 'rdg-picks-vs-categories';
    protected $block_title = 'RDG Picks Vs Categories';
    private $block_description = 'This block allow to create a 3 columns table with multiple picks categorized by sport or sport categories';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sports', 'picks', 'category', 'categories', '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 Picks Vs Categories';
    protected $config_menu_title = 'Picks Vs Categories';
    protected $interval_field = 'picks_vs_categories_interval';

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

    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_picks_vs_categories.css'),
                'enqueue_assets' => function(){
                    wp_register_script('rdg_picks_vs_categories_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-picks-vs-categories/assets/js/rdg-picks-vs-categories.js', array('jquery'), '1.0.0', true);
                    wp_enqueue_script('rdg_picks_vs_categories_script');
                    wp_localize_script('rdg_picks_vs_categories_script','rdg_picks_vs_categories_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-picks-vs-categori-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() {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];
        
        add_filter('acf/prepare_field', [$this, 'loadLeagues']);

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'block_rdg_picks_vs_category_group_64b04a8884b9d',
                'title' => 'Block RDG Picks Vs Category',
                'fields' => array(
                    array(
                        'key' => 'field_64b04a888fa07',
                        'label' => 'Show In',
                        'name' => 'show_in',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'full' => 'Full width',
                            'content' => 'Content width',
                        ),
                        'default_value' => 'full',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a88936a4',
                        'label' => 'Link Options',
                        'name' => 'link_options',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'none' => 'None',
                            'default' => 'API',
                            'custom' => 'Custom',
                        ),
                        'default_value' => 'none',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a8897166',
                        'label' => 'Link',
                        'name' => 'custom_link',
                        'aria-label' => '',
                        'type' => 'link',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88936a4',
                                    'operator' => '==',
                                    'value' => 'custom',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                    ),
                    array(
                        'key' => 'field_64b04a88ad2ff',
                        'label' => 'Filter Date',
                        'name' => 'filter_date',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'hide' => 'Hide',
                            'show' => 'Show',
                        ),
                        'default_value' => 'hide',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64b04a88b0fac',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88ad2ff',
                                    'operator' => '==',
                                    'value' => 'show',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'yesterday' => 'Yesterday',
                            'now' => 'Now',
                            'tomorrow' => 'Tomorrow',
                            'range' => 'Range',
                        ),
                        'default_value' => 'now',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64b04a88b4a24',
                        'label' => 'Since Date',
                        'name' => 'since_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88b0fac',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_64b04a88b84ca',
                        'label' => 'To Date',
                        'name' => 'to_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64b04a88b0fac',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_64bebc7f85434',
                        'label' => 'Heading',
                        'name' => 'category_heading',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'h1' => 'Heading H1',
                            'h2' => 'Heading H2',
                            'h3' => 'Heading H3',
                            'span' => 'Heading Span',
                        ),
                        'default_value' => 'h1',
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64b1daa829050',
                        'label' => 'Sports',
                        'name' => 'sports',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        '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' => 'field_picks_vs_categories_sport',
                                'label' => 'Sport',
                                'name' => 'sport',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => 'rdg-picks-vs-categories-sport-select',
                                    'id' => '',
                                ),
                                'choices' => [0 => 'Choose an option'] + $sports,
                                'default_value' => false,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_64b1daa829050',
                            ),
                            array(
                                'key' => 'field_picks_vs_categories_league',
                                'label' => 'League',
                                'name' => 'league',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => 'rdg-picks-vs-categories-league-select',
                                    'id' => '',
                                ),
                                'choices' => ['0' => 'Choose an option'],
                                'default_value' => false,
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_64b1daa829050',
                            ),
                            array(
                                'key' => 'field_64b04a88a9820',
                                'label' => 'Number of Items',
                                'name' => 'number_of_items',
                                'aria-label' => '',
                                'type' => 'number',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => 3,
                                'min' => 0,
                                'max' => '',
                                'placeholder' => '',
                                'step' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64b1daa829050',
                            ),
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-categories',
                        ),
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-categories',
                        ),
                    ),
                ),
                '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_picks_vs_categories_block_sdfweewrrwrwr2',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_63d9b9werrwer',
                        'label' => 'URL',
                        'name' => 'picks_vs_categories_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' => 'field_6werwffwssdfsf',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'picks_vs_categories_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' => 'field_dfggdgdfdgfdsdsfg',
                        'label' => 'Token',
                        'name' => 'picks_vs_categories_api_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '100',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-picks-vs-categories',
                        ),
                    ),
                ),
                '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'] != 'field_picks_vs_categories_league') {
            return $field;
        }
        
        // Default choices
        $field['choices'] = ['0' => 'Choose an option'];
        
        // Strategy 1: Try to get sport value from the field's stored value
        // If the league already has a value, we can determine the sport from it
        if (!empty($field['value'])) {
            // The league value contains hierarchy ID
            $saved_value = $field['value'];
            
            // Try to get the sport that contains this hierarchy
            if (function_exists('shMappingHierarchySports')) {
                $all_sports = shMappingHierarchySports();
                
                // Find which sport this league belongs to by checking if the saved value exists in leagues
                foreach ($all_sports as $sport_id => $sport_name) {
                    if (function_exists('shMappingHierarchyFamily')) {
                        $leagues = shMappingHierarchyFamily($sport_id);
                        if (is_array($leagues) && isset($leagues[$saved_value])) {
                            // Found the correct sport, load its leagues
                            $field['choices'] = ['0' => 'Choose an option'] + $leagues;
                            return $field;
                        }
                    }
                }
            }
        }
        
        // Strategy 2: Check POST data for sport value in the same repeater row
        if (isset($_POST['acf']) && is_array($_POST['acf'])) {
            foreach ($_POST['acf'] as $block_key => $block_values) {
                if (isset($block_values['field_64b1daa829050']) && is_array($block_values['field_64b1daa829050'])) {
                    foreach ($block_values['field_64b1daa829050'] as $row_key => $row_values) {
                        // Check if this row has a league value matching the current field
                        if (isset($row_values['field_picks_vs_categories_league']) && $row_values['field_picks_vs_categories_league'] == $field['value']) {
                            // Found matching row, get sport from it
                            if (isset($row_values['field_picks_vs_categories_sport']) && !empty($row_values['field_picks_vs_categories_sport'])) {
                                $sport_value = $row_values['field_picks_vs_categories_sport'];
                                
                                if (function_exists('shMappingHierarchyFamily')) {
                                    $leagues = shMappingHierarchyFamily($sport_value);
                                    if (is_array($leagues) && count($leagues) > 0) {
                                        $field['choices'] = ['0' => 'Choose an option'] + $leagues;
                                        return $field;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // Strategy 3: Load all possible leagues if we can't determine the specific sport
        // This ensures that saved values are still visible even after page refresh
        if (!empty($field['value']) && function_exists('shMappingHierarchySports')) {
            $all_sports = shMappingHierarchySports();
            $all_leagues = [];
            
            foreach ($all_sports as $sport_id => $sport_name) {
                if (function_exists('shMappingHierarchyFamily')) {
                    $leagues = shMappingHierarchyFamily($sport_id);
                    if (is_array($leagues)) {
                        $all_leagues = $all_leagues + $leagues;
                    }
                }
            }
            
            if (count($all_leagues) > 0) {
                $field['choices'] = ['0' => 'Choose an option'] + $all_leagues;
            }
        }
        
        return $field;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('picks_vs_categories_api_url', 'option');
        $api_token = get_field('picks_vs_categories_api_token', 'option');
        $cache_refresh = get_field('picks_vs_categories_interval', 'option');

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        
        $categories_params = $this->get_sports_categories_url_params($attributes);
        
        error_log('DEBUG - categories_params: ' . $categories_params);
        error_log('DEBUG - Full API URL: ' . $api_url . '?' . $categories_params);

        if (!empty($categories_params) ) {
            $api_url .= '?'.$categories_params;
        } else {
            $api_url .= '?';
        }

        if (isset($attributes['date']) && is_array($attributes['date']) && count($attributes['date']) == 2) {
            if (!empty($attributes['date']['start'])) {
                $api_url .= '&principalDate='.$attributes['date']['start'];
            }
            
            if (!empty($attributes['date']['end'])) {
                $api_url .= '&secondaryDate='.$attributes['date']['end'];
            }
        }

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

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

    public function get_sports_categories_url_params($attributes) {
        if (!isset($attributes['sports']) || empty($attributes['sports']) || !is_array($attributes['sports']) || count($attributes['sports']) == 0) {
            return null;
        }

        $hierarchies = [];
        $qty_per_sport = [];

        foreach($attributes['sports'] as $sport_row) {
            $hierarchy_id = null;
            $items = (isset($sport_row['number_of_items']) && !empty($sport_row['number_of_items'])) ? intval($sport_row['number_of_items']) : 1;
            
            // Priority 1: If league is selected and valid → use league ID
            if (isset($sport_row['league']) && !empty($sport_row['league']) && $sport_row['league'] !== '0') {
                $hierarchy_id = $sport_row['league'];
            }
            // Priority 2: If NO league but sport is selected → use sport ID
            elseif (isset($sport_row['sport']) && !empty($sport_row['sport']) && $sport_row['sport'] !== '0') {
                $hierarchy_id = $sport_row['sport'];
            }
            // Priority 3: If neither league nor sport → skip this row
            else {
                continue;
            }
            
            // Clean hierarchy ID - remove non-numeric characters (e.g., L271 -> 271, G216 -> 216)
            $hierarchy_clean = preg_replace('/\D/', '', $hierarchy_id);
            
            if (!empty($hierarchy_clean)) {
                $hierarchies[] = $hierarchy_clean;
                $qty_per_sport[] = $items;
            }
        }

        if (count($hierarchies) == 0) {
            return null;
        }
        
        // API structure: hierarchy (league or sport IDs) and qtyPerSport parameters
        $params = [
            'hierarchy='.implode(',', $hierarchies),
            'qtyPerSport='.implode(',', $qty_per_sport),
        ];
        
        return implode('&', $params);
    }

    public function get_date_filter($date_type, $since_date, $to_date) {
        $date = [
            'start' => null,
            'end' => null
        ];

        if ($date_type == API_DATE_TYPE_YESTERDAY) {
            $date['start'] = date('Y-m-d', strtotime("-1 days"));

            return $date;
        }

        if ($date_type == API_DATE_TYPE_NOW) {

            return $date;
        }
        
        if ($date_type == API_DATE_TYPE_TOMORROW) {
            $date['start'] = date('Y-m-d',strtotime("+1 days"));
            
            return $date;
        }

        if ($date_type == API_DATE_TYPE_RANGE) {
            if (!empty($since_date) && !empty($to_date)) {
                $date['start'] = $since_date;
                $date['end'] = $to_date;
            
                return $date;
            }

            if (empty($since_date) && empty($to_date)) {
                return $date;
            }

            if (!empty($since_date) && empty($to_date)) {
                $date['start'] = $since_date;
            
                return $date;
            }

            if (empty($since_date) && !empty($to_date)) {
                $date['start'] = $to_date;
            
                return $date;
            }
        }

        return $date;
    }

    public function getApiParams() {
        return [
            'sports' => 'sports',
            '_to_transform_' => [
                [
                    'key' => 'date',
                    'function' => 'get_date_filter',
                    'params' => ['date_type', 'since_date', 'to_date'],
                    'fields_date' => ['since_date', 'to_date'],
                ]
            ],
            '_to_array_' => [
                'key' => 'sports',
                'fields' => ['sport', 'league', 'number_of_items'], // sport is now used as fallback when league is not selected
            ]
        ];
    }

    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_picks_vs_title_format($title) {
        if (strpos($title, '|') && is_array(explode(' | ', $title)) && count(explode(' | ', $title)) == 2) {
            $title_parts = explode(' | ', $title);
    
            return "<span style='color: var(--color-black); text-shadow: none;'>$title_parts[0] | </span> $title_parts[1]";
        }
        
        return "<span style='color: var(--color-black); text-shadow: none;'>$title</span>";
    }

    public function get_categories_sports($sports) {
        $sports_array = [];

        if (!empty($sports) && is_array($sports) && count($sports) > 0) {
            foreach ($sports as $sport_params) {
                $hierarchy_id = null;
                
                // Priority 1: Use league if available
                if (isset($sport_params['league']) && !empty($sport_params['league']) && $sport_params['league'] !== '0') {
                    $hierarchy_id = $sport_params['league'];
                }
                // Priority 2: Use sport if no league
                elseif (isset($sport_params['sport']) && !empty($sport_params['sport']) && $sport_params['sport'] !== '0') {
                    $hierarchy_id = $sport_params['sport'];
                }
                
                if ($hierarchy_id) {
                    // Clean hierarchy ID (L271 -> 271, G216 -> 216)
                    $hierarchy_clean = preg_replace('/\D/', '', $hierarchy_id);
                    // Map hierarchy ID to itself
                    $sports_array[$hierarchy_clean] = $hierarchy_clean;
                }
            }
        }

        return $sports_array;
    }

    public function getFieldsValidate() {
        return [
            //'id_game' => ['required'],
            //'id_sport' => ['required'],
            'sport_name' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            //'id_visitor_team' => ['required'],
            //'id_master_visitor_team' => ['required'],
            'visitor_name' => ['required', 'notnull'],
            //'id_home_team' => ['required'],
            //'id_master_home_team' => ['required'],
            'home_name' => ['required', 'notnull'],
            'game_stat' => ['required', 'notnull'],
            'num_picks' => ['required', 'notnull'],
            'game_url' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
            //'visitor_image_type' => ['required'],
            //'home_image_type' => ['required'],
        ];
    }

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

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-picks-vs-categories-pick-bg','slug' => 'color-picks-vs-categories-pick-bg','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-vs','slug' => 'color-picks-vs-categories-vs','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-vs-bg','slug' => 'color-picks-vs-categories-vs-bg','color' => '#0160ac'],
            ['name' => 'color-picks-vs-categories-name','slug' => 'color-picks-vs-categories-name','color' => '#FFFFFF'],
            ['name' => 'color-picks-vs-categories-name-bg','slug' => 'color-picks-vs-categories-name-bg','color' => '#0160ac'],
            ['name' => 'color-picks-vs-categories-sport','slug' => 'color-picks-vs-categories-sport','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-date','slug' => 'color-picks-vs-categories-date','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-status','slug' => 'color-picks-vs-categories-status','color' => '#111111'],
            ['name' => 'color-picks-vs-categories-team-name','slug' => 'color-picks-vs-categories-team-name','color' => '#111111'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .sport',
                'fontWeight' => '700',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .date-time',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-header .content .status',
                'fontWeight' => '700',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team .team-name',
                'fontWeight' => '700',
                'fontSize' => '0.8rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team-vs .vs-logo span',
                'fontWeight' => '500',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-picks-vs-categories .picks .pick .pick-body .teams .team-vs .vs-name span',
                'fontWeight' => '600',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
        ];
    }

    /**
     * Normalize API response to handle both old and new structures
     * 
     * Old structure: [...picks...]
     * New structure: {"277": [...picks...], "269": [...picks...]}
     * 
     * @param mixed $response_data The API response data
     * @param array $hierarchies Array of hierarchy IDs requested
     * @return array Normalized and grouped picks by hierarchy
     */
    private function normalizeApiResponse($response_data, $hierarchies = []) {
        // If response is already an array of picks ( old format )
        if (is_array($response_data) && isset($response_data[0])) {
            // Old format - group by id_sport for backward compatibility
            $grouped = [];
            foreach ($response_data as $pick) {
                $sport_id = $pick['id_sport'] ?? 'unknown';
                if (!isset($grouped[$sport_id])) {
                    $grouped[$sport_id] = [];
                }
                $grouped[$sport_id][] = $pick;
            }
            return $grouped;
        }
        
        // If response is object with hierarchy keys (new format)
        if (is_array($response_data) && !isset($response_data[0])) {
            // New format: {"277": [...picks...], "269": [...picks...]}
            // Already grouped by hierarchy, return as is
            return $response_data;
        }
        
        // Unknown format or empty response
        return [];
    }

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

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

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

        // Extract hierarchies from request for normalization
        $hierarchies = [];
        if (isset($request['request']) && strpos($request['request'], 'hierarchy=') !== false) {
            preg_match('/hierarchy=([^&]+)/', $request['request'], $matches);
            if (isset($matches[1])) {
                $hierarchies = explode(',', $matches[1]);
            }
        }

        // Normalize API response to handle new structure (hierarchy-keyed object)
        $data->json = $this->normalizeApiResponse($response->json, $hierarchies);

        return $data;
    }
}

add_action('wp_ajax_nopriv_load_picks_vs_categories_options','getPicksVsCategoriesOptions');
add_action('wp_ajax_load_picks_vs_categories_options','getPicksVsCategoriesOptions');

function getPicksVsCategoriesOptions() {
    $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'] = ['0' => 'Choose an option'] + $leagues;

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

$rdg_picks_vs_categories_class = new Rdg_Blocks_Picks_Vs_Categories();
$rdg_picks_vs_categories_class->init();

return $rdg_picks_vs_categories_class;
