<?php

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

class Rdg_Blocks_Sports_Picks extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_SPORTS_PICKS;
    private $block_folder_name = 'rdg-sports-picks';
    protected $block_title = 'RDG Sports Picks';
    private $block_description = 'The block is a dynamic form to display the info for sports picks, it is possible to edit if the info comes from an API or in manual form, the category and number of items';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sport', 'pick', '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 Sports Picks';
    protected $config_menu_title = 'Sports Picks';
    protected $interval_field = 'sports_picks_interval';

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

    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_sports_picks.css'),
                'enqueue_script' => RDGBLOCKS_PLUGIN_URL . 'blocks/'.$this->block_folder_name.'/assets/js/rdg-sports-picks.js',
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-sport-picks-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() : [];

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_sports_picks_block_adadasd',
                'title' => 'Block_rdg_sports_picks',
                'fields' => array(
                    array(
                        'key' => 'field_64baa30e118cc',
                        '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_64baa30e15438',
                        '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,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'field_64baa737d752a',
                        'label' => 'Link Options',
                        'name' => 'link_options',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        '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_64baa79dd752b',
                        'label' => 'Link',
                        'name' => 'custom_link',
                        'aria-label' => '',
                        'type' => 'link',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa737d752a',
                                    'operator' => '==',
                                    'value' => 'custom',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                    ),
                    array(
                        'key' => 'field_64baa30e18ffd',
                        'label' => 'Picks',
                        'name' => 'picks',
                        'aria-label' => '',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    '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_64baa30e338d8',
                                'label' => 'Title',
                                'name' => 'title',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e37313',
                                '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_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e3adc0',
                                '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_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e3eae5',
                                '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_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e425dd',
                                'label' => 'Vs',
                                'name' => 'vs',
                                'aria-label' => '',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e45ef2',
                                '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_64baa30e60992',
                                        '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_64baa30e45ef2',
                                    ),
                                    array(
                                        'key' => 'field_64baa30e64627',
                                        '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_64baa30e45ef2',
                                    ),
                                ),
                                'parent_repeater' => 'field_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e49a70',
                                'label' => 'Ranking',
                                'name' => 'ranking',
                                'aria-label' => '',
                                'type' => 'repeater',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'layout' => 'block',
                                'min' => 0,
                                'max' => 0,
                                'collapsed' => '',
                                'button_label' => 'Add Row',
                                'rows_per_page' => 20,
                                'sub_fields' => array(
                                    array(
                                        'key' => 'field_64baa30e6fb20',
                                        'label' => 'Value',
                                        'name' => 'value',
                                        'aria-label' => '',
                                        'type' => 'text',
                                        'instructions' => '',
                                        'required' => 1,
                                        'conditional_logic' => 0,
                                        'wrapper' => array(
                                            'width' => '',
                                            'class' => '',
                                            'id' => '',
                                        ),
                                        'default_value' => '',
                                        'maxlength' => '',
                                        'placeholder' => '',
                                        'prepend' => '',
                                        'append' => '',
                                        'parent_repeater' => 'field_64baa30e49a70',
                                    ),
                                ),
                                'parent_repeater' => 'field_64baa30e18ffd',
                            ),
                            array(
                                'key' => 'field_64baa30e4d5c8',
                                'label' => 'Link',
                                'name' => 'link',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'parent_repeater' => 'field_64baa30e18ffd',
                            ),
                        ),
                    ),
                    // DEV-853: Old Category field hidden - now using Sport + League fields
                    // Keeping for backward compatibility with existing posts
                    array(
                        'key' => 'field_64baa30e1cae3',
                        'label' => 'Category (deprecated)',
                        'name' => 'category',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    'operator' => '==',
                                    'value' => 'never_show_this_field', // Hidden: replaced by Sport + League
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => 'hidden',
                            'id' => '',
                        ),
                        'choices' => [0 => 'Choose an option'] + $sports,
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_64baa30e241a9',
                        'label' => 'Number of Items',
                        'name' => 'number_of_items',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => 1,
                        'max' => 20,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_64baa30e27bfe',
                        'label' => 'Links',
                        'name' => 'links',
                        '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_64baa30e86c7d',
                                'label' => 'Link',
                                'name' => 'link',
                                'aria-label' => '',
                                'type' => 'link',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'return_format' => 'array',
                                'parent_repeater' => 'field_64baa30e27bfe',
                            ),
                            array(
                                'key' => 'field_64baa30e8a732',
                                'label' => 'Default Styles',
                                'name' => 'default_styles',
                                'aria-label' => '',
                                'type' => 'select',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'choices' => array(
                                    'link-success' => 'Success',
                                    'link-warning' => 'Warning',
                                    'link-danger' => 'Danger',
                                    'link-default' => 'Default',
                                    'custom' => 'Custom',
                                ),
                                'default_value' => 'link-success',
                                'return_format' => 'value',
                                'multiple' => 0,
                                'allow_null' => 0,
                                'ui' => 0,
                                'ajax' => 0,
                                'placeholder' => '',
                                'parent_repeater' => 'field_64baa30e27bfe',
                            ),
                            array(
                                'key' => 'field_64baa30e8e05c',
                                'label' => 'Background color',
                                'name' => 'background_color',
                                'aria-label' => '',
                                'type' => 'color_picker',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_64baa30e8a732',
                                            'operator' => '==',
                                            'value' => 'custom',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'enable_opacity' => 0,
                                'return_format' => 'string',
                                'parent_repeater' => 'field_64baa30e27bfe',
                            ),
                            array(
                                'key' => 'field_64baa30e91ad8',
                                'label' => 'Background Hover Color',
                                'name' => 'background_hover_color',
                                'aria-label' => '',
                                'type' => 'color_picker',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_64baa30e8a732',
                                            'operator' => '==',
                                            'value' => 'custom',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'enable_opacity' => 0,
                                'return_format' => 'string',
                                'parent_repeater' => 'field_64baa30e27bfe',
                            ),
                            array(
                                'key' => 'field_64baa30e954cf',
                                'label' => 'Text color',
                                'name' => 'text_color',
                                'aria-label' => '',
                                'type' => 'color_picker',
                                'instructions' => '',
                                'required' => 1,
                                'conditional_logic' => array(
                                    array(
                                        array(
                                            'field' => 'field_64baa30e8a732',
                                            'operator' => '==',
                                            'value' => 'custom',
                                        ),
                                    ),
                                ),
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'enable_opacity' => 0,
                                'return_format' => 'string',
                                'parent_repeater' => 'field_64baa30e27bfe',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_sports_picks_sport',
                        'label' => 'Sport',
                        'name' => 'sports_picks_sport',
                        'type' => 'select',
                        'choices' => [0 => 'Choose an option'] + $sports,
                        'required' => 0, // Sport is not strictly required, as league is the final parameter
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => false,
                        'allow_null' => 0,
                        'multiple' => 0,
                        'ui' => 0,
                        'return_format' => 'value',
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'field_sports_picks_league',
                        'label' => 'League',
                        'name' => 'sports_picks_league',
                        'type' => 'select',
                        'choices' => [0 => 'Choose an option'],
                        'required' => 1, // League is now required
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'field_64baa30e15438',
                                    'operator' => '==',
                                    'value' => 'api',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '50',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => false,
                        'allow_null' => 0,
                        'multiple' => 0,
                        'ui' => 0,
                        'return_format' => 'value',
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-sports-picks',
                        ),
                    ),
                ),
                '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_sports_picks_block_sdfw34fs2332',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'sports_picks_field_6dfwd232323es3e',
                        'label' => 'URL',
                        'name' => 'sports_picks_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' => 'sports_picks_field_2d3e23e3de32e',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'sports_picks_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' => 'sports_picks_field_62d3e23e23e32e',
                        'label' => 'Token',
                        'name' => 'sports_picks_api_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-sports-picks',
                        ),
                    ),
                ),
                '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['name'] != 'sports_picks_league') {
            return $field;
        }

        $sport = $_POST['_ajax_nonce-acf'] ?? null;
        
        if (!empty($sport)) {
            global $post;
            $post_id = $_POST['post_id'] ?? 0;
            
            if (is_numeric($post_id)) {
                $sport_value = get_post_meta($post_id, 'sports_picks_sport', true);
                
                if (!empty($sport_value)) {
                    $leagues = (function_exists('shMappingHierarchyFamily'))
                        ? shMappingHierarchyFamily($sport_value)
                        : [];
                    
                    $field['choices'] = [0 => 'Choose an option'] + $leagues;
                }
            }
        }
        
        return $field;
    }

    public function getSportsPicksOptions() {
        $sport = $_POST['sport'] ?? '';
        
        if (empty($sport)) {
            wp_send_json_error('No sport selected');
            return;
        }
        
        $leagues = (function_exists('shMappingHierarchyFamily'))
            ? shMappingHierarchyFamily($sport)
            : [];
        
        wp_send_json_success(['leagues' => $leagues]);
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('sports_picks_api_url', 'option');
        $api_token = get_field('sports_picks_api_token', 'option');
        $cache_refresh = get_field('sports_picks_interval', 'option');
        $items = (!empty($items)) ? intval($items) : 10;

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

        // DEV-853: Use league field for hierarchy parameter (after sh-mapping fix, league ID is correct level 2 group ID)
        $hierarchy_id = null;

        // Try new league field first
        if (isset($attributes['league']) && !empty($attributes['league'])) {
            preg_match('/\d+/', $attributes['league'], $match);
            $hierarchy_id = $match[0] ?? null;
        }
        // Backward compatibility: try old category field
        else if (isset($attributes['category']) && !empty($attributes['category'])) {
            if (strpos($attributes['category'], '-')) {
                list($hierarchy_id, $sub_category) = explode('-', $attributes['category']);
            } else {
                $hierarchy_id = $attributes['category'];
            }
        }

        // League selection is required - return null if missing
        if (empty($hierarchy_id)) {
            return null;
        }

        $hierarchy_clean = preg_replace('/\D/', '', $hierarchy_id);
        $api_url .= '&hierarchy='.$hierarchy_clean;

        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' => $items,
            'method' => 'GET',
            'cache_refresh' => $cache_refresh,
            'headers' => ['Accept: application/json'],
            'request' => $api_request,
            'category_primary' => $hierarchy_id, // Backward compatibility
            'sub_category' => $sub_category,
        ];
    }

    public function getApiParams() {
        return [
            'sport' => 'sports_picks_sport',
            'league' => 'sports_picks_league',
            'category' => 'category' // Backward compatibility
        ];
    }

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

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

    public function 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 [
            //'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-rdg-sports-picks-title-bg','slug' => 'color-rdg-sports-picks-title-bg','color' => '#0160ac'],
            ['name' => 'color-rdg-sports-picks-title-border','slug' => 'color-rdg-sports-picks-title-border','color' => '#3a96e0'],
            ['name' => 'color-rdg-sports-picks-vs-name','slug' => 'color-rdg-sports-picks-vs-name','color' => '#0160ac'],
            ['name' => 'color-rdg-sports-picks-vs-logo','slug' => 'color-rdg-sports-picks-vs-logo','color' => '#0160ac'],
        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-sports-picks .pick-header .content .sport',
                'fontWeight' =>'bold',
                'textTransform' => 'uppercase',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .pick-header .content .status',
                'fontWeight' =>'bold',
                'textTransform' => 'uppercase',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .pick-header .content .date-time',
                'textTransform' => 'uppercase',
                'fontSize' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .pick-body .teams .team-name',
                'fontWeight' =>'bold',
                'textTransform' => 'uppercase',
                'fontSize' => '0.8rem',
                'fontSizeMobile' => '0.9rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .pick-body .numbers .number',
                'fontWeight' =>'600',
                'fontSize' => '1.1rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .picks .pick .pick-body .teams .team-vs .vs-logo span',
                'fontWeight' =>'500',
                'fontSize' => '1.1rem',
            ],
            [
                'customSelector' => '.rdg-sports-picks .picks .pick .pick-body .teams .team-vs .vs-name span',
                'fontWeight' =>'600',
                'fontSize' => '0.9rem',
                'textTransform' => 'uppercase',
            ],
            [
                'customSelector' => '.rdg-sports-picks .picks .pick .pick-footer a',
                'fontWeight' =>'600',
            ],
            [
                'customSelector' => '.rdg-sports-picks .buttons a',
                'fontWeight' =>'500',
                'fontSize' => '1rem',
            ],
        ];
    }
}

$rdg_sports_picks_class = new Rdg_Blocks_Sports_Picks();
$rdg_sports_picks_class->init();

return $rdg_sports_picks_class;
