<?php

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

class Rdg_Blocks_Picks_Vs_Multi extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_PICKS_VS_MULTI;
    private $block_folder_name = 'rdg-picks-vs-multi';
    protected $block_title = 'RDG Picks Vs Multi';
    private $block_description = 'This block allow to create a 3 columns table with teams pick but with multi categories';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sports', 'picks', '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 Multi';
    protected $config_menu_title = 'Picks Vs Multi';
    protected $interval_field = 'picks_vs_multi_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_multi.css'),
                'enqueue_assets' => function(){
                    wp_register_script('rdg_picks_vs_multi_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-picks-vs-multi/assets/js/rdg-picks-vs-multi.js', array('jquery'), '1.0.0', true);
                    wp_enqueue_script('rdg_picks_vs_multi_script');
                    wp_localize_script('rdg_picks_vs_multi_script','rdg_picks_vs_multi_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-multi-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() {
        $rdg_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' => 'group_rdg_picks_vs_multi_block',
                'title' => 'Block_rdg_picks_vs_multi',
                'fields' => array(
                    array(
                        'key' => 'rdg_picks_vs_multi_source',
                        'label' => 'Source',
                        'name' => 'source',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'manual' => 'Manual',
                            'api' => 'API',
                        ),
                        'default_value' => 'manual',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'save_other_choice' => 0,
                        'layout' => 'horizontal',
                    ),                   
                    array(
                        'key' => 'field_63cc527c9d04e',
                        'label' => 'Picks',
                        'name' => 'picks',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'manual',
                                ),
                            ),
                        ),
                        '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_63cc527cbe269',
                                'label' => 'Category',
                                'name' => 'category',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cc1bba',
                                'label' => 'Time',
                                'name' => 'time',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cc584e',
                                'label' => 'Status',
                                'name' => 'status',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_63cc527cccd29',
                                'label' => 'Teams',
                                'name' => 'teams',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'block',
                                'pagination' => 0,
                                'min' => 0,
                                'max' => 2,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_63cc527ce34ba',
                                        'label' => 'Logo',
                                        'name' => 'logo',
                                        'aria-label' => '',
                                        'type' => 'image',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'return_format' => 'array',
                                        'library' => 'all',
                                        'min_width' => '',
                                        'min_height' => '',
                                        'min_size' => '',
                                        'max_width' => '',
                                        'max_height' => '',
                                        'max_size' => '',
                                        'mime_types' => '',
                                        'preview_size' => 'medium',
                                        'parent_repeater' => 'field_63cc527cccd29',
                                    ),
                                    array(
                                        'key' => 'field_63cc527ce6f33',
                                        'label' => 'Name',
                                        'name' => 'name',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_63cc527cccd29',
                                    ),
                                ),
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                            array(
                                'key' => 'field_67f7d58aff741',
                                'label' => 'Picks Availables',
                                'name' => 'picks_availables',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'allow_in_bindings' => 0,
                                'parent_repeater' => 'field_63cc527c9d04e',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'rdg_picks_vs_multi_picks_sports',
                        'label' => 'Sports',
                        'name' => 'sports',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        '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_multi_sport',
                                'label' => 'Sport',
                                'name' => 'sport',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    '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' => 'rdg_picks_vs_multi_picks_sports',
                            ),
                            array(
                                'key' => 'field_picks_vs_multi_league',
                                'label' => 'League',
                                'name' => 'league',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => 'rdg-picks-vs-multi-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' => 'rdg_picks_vs_multi_picks_sports',
                            ),
                            array(
                                'key' => 'field_quantity',
                                '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' => 'rdg_picks_vs_multi_picks_sports',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_63dbbff733345',
                        'label' => 'Filter Date',
                        'name' => 'filter_date',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'rdg_picks_vs_multi_source',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        '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_63e6b06bc7010',
                        'label' => 'Date Type',
                        'name' => 'date_type',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63dbbff733345',
                                    '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_63e6af4c50608',
                        'label' => 'Since Date',
                        'name' => 'since_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63e6b06bc7010',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                    array(
                        'key' => 'field_63e6afb550609',
                        'label' => 'To Date',
                        'name' => 'to_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_63e6b06bc7010',
                                    'operator' => '==',
                                    'value' => 'range',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-picks-vs-multi',
                        ),
                    ),
                ),
                '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_multi_block',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'field_63d9b555d0be',
                        'label' => 'URL',
                        'name' => 'picks_vs_multi_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_63d9b987c0adf',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'picks_vs_multi_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_63d9b987c4506',
                        'label' => 'Token',
                        'name' => 'picks_vs_multi_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-multi',
                        ),
                    ),
                ),
                '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_multi_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['rdg_picks_vs_multi_picks_sports']) && is_array($block_values['rdg_picks_vs_multi_picks_sports'])) {
                    foreach ($block_values['rdg_picks_vs_multi_picks_sports'] as $row_key => $row_values) {
                        // Check if this row has a league value matching the current field
                        if (isset($row_values['field_picks_vs_multi_league']) && $row_values['field_picks_vs_multi_league'] == $field['value']) {
                            // Found matching row, get sport from it
                            if (isset($row_values['field_picks_vs_multi_sport']) && !empty($row_values['field_picks_vs_multi_sport'])) {
                                $sport_value = $row_values['field_picks_vs_multi_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_multi_api_url', 'option');
        $api_token = get_field('picks_vs_multi_api_token', 'option');
        $cache_refresh = get_field('picks_vs_multi_interval', 'option');
        $items = (!empty($items)) ? intval($items) : 10;
        
        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $categories_params = $this->getSportsCategoriesParams($attributes);

        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;

        // Extract hierarchies for logging/debugging purposes
        $hierarchies = [];
        if (isset($attributes['sports']) && is_array($attributes['sports'])) {
            foreach($attributes['sports'] as $sport) {
                if (isset($sport['league']) && !empty($sport['league'])) {
                    $hierarchies[] = preg_replace('/\D/', '', $sport['league']);
                } elseif (isset($sport['category']) && !empty($sport['category'])) {
                    // Backward compatibility
                    $hierarchy_id = strpos($sport['category'], '-') !== false 
                        ? explode('-', $sport['category'])[0] 
                        : $sport['category'];
                    $hierarchies[] = preg_replace('/\D/', '', $hierarchy_id);
                }
            }
        }

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

    public function getSportsCategoriesParams($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) {
            $hierarchy_id = null;

            // New structure: using 'league' field (contains hierarchy ID)
            if (isset($sport['league']) && !empty($sport['league'])) {
                $hierarchy_id = $sport['league'];
                $items_param = (isset($sport['number_of_items']) && !empty($sport['number_of_items'])) ? intval($sport['number_of_items']) : 1;
                
                // Clean hierarchy ID (remove any non-numeric characters)
                $hierarchy_clean = preg_replace('/\D/', '', $hierarchy_id);
                
                if (!empty($hierarchy_clean)) {
                    $hierarchies[] = $hierarchy_clean;
                    $qty_per_sport[] = $items_param;
                }
            }
            // Backward compatibility: support old 'category' field
            elseif (isset($sport['category']) && !empty($sport['category'])) {
                $items_param = (isset($sport['number_of_items']) && !empty($sport['number_of_items'])) ? intval($sport['number_of_items']) : 1;
                
                if (strpos($sport['category'], '-')) {
                    list($sport_param, $category_param) = explode('-', $sport['category']);
                    $hierarchy_id = $sport_param;
                } else {
                    $hierarchy_id = $sport['category'];
                }
                
                $hierarchy_clean = preg_replace('/\D/', '', $hierarchy_id);
                
                if (!empty($hierarchy_clean)) {
                    $hierarchies[] = $hierarchy_clean;
                    $qty_per_sport[] = $items_param;
                }
            }
        }

        if (count($hierarchies) == 0 || count($hierarchies) != count($qty_per_sport)) {
            return null;
        }
        
        $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', 'category', 'number_of_items'], // Added sport, league; kept category for backward compatibility
            ]
        ];
    }

    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 getFieldsValidate() {
        return [
            'sport_name' => ['required', 'notnull'],
            'game_date' => ['required', 'notnull'],
            'visitor_name' => ['required', 'notnull'],
            'home_name' => ['required', 'notnull'],
            'game_stat' => ['required', 'notnull'],
            'num_picks' => ['required', 'notnull'],
            'game_url' => ['required', 'notnull'],
            'visitor_image' => ['required', 'notnull'],
            'home_image' => ['required', 'notnull'],
        ];
    }
    
    public function getPreSavedData($data, $attributes = [])
    {
        return $data;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-rdg-pvm-bg','slug' => 'color-rdg-pvm-bg','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-vs-bg','slug' => 'color-rdg-pvm-vs-bg','color' => '#0160ac'],
            ['name' => 'color-rdg-pvm-vs-p','slug' => 'color-rdg-pvm-vs-p','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-btn-bg','slug' => 'color-rdg-pvm-btn-bg','color' => '#0160ac'],
            ['name' => 'color-rdg-pvm-btn-p','slug' => 'color-rdg-pvm-btn-p','color' => '#FFFFFF'],
            ['name' => 'color-rdg-pvm-btn-hover','slug' => 'color-rdg-pvm-btn-hover','color' => '#014f8c'],
            
        ]; 
    }

    public function getStylesToloadGeneratePress() {
        return [
        ];
    }
}

add_action('wp_ajax_nopriv_load_picks_vs_multi_options','getPicksVsMultiOptions');
add_action('wp_ajax_load_picks_vs_multi_options','getPicksVsMultiOptions');

function getPicksVsMultiOptions() {
    $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_picks_vs_multi_class = new Rdg_Blocks_Picks_Vs_Multi();
$rdg_picks_vs_multi_class->init();

return $rdg_picks_vs_multi_class;
