<?php

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

class Rdg_Blocks_Sport_Betting_Odds extends Rdg_Blocks_Base implements Rdg_Blocks_Api_Request
{
    protected $block_name = BLOCK_RDG_SPORT_BETTING_ODDS;
    private $block_folder_name = BLOCK_RDG_SPORT_BETTING_ODDS;
    protected $block_title = 'RDG Sport Betting Odds';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'sport', 'betting', 'odd'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_caching = true;
    protected $is_config = true;
    protected $is_styles_load = true;
    protected $config_page_title = 'RDG Sport Betting Odds';
    protected $config_menu_title = 'Sport Betting Odds';

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

        add_filter('acf/load_value/name=sport_betting_odds_block_id', [$this, 'setUniqueBlockId'], 10, 3);
        add_filter('acf/load_field/name=sport_betting_odds_sports_categories', [$this, 'loadCategoriesHierarchy']);
        add_filter('acf/load_field/name=sport_betting_odds_category', [$this, 'setBlockId']);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
                'enqueue_style' => $rdg_helpers->webpack('rdg_sport_betting_odds.css'),
                'enqueue_assets' => function() {
                    wp_register_script('rdg_sport_betting_odds_script', RDGBLOCKS_PLUGIN_URL.'blocks/rdg-sport-betting-odds/assets/js/rdg-sport-betting-odds.js', array('jquery'), '1', true);
                    wp_enqueue_script('rdg_sport_betting_odds_script');
                    wp_localize_script('rdg_sport_betting_odds_script','rdg_sport_betting_odds_var',['ajaxurl' => admin_url('admin-ajax.php')]);
                    wp_localize_script('rdg_sport_betting_odds_script','rdg_blocks',['cache_dir' => CACHE_MAINTENANCE_FOLDER_URI]);
                },
                'supports' => [
                    'jsx' => true,
			        'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'group_rdg_sport_betting_odds',
                'title' => 'Block_rdg_sport_betting_odds',
                'fields' => array(
                    array(
                        'key' => 'key_sport_betting_odds_date_type',
                        'label' => 'Date type',
                        'name' => 'sport_betting_odds_date_type',
                        'aria-label' => '',
                        'type' => 'radio',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'auto' => 'Auto',
                            'custom' => 'Custom',
                        ),
                        'default_value' => 'auto',
                        'return_format' => 'value',
                        'allow_null' => 0,
                        'other_choice' => 0,
                        'layout' => 'horizontal',
                        'save_other_choice' => 0,
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_date',
                        'label' => 'Date',
                        'name' => 'sport_betting_odds_date',
                        'aria-label' => '',
                        'type' => 'date_picker',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => array(
                            array(
                                array(
                                    'field' => 'key_sport_betting_odds_date_type',
                                    'operator' => '==',
                                    'value' => 'custom',
                                ),
                            ),
                        ),
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'display_format' => 'Y-m-d',
                        'return_format' => 'Y-m-d',
                        'first_day' => 1,
                        'placeholder' => '',
                        'min_date' => '',
                        'max_date' => '',
                        'no_weekends' => 0,
                    ),
                    array(
                        'key' => 'field_64baa30e241a9',
                        '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' => 1,
                        'min' => 1,
                        'max' => 20,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_category',
                        'label' => 'Category',
                        'name' => 'sport_betting_odds_category',
                        'aria-label' => '',
                        'type' => 'acfe_hidden',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => 'sports_hierarchy_category',
                            'id' => 'sports_hierarchy_category',
                        ),
                        'default_value' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_block_id',
                        'label' => 'ID',
                        'name' => 'sport_betting_odds_block_id',
                        'aria-label' => '',
                        'type' => 'acfe_hidden',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_sports',
                        'label' => 'Sports',
                        'name' => 'sport_betting_odds_sports',
                        'aria-label' => '',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => 'sports_hierarchy',
                            'id' => '',
                            'data-level' => 1,
                            'data-parent-id' => 'null',
                        ),
                        'choices' => [0 => 'Choose an option'] + $sports,
                        'default_value' => 1,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_sports_categories',
                        'label' => 'Categories',
                        'name' => 'sport_betting_odds_sports_categories',
                        'aria-label' => '',
                        'type' => 'group',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'block',
                        'sub_fields' => 0,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-sport-betting-odds',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_config_menu() {
        if( function_exists('acf_add_local_field_group') ):
            acf_add_local_field_group(array(
                'key' => 'api_configuration_sport_betting_odds',
                'title' => 'API configuration',
                'fields' => array(
                    array(
                        'key' => 'key_sport_betting_odds_url',
                        'label' => 'URL',
                        'name' => 'sport_betting_odds_url',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_interval',
                        'label' => 'Cache Refresh Frequency (Hours)',
                        'name' => 'sport_betting_odds_interval',
                        'aria-label' => '',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '30',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => 1,
                        'min' => '',
                        'max' => '',
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'key_sport_betting_odds_token',
                        'label' => 'Token',
                        'name' => 'sport_betting_odds_token',
                        'aria-label' => '',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 1,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '70',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'options_page',
                            'operator' => '==',
                            'value' => 'acf-options-sport-betting-odds',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

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

        return $value;
    }

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

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

        return $field;
    }

    public function loadCategoriesHierarchy($field) {
        global $rdgb;
        $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();
        $sub_fields = [];

        global $_POST;

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

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

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

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

                return $field;
            }

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

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

                    return $field;
                }

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

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

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

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

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

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

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

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

            return $field;
        }

        $field['sub_fields'] = $sub_fields;

        return $field;
    }

    public function getApiAttributes($items = null, $attributes = []) {
        $api_url = get_field('sport_betting_odds_url', 'option');
        $api_token = get_field('sport_betting_odds_token', 'option');
        $cache_refresh = get_field('sport_betting_odds_interval', 'option');

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

        $date = null;
        if (isset($attributes['date']) && !empty($attributes['date'])) {
            try {
                $d = DateTime::createFromFormat('Y-m-d', $attributes['date']);
                $date_status = $d && $d->format('Y-m-d') == $attributes['date'];

                if ($date_status) {
                    $date = $d->format('Y-m-d');
                }
            } catch (\Exception $exception) {
                //
            }
        }

        if (empty($date)) {
            $date = date('Y-m-d');
        }

        $api_url .= '&date='.$date;
        $items = (!empty($items)) ? intval($items) : 10;
        $api_url = $api_url.'&recordsQty='.$items;

        $category = '';
        $parts_ids = [];

        if (isset($attributes['category'])) {
            if (strpos($attributes['category'], '-')) {
                $parts_ids = explode('-', $attributes['category']);
                $category = $parts_ids[count($parts_ids) - 1];
            } else {
                $category = $attributes['category'];
            }
        }

        $field = null;
        if (strpos($category, 'G') === 0) {
            $field = 'sports_hierarchy';
            $category = str_replace('G', '', $category);
        } else if (strpos($category, 'L') === 0) {
            $field = 'leagues_hierarchy';
            $category = str_replace('L', '', $category);
        }

        if (!empty($field)) {
            $api_url .= '&'.$field.'='.$category;
        }

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

        return $request;
    }

    public function getApiParams() {
        return [
            'category' => 'sport_betting_odds_category',
            '_to_transform_' => [
                'key' => 'date',
                'function' => 'formatDate',
                'params' => ['sport_betting_odds_date'],
            ],
        ];
    }

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

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

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

        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $injury_report = $rdgb_helpers->getApiData($this->block_name, $cache_file, $request);

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

        $data->json = $injury_report->json;

        return $data;
    }

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

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

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

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

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

        return $count;
    }

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

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

        return $value;
    }

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

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

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

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

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

                if (is_array($children) && count($children) > 0) {
                    $categories[$i][] = ['id' => 0,'class' => '', 'selected' => 0, 'value' => 'Choose an option'];
                    foreach ($children as $key => $child) {
                        $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                        $categories[$i][] = ['id' => $category.'-'.$key,'class' => $class, 'selected' => 0, 'value' => $child];
                    }
                }

                return $categories;
            }

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

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

                    $level++;

                    $children = shMappingHierarchyFamily($new_cat);
                    if (is_array($children) && count($children) > 0) {
                        $categories[$i][] = ['id' => 0,'class' => '', 'selected' => 0, 'value' => 'Choose an option'];
                        foreach ($children as $key => $child) {
                            $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                            $selected = ($new_cat.'-'.str_replace('-child', '', $key) == $option_selected) ? 1 : 0;
                            $categories[$i][] = ['id' => $new_cat.'-'.$key,'class' => $class, 'selected' => $selected, 'value' => $child];
                        }
                    }

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

add_action('wp_ajax_nopriv_load_ajax_sports_family','sport_betting_odds_sports_family');
add_action('wp_ajax_load_ajax_sports_family','sport_betting_odds_sports_family');

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

    if (!empty($sport) && function_exists('shMappingHierarchyFamily')) {
        $sport = (strpos($sport, '-child')) ? str_replace('-child', '', $sport) : $sport;
        $children = shMappingHierarchyFamily($sport);

        if (is_array($children) && count($children) > 0) {
            $categories[] = ['id' => 0, 'class' => '', 'value' => 'Choose an option'];
            foreach ($children as $key => $child) {
                $class = (strpos($key, '-child')) ? 'hierarchy-child' : '';
                $categories[] = ['id' => $sport.'-'.$key,'class' => $class, 'value' => $child];
            }
        }
    }
    
    echo json_encode($categories);

    wp_die();
}

add_action('wp_ajax_nopriv_load_categories_hierarchy','sportBettingOddsCategoriesHierarchy');
add_action('wp_ajax_load_categories_hierarchy','sportBettingOddsCategoriesHierarchy');

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

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

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

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

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

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

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

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

        $i++;
    }

    echo $selects;

    wp_die();
}

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

return $rdg_sport_betting_odds_class;
