<?php

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

/**
 * HELPER COMMENT START
 *
 * This class contains all of the available CLI commands for your plugin.
 * Down below, we added a command that allows you to display the current
 * details about your plugin within the console.
 *
 * To test the command, please head over to your WordPress instance and type in the following
 *
 * wp sportshub_games details
 *
 * HELPER COMMENT END
 */

WP_CLI::add_command('sportshub_games', 'Sportshub_Games_CLI');

/**
 * Class Sportshub_Games_CLI
 *
 * This class contains all WP CLI related features.
 *
 * @package         SHGAMES
 * @subpackage      Classes/Sportshub_Games_CLI
 * @author          IT
 * @since           1.0.0
 */
class Sportshub_Games_CLI extends WP_CLI_Command {
    CONST SOURCE_MEMBERS = 'members';
    CONST SOURCE_MASTERFEED = 'masterfeed';

    function __construct() {
    }

    public function details($args, $assoc_args) {
        WP_CLI::line(sprintf(__('Plugin name: %s', 'SportsHub Games'), SHGAMES_NAME));
        WP_CLI::line(sprintf(__('Plugin version: %s', 'SportsHub Games'), SHGAMES_VERSION));
    }

    public function pull($args, $assoc_args)
    {
        if (get_option('shg_status') != 1) {
            error_log(sprintf(__('Sportshub Games: Plugin disabled.', 'SportsHub Games')));

            return;
        }

        $source = (empty(get_option('shg_source')) || get_option('shg_source') == self::SOURCE_MEMBERS) ? self::SOURCE_MEMBERS : self::SOURCE_MASTERFEED;
        $sports_leagues_name = shMappingSportsLeaguesNamesConverter($source);

        $shg = (!empty($shg)) ? $shg : Sportshub_Games::instance();
        $cpt_lists = $shg->getCustomTypesArray();

        if (!is_array($cpt_lists) || count($cpt_lists) == 0) {
            error_log(sprintf(__('Sportshub Games: It is necessary to define the cpts in the custom_types.json file.', 'SportsHub Games')));

            return;
        }

        $cpts = [];
        $titles = [];
        $parents = [];
        $sports_cpts = [];
        $main_games = [];
        $cpt_titles = [];
        $cpt_default = array_key_first($cpt_lists);
        $shg_sports_leagues_cpt = get_field('shg_sports_leagues', 'options');

        if (is_array($shg_sports_leagues_cpt) && count($shg_sports_leagues_cpt) > 0) {
            foreach ($shg_sports_leagues_cpt as $sport_cpt) {
                $cpts[$sport_cpt['shg_sport_league']] = $sport_cpt['shg_sport_league_cpt'];
                $parents[$sport_cpt['shg_sport_league']] = $sport_cpt['shg_sport_league_post'];
                $titles[$sport_cpt['shg_sport_league']] = $sport_cpt['shg_sport_league_title'];
            }

            if (is_array($cpts) && count($cpts) > 0) {
                $sports_cpts = shMappingAuthorsMainsSportsLeaguesConverter($cpts, $source);
            }

            if (is_array($parents) && count($parents) > 0) {
                $main_games = shMappingAuthorsMainsSportsLeaguesConverter($parents, $source);
            }

            if (is_array($titles) && count($titles) > 0) {
                $cpt_titles = shMappingAuthorsMainsSportsLeaguesConverter($titles, $source);
            }
        }

        $author_general_id = 1;
        $author_general = null;
        $sports_authors = get_field('shg_authors', 'options');
        $authors = [];

        if (is_array($sports_authors) && count($sports_authors) > 0) {
            foreach ($sports_authors as $sport => $author) {
                $post_author = get_user_by('ID', $author['shg_sport_user']);

                if (empty($post_author)) continue;

                if ($author['shg_sport'] == 0) {
                    $author_general = $author['shg_sport_user'];
                    continue;
                } else {
                    $authors[$author['shg_sport']] = $author['shg_sport_user'];
                }
            }
        }

        if (!function_exists('shMappingAuthorsMainsSportsLeaguesConverter')) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')),
            ], true));

            WP_CLI::line(sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')));

            return;
        }

        $authors = shMappingAuthorsMainsSportsLeaguesConverter($authors, $source);

        $author_general = (isset($author_general)) ? get_user_by('id', $author_general) : null;
        if (!empty($author_general)) {
            $author_general_id = $author_general->ID;
        }

        $images = [];
        $sport_featured_image_default = '';
        $sports_images = get_field('shg_sports_featured_images', 'options');

        if (is_array($sports_images) && count($sports_images) > 0) {
            foreach ($sports_images as $sport_image) {
                if (!isset($sport_image['shg_sport']) || !isset($sport_image['shg_image'])) continue;
                $images[$sport_image['shg_sport']] = $sport_image['shg_image'];
            }
        }

        if (isset($images[0])) {
            $sport_featured_image_default = $images[0];
            unset($images[0]);
        }

        $sports_images = shMappingAuthorsMainsSportsLeaguesConverter($images, $source);

        $sports_leagues_parts = [];
        $sports_leagues_data = (is_array(get_field('shgame_sports_and_leagues', 'options')) && count(get_field('shgame_sports_and_leagues', 'options')) > 0)
            ? get_field('shgame_sports_and_leagues', 'options')
            : null;

        if (is_array($sports_leagues_data) && count($sports_leagues_data) > 0) {
            foreach ($sports_leagues_data as $sport_part) {
                if (isset($sport_part['shg_sport_id']) && !empty($sport_part['shg_sport_id']) && isset($sport_part['shg_game_parts']) && !empty($sport_part['shg_game_parts'])) {
                    $sports_leagues_parts[$sport_part['shg_sport_id']] = $sport_part['shg_game_parts'];
                }
            }
        }

        $sports_leagues_array = [];
        $sports_leagues = (is_array(get_field('shg_sports_leagues', 'options')) && count(get_field('shg_sports_leagues', 'options')) > 0)
            ? get_field('shg_sports_leagues', 'options')
            : null;

        if (is_array($sports_leagues) && count($sports_leagues) > 0) {
            foreach ($sports_leagues as $sport) {
                if ($sport['shg_sport_league'] == 0) continue;

                if (isset($sport['shg_sport_league']) && !empty($sport['shg_sport_league'])) {
                    if (strpos($sport['shg_sport_league'], '-')) {
                        list($sport_id, $league_id) = explode('-', $sport['shg_sport_league']);

                        if (!isset($sports_leagues_array[$sport_id])) {
                            $sports_leagues_array[$sport_id] = [];
                            array_push($sports_leagues_array[$sport_id], $league_id);
                        } else {
                            array_push($sports_leagues_array[$sport_id], $league_id);
                        }
                    } else {
                        $league_id = null;
                        $sport_id = $sport['shg_sport_league'];

                        if (!isset($sports_leagues_array[$sport_id])) {
                            $sports_leagues_array[$sport_id] = [];
                        }
                    }
                }
            }
        }

        if (is_array($sports_leagues_array) && count($sports_leagues_array) == 0) {
            $sports_leagues_array[0] = '';
        }

        $filename =  'SPORTS_HUB_GAMES_PULL_'. date('Y-m-d-H-i-s') . '.json';
        $file_path = SHGAMES_PLUGIN_LOG_DIR . '/' . $filename;

        if (!file_exists(SHGAMES_PLUGIN_LOG_DIR)) {
            wp_mkdir_p(SHGAMES_PLUGIN_LOG_DIR);
        }

        $teams = $this->get_teams_data();
        if (!is_array($teams) || count($teams) == 0) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Games: Error while trying to recover the teams.', 'SportsHub Games')),
                'teams' => $teams
            ], true));

            WP_CLI::line(sprintf(__('Sportshub Games: Error while trying to recover the teams.', 'SportsHub Games')));

            return;
        }

        $games = $this->get_games_data();
        if (!is_array($games) || count($games) == 0) {
            error_log(print_r([
                'message' => sprintf(__('SportsHub Games: Error while trying to recover the games.', 'SportsHub Games')),
                'games' => $games
            ], true));
            WP_CLI::line(sprintf(__('SportsHub Games: Error while trying to recover the games.', 'SportsHub Games')));
            return;
        }

        if ($source == self::SOURCE_MEMBERS) {
            if (!function_exists('shMappingSportsLeaguesConverter')) {
                error_log(print_r([
                    'message' => sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')),
                ], true));

                WP_CLI::line(sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')));

                return;
            }

            $sports_converted = shMappingSportsLeaguesConverter($sports_leagues_array, $source);
            $shg_request = $this->get_api_request_members($sports_converted);

            WP_CLI::line(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $shg_request));
            error_log(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $shg_request));

            $execute_request = $this->exe_request($shg_request, $file_path);
            if ($execute_request) {
                $parse_results = $this->parse_feed_file($file_path);

                if (is_array($parse_results) && count($parse_results) > 0) {
                    $new_post = 0;
                    $existing_post = 0;
                    $analyzed_post = 0;

                    foreach ($parse_results as $sport_name => $sports_leagues) {
                        if (isset($sports_leagues['previews']) && is_array($sports_leagues['previews']) && count($sports_leagues['previews']) > 0) {
                            foreach ($sports_leagues['previews'] as $game) {
                                $analyzed_post++;

                                if (!$this->isValidTeams($game)) {
                                    continue;
                                }

                                $title_template = '[team-home] vs [team-visitor] [date]';
                                if (is_array($cpt_titles['leagues']) && isset($cpt_titles['leagues'][$game['league_id']])) {
                                    $title_template = $cpt_titles['leagues'][$game['league_id']];
                                } elseif (is_array($cpt_titles['sports']) && isset($cpt_titles['sports'][$game['id_sport']])) {
                                    $title_template = $cpt_titles['sports'][$game['id_sport']];
                                }

                                $data[] = [
                                    'date' => $game['date'],
                                    'team-home' => $game['home_team'],
                                    'team-visitor' => $game['away_team'],
                                ];

                                $post_title = $this->getTitle($title_template, $data);
                                
                                $status_content = $this->getContentMembers($game);
                                $contents = [
                                    'preview' => $status_content['post_content'],
                                    'knup' => $this->getKnupSportsContent($game),
                                ];

                                $all_content = $this->getAllContents($contents);

                                $cpt_slug = $cpt_default;
                                if (isset($game['id_sport'])) {
                                    if (is_array($sports_cpts['leagues']) && isset($sports_cpts['leagues'][$game['league_id']])) {
                                        $cpt_slug = $sports_cpts['leagues'][$game['league_id']];
                                    } elseif (is_array($sports_cpts['sports']) && isset($sports_cpts['sports'][$game['id_sport']])) {
                                        $cpt_slug = $sports_cpts['sports'][$game['id_sport']];
                                    }
                                }

                                $args = [
                                    'post_title'    => $post_title,
                                    'post_type'     => $cpt_slug,
                                    'post_status'   => $status_content['post_status'],
                                    'post_author'   => $author_general_id,
                                    'post_parent'   => null,
                                    'post_content'  => $all_content,
                                ];

                                $post_id = '';
                                if (isset($game['id'])) {
                                    WP_CLI::line(__('External ID: '. $game['id'], 'SportsHub Games'));
                                    $args['meta_input']['shg_external_id'] = $game['id'];
                                    $post_id = $game['id'];
                                }

                                $attributes = [
                                    'game' => $game,
                                    'sports_leagues_name' => $sports_leagues_name,
                                    'authors' => $authors,
                                    'main_games' => $main_games,
                                    'handicappers' => $sports_leagues['handicappers'],
                                    'sport_name' => $sport_name,
                                ];

                                $args = $this->parse_data($post_id, $args, $attributes);
                                $response = $this->insert_auto_post($args, $cpt_slug, $attributes);

                                if (is_array($response) && isset($response['type'])) {
                                    if ($response['type'] == 'new') {
                                        $new_post++;
                                    } elseif ($response['type'] == 'duplicate') {
                                        $existing_post++;
                                    } else {
                                        WP_CLI::Line($response['message']);
                                    }
                                }
                            }
                        }
                    }

                    error_log(sprintf(__('Sportshub Games: %s Succesfully inserted posts.', 'SportsHub Games'), $new_post));
                    WP_CLI::line(sprintf(__('%s Succesfully inserted posts.', 'SportsHub Games'), $new_post));

                    if ($existing_post > 0) {
                        error_log(sprintf(__('Sportshub Games: %s Existing posts.', 'SportsHub Games'), $existing_post));
                        WP_CLI::line(sprintf(__('%s Existing posts.', 'SportsHub Games'), $existing_post));
                    }

                    if ($analyzed_post > 0) {
                        error_log(sprintf(__('Sportshub Games: %s Posts were analyzed.', 'SportsHub Games'), $analyzed_post));
                        WP_CLI::line(sprintf(__('%s Posts were analyzed.', 'SportsHub Games'), $analyzed_post));
                    }
                } else {
                    error_log('Sportshub Games: No data available for this pull.');
                    WP_CLI::line(__('No data available for this pull', 'SportsHub Games'));
                }
            } else {
                return;
            }
        } else {
            if (!function_exists('shMappingSportsConverter')) {
                error_log(print_r([
                    'message' => sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')),
                ], true));

                WP_CLI::line(sprintf(__('Sportshub Games: The installation of SH Mapping is necessary.', 'SportsHub Games')));

                return;
            }

            $sports_leagues_array_converted = shMappingSportsConverter($sports_leagues_array, $source, 'array');
            $shg_request = $this->get_api_request_masterfeed($sports_leagues_array_converted);

            if (!is_array($shg_request) || (is_array($shg_request) && (!isset($shg_request['requests']) || !isset($shg_request['sports']))) || count($shg_request['requests']) == 0 || count($shg_request['requests']) != count($shg_request['sports'])) {
                WP_CLI::line(__('Error when trying to process requests', 'SportsHub Games'));
                error_log(print_r([
                    'message' => __('Error when trying to process requests', 'SportsHub Games'),
                    'shg_request' => $shg_request,
                ], true));

                return;
            }

            foreach ($shg_request['requests'] as $key =>  $request) {
                if (!empty($request)) {
                    $sport = $shg_request['sports'][$key]['sport'];
                    $category = $shg_request['sports'][$key]['category'];
                    $type = $shg_request['sports'][$key]['type'];

                    if ($sport != null && $category != null) {
                        $pattern = 'SPORTS_HUB_GAMES_%1$s_%2$s_%3$s_%4$s_PULL.json';
                    } else {
                        $pattern = 'SPORTS_HUB_GAMES_%1$s_%3$s_%4$s_PULL.json';
                    }

                    $filename =  sprintf($pattern, $sport, $category, $type, date('Y-m-d-H-i-s'));
                    $file_path = SHGAMES_PLUGIN_LOG_DIR . '/' . $filename;

                    WP_CLI::line(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $request));
                    error_log(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $request));

                    $execute_request = $this->exe_request($request, $file_path);

                    if ($execute_request) {
                        $parse_results = $this->parse_feed_file($file_path);

                        if (isset($parse_results[0]['data-content'][0][0]['contents']) &&
                            is_array($parse_results[0]['data-content'][0][0]['contents']) &&
                            count($parse_results[0]['data-content'][0][0]['contents']) > 0) {
                                $new_post = 0;
                                $existing_post = 0;

                                foreach ($parse_results[0]['data-content'][0][0]['contents'] as $content) {
                                    if (!empty($parse_results)) {
                                        $post_title = 'Game Title';
                                        $post_name = $post_title;
                                        if (isset($content['title']) && !empty($content['title'])) {
                                            $post_title = ucfirst(strtolower($content['title']));
                                        }

                                        $post_status = (!empty(get_field('shg_status_games', 'options'))) ? get_field('shg_status_games', 'options') : 'draft';

                                        $args = [
                                            'post_title'    => $post_title,
                                            'post_name'     => $post_name,
                                            'post_type'     => $cpt_default,
                                            'post_status'   => $post_status,
                                            'post_author'   => $author_general_id,
                                            'post_parent'   => null,
                                            'post_content'   => $this->generateContentMasterfeed($content['body']),
                                        ];

                                        if (isset($content['sport_id'])) {
                                            if (is_array($authors['leagues']) && isset($authors['leagues'][$content['league_id']])) {
                                                $args['post_author'] = $authors['leagues'][$content['league_id']];
                                            } elseif (is_array($authors['sports']) && isset($authors['sports'][$content['sport_id']])) {
                                                $args['post_author'] = $authors['sports'][$content['sport_id']];
                                            }

                                            if (is_array($main_games) && count($main_games) > 0) {
                                                if (is_array($main_games['leagues']) && isset($main_games['leagues'][$content['league_id']])) {
                                                    $args['post_parent'] = $main_games['leagues'][$content['league_id']];
                                                } elseif (is_array($main_games['sports']) && isset($main_games['sports'][$content['sport_id']])) {
                                                    $args['post_parent'] = $main_games['sports'][$content['sport_id']];
                                                }
                                            }

                                            if (is_array($sports_cpts['leagues']) && isset($sports_cpts['leagues'][$content['league_id']])) {
                                                $args['post_type'] = $sports_cpts['leagues'][$content['league_id']];
                                            } elseif (is_array($sports_cpts['sports']) && isset($sports_cpts['sports'][$content['sport_id']])) {
                                                $args['post_type'] = $sports_cpts['sports'][$content['sport_id']];
                                            }
                                        }

                                        $args = $this->parse_data_simple($args, $content, $teams, $games);
                                        $validation = $this->is_valid_args_simple($args);

                                        if (!$validation) {
                                            error_log(print_r([
                                                'message' => 'The game does not contain the required data.',
                                                'shg_external_id' => (isset($args['meta_input']['shg_external_id'])) ? $args['meta_input']['shg_external_id'] : ''
                                            ], true));
                                            continue;
                                        }

                                        if (
                                            isset($content['home_team_id']) &&
                                            isset($content['visitor_team_id']) &&
                                            isset($teams[$content['home_team_id']]['name']) &&
                                            !empty($teams[$content['home_team_id']]['name']) &&
                                            isset($teams[$content['visitor_team_id']]['name']) &&
                                            !empty($teams[$content['visitor_team_id']]['name'])
                                            ) {
                                                $title = $teams[$content['home_team_id']]['name'];
                                                $title .= ' vs. ';
                                                $title .= $teams[$content['visitor_team_id']]['name'];
                                                $title .= ' Pick & Prediction ';
                                                try {
                                                    $title_date = '';
                                                    $title_date = strtoupper(date('F', strtotime($args['meta_input']['shg_game_date']))).' '.date('jS Y', strtotime($args['meta_input']['shg_game_date']));
                                                } catch (\Exception $exception) {
                                                    error_log(print_r([
                                                        'game_date', $args['meta_input']['shg_game_date'],
                                                        'exception', $exception->getMessage()
                                                    ], true));
                                                }
                                                $title .= (!empty($title_date)) ? $title_date : '';
                                                $args['post_title'] = $title;
                                        }

                                        $response = $this->insert_auto_post_content($args, $args['post_type']);
                                        if (is_array($response) && isset($response['type'])) {
                                            if ($response['type'] == 'new') {
                                                $new_post++;
                                            } elseif ($response['type'] == 'duplicate') {
                                                $existing_post++;
                                            } else {
                                                WP_CLI::Line($response['message']);
                                            }
                                        }
                                    } else {
                                        error_log('Sportshub Games: No data available for this pull.');
                                        WP_CLI::line(__('No data available for this pull', 'SportsHub Games'));
                                    }
                                }

                                error_log(sprintf(__('Sportshub Games: %s Succesfully inserted posts.', 'SportsHub Games'), $new_post));
                                WP_CLI::line(sprintf(__('%s Succesfully inserted posts.', 'SportsHub Games'), $new_post));

                                if ($existing_post > 0) {
                                    error_log(sprintf(__('Sportshub Games: %s Existing posts.', 'SportsHub Games'), $existing_post));
                                    WP_CLI::line(sprintf(__('%s Existing posts.', 'SportsHub Games'), $existing_post));
                                }
                        } else {
                            unlink($file_path);

                            WP_CLI::line(__('Sportshub Games: No data available for this pull.', 'SportsHub Games'));
                            error_log(__('Sportshub Games: No data available for this pull.', 'SportsHub Games'));
                        }
                    } else {
                        return;
                    }
                }
            }
        }

        update_option('sportshub_last_run', date('Y-m-d H:i:s'));
    }

    private function isValidTeams($game)
    {
        $valid = 0;
        $valid_data = [];
        $missing_data  = [];

        if (isset($game['external_id']) && !empty($game['external_id'])) {
            $valid_data['external_id'] = $game['external_id'];
        }

        if (isset($game['away_team']) && !empty($game['away_team'])) {
            $valid++;
            $valid_data['away_team'] = $game['away_team'];
        } else {
            $missing_data ['away_team'] = '';
        }

        if (isset($game['home_team']) && !empty($game['home_team'])) {
            $valid++;
            $valid_data['home_team'] = $game['home_team'];
        } else {
            $missing_data ['home_team'] = '';
        }

        if (isset($game['visitor_image']) && !empty($game['visitor_image'])) {
            $valid++;
            $valid_data['visitor_image'] = $game['visitor_image'];
        } else {
            $missing_data ['visitor_image'] = '';
        }

        if (isset($game['home_image']) && !empty($game['home_image'])) {
            $valid++;
            $valid_data['home_image'] = $game['home_image'];
        } else {
            $missing_data ['home_image'] = '';
        }

        if ($valid >= 4) {
            return true;
        }

        error_log(print_r([
            'messge' => 'SH Game: Incomplete equipment data.',
            'valid_data' => $valid_data,
            'missing_data ' => $missing_data ,
        ], true));

        return false;
    }

    public function getContentMembers($game)
    {
        $content = '';
        $count_types = 0;
        $contents = [];

        $post_status = (!empty(get_field('shg_status_games', 'options'))) ? get_field('shg_status_games', 'options') : 'draft';
        $types = get_field('shg_content_types_members', 'options');
        $max_types = count($types);

        foreach ($types as $type) {
            $body = '';
            if ($type['shg_content_type_slug_members'] == 'preview') {
                if (isset($game['body']) && !empty($game['body'])) {
                    $body = $game['body'];
                    $data_game[0] = $game;
                }
            } elseif ($type['shg_content_type_slug_members'] == 'recap') {
                if (isset($game['recap'][0]['body']) && !empty($game['recap'][0]['body'])) {
                    $body = $game['recap'][0]['body'];
                    $data_game = $game['recap'];
                }
            } else {
                if (isset($game[$type['shg_content_type_slug_members']][0]['body']) && !empty($game[$type['shg_content_type_slug_members']][0]['body'])) {
                    $body = $game[$type['shg_content_type_slug_members']][0]['body'];
                }
            }

            if (!empty($body)) {
                $count_types++;
                $content .= $this->generateContentMembers($data_game, $type['shg_content_type_slug_members'], $type['shg_content_type_title_members']);
                $contents[$type['shg_content_type_slug_members']] = true;
            } else {
                $contents[$type['shg_content_type_slug_members']] = false;
            }
        }

        if ($count_types == $max_types) {
            return [
                'post_status' => $post_status,
                'post_content' => $content,
            ];
        }

        if ($count_types > 0 && $count_types < $max_types && $contents['preview'] == true) {
            return [
                'post_status' => $post_status,
                'post_content' => $content,
            ];
        }

        return [
            'post_status' => 'draft',
            'post_content' => '',
        ];
    }

    public function getTeamName($team)
    {
        $nickname = (isset($team['nickname']) && !empty($team['nickname'])) ? $team['nickname'] : '';
        $name = (isset($team['name']) && !empty($team['name'])) ? $team['name'] : '';

        if (!empty($nickname) && !empty($name)) {
            return $name.' '.$nickname;
        }

        if (!empty($nickname) && empty($name)) {
            return $nickname;
        }

        if (empty($nickname) && !empty($name)) {
            return $name;
        }

        return '';
    }

    public function is_valid_args_simple($args)
    {
        $validate = true;
        $fields_required = [
            'shg_external_id',
            'shg_sport_id',
            'shg_game_date',
            'shg_id_home_team',
            'shg_id_visitor_team'
        ];

        if (isset($args['meta_input']) && is_array($args['meta_input']) && count($args['meta_input']) > 0) {
            foreach ($fields_required as $field) {
                if (!isset($args['meta_input'][$field]) || (isset($args['meta_input'][$field]) && empty($args['meta_input'][$field]))) {
                    $validate = false;
                    break;
                };
            }

            if (!$validate) {
                return false;
            } else {
                return true;
            }
        }

        return false;
    }

    public function get_teams_data()
    {
        $teams_array = [];
        $filename_teams =  'SPORTS_HUB_GAMES_TEAMS.json';
        $file_path_teams = SHGAMES_PLUGIN_LOG_DIR . '/' . $filename_teams;
        $helpers = New Sportshub_Games_Helpers;

        if ($helpers->initRedis()) {
            $helpers->setRedisGroup(REDIS_GROUP_SHGAMES);
            $key = $helpers->getRedisKeyTeams();
            $teams = $helpers->getRedis($key);

            if (!empty($teams)) {
                $unserialize_data = unserialize($teams);

                if (is_array($unserialize_data) && count($unserialize_data) > 0) {
                    return $unserialize_data;
                }
            }
        }

        $teams_url = $this->get_api_request_teams();
        $execute_request_teams = $this->exe_request($teams_url, $file_path_teams);

        if ($execute_request_teams) {
            $parse_results_teams = $this->parse_feed_file($file_path_teams);

            if (!empty($parse_results_teams) && isset($parse_results_teams[0]['data-content'][0][0]['teams']) && is_array($parse_results_teams[0]['data-content'][0][0]['teams'])) {
                foreach ($parse_results_teams[0]['data-content'][0][0]['teams'] as $team) {
                    $teams_array[$team['id']] = [
                        'name' => $team['name'],
                        'nickname' => $team['nickname'],
                        'city' => null,
                    ];

                    if (!empty($team['nickname'])) {
                        $teams_array[$team['id']]['city'] = trim(str_replace($team['nickname'], '', $team['name']));
                    }
                }

                if ($helpers->initRedis() && is_array($teams_array) && count($teams_array) > 0) {
                    $helpers->setRedis($key, serialize($teams_array), SHGAMES_REDIS_TIMEOUT);
                }
            }
        }

        return $teams_array;
    }

    public function get_games_data()
    {
        $games_array = [];
        $filename_games =  'SPORTS_HUB_GAMES_INFO.json';
        $file_path_games = SHGAMES_PLUGIN_LOG_DIR . '/' . $filename_games;
        $helpers = New Sportshub_Games_Helpers;
        if ($helpers->initRedis()) {
            $helpers->setRedisGroup(REDIS_GROUP_SHGAMES);
            $key = $helpers->getRedisKeyGames();
            $games = $helpers->getRedis($key);

            if (!empty($games)) {
                return unserialize($games);
            }
        }

        $games_url = $this->get_api_request_games();
        $execute_request_games = $this->exe_request($games_url, $file_path_games);

        if ($execute_request_games) {
            $parse_results_games = $this->parse_feed_file($file_path_games);

            if (!empty($parse_results_games) && isset($parse_results_games[0]['data-content'][0][0]['games']) && is_array($parse_results_games[0]['data-content'][0][0]['games'])) {
                foreach ($parse_results_games[0]['data-content'][0][0]['games'] as $game) {
                    $games_array[$game['id']] = [
                        'home_team_id' => $game['home_team_id'],
                        'visitor_team_id' => $game['visitor_team_id'],
                        'start_date' => $game['start_date'],
                    ];
                }

                if ($helpers->initRedis() && is_array($games_array) && count($games_array) > 0) {
                    $helpers->setRedis($key, serialize($games_array), SHGAMES_REDIS_TIMEOUT);
                }
            }
        }

        return $games_array;
    }

    public function generateContentMasterfeed($content)
    {
        $block_init = '<!-- wp:paragraph --><p class="shg-paragraph">';
        $block_end = '</p><!-- /wp:paragraph -->';

        $paragraphs_content = [];
        $paragraphs = explode("\r\n\r\n", $content);

        if (is_array($paragraphs) && count($paragraphs) > 0) {
            foreach ($paragraphs as $paragraph) {
                if (!empty($paragraph)) {
                    $paragraphs_content[] = $block_init;
                    $paragraphs_content[] = $paragraph;
                    $paragraphs_content[] = $block_end;
                }
            }
        }

        return implode('', $paragraphs_content);
    }

    public function generateContentMembers($content, $type, $title_template)
    {
        $id_type = $this->getIdType($type);
        $title = $this->getTitle($title_template, $content);
        $paragraphs_content[] = '<!-- wp:heading --><h2 class="wp-block-heading shg-game-titles" id="'.$id_type.'">'.$title.'</h2><!-- /wp:heading -->';

        $block_init = '<!-- wp:paragraph --><p class="shg-paragraph">';
        $block_end = '</p><!-- /wp:paragraph -->';

        $paragraphs = explode("\r\n\r\n", $content[0]['body']);

        if (is_array($paragraphs) && count($paragraphs) > 1) {
            foreach ($paragraphs as $paragraph) {
                if (!empty($paragraph)) {
                    $paragraphs_content[] = $block_init;
                    $paragraphs_content[] = $paragraph;
                    $paragraphs_content[] = $block_end;
                }
            }
        } else {
            $paragraphs = explode("\r\n \r\n", $content[0]['body']);

            if (is_array($paragraphs) && count($paragraphs) > 1) {
                foreach ($paragraphs as $paragraph) {
                    if (!empty($paragraph)) {
                        $paragraphs_content[] = $block_init;
                        $paragraphs_content[] = $paragraph;
                        $paragraphs_content[] = $block_end;
                    }
                }
            } else {
                $paragraphs_content[] = $block_init;
                $paragraphs_content[] = $content[0]['body'];
                $paragraphs_content[] = $block_end;
            }
        }

        return implode('', $paragraphs_content);
    }

    public function getTitle($template, $content)
    {
        try {
            $template = str_replace('[date]', date('F jS Y', strtotime($content[0]['date'])), $template);

            if (isset($content[0]['title']) && !empty($content[0]['title'])) {
                $template = str_replace('[title]', $content[0]['title'], $template);
            }

            if (isset($content[0]['team-home']) && !empty($content[0]['team-home'])) {
                $template = str_replace('[team-home]', $content[0]['team-home'], $template);
            }

            if (isset($content[0]['team-visitor']) && !empty($content[0]['team-visitor'])) {
                $template = str_replace('[team-visitor]', $content[0]['team-visitor'], $template);
            }
        } catch (\Exception $exception) {
            error_log(print_r([
                'template' => $template,
                'content' => $content,
                'message' => $exception->getMessage(),
            ], true));
        }

        return $template;
    }

    public function getIdType($type)
    {
        if ($type == 'preview') {
            return 'block-game-links-preview';
        }

        if ($type == 'recap') {
            return 'block-game-links-recap';
        }

        if ($type == 'knup_sports') {
            return 'block-game-links-knup-sports';
        }

        return '';
    }

    public function exe_request($request, $file_path)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        if ($response === false) {
            curl_close($ch);
            error_log(sprintf(__('Sportshub Games: ERROR: %s.', 'SportsHub Games'), curl_error($ch)));
            WP_CLI::line(sprintf(__('ERROR: %s.', 'SportsHub Games'), curl_error($ch)));
        } else {
            file_put_contents($file_path, $response);
            curl_close($ch);

            WP_CLI::line(sprintf(__('JSON response saved to: %s', 'SportsHub Games'), $file_path));

            return true;
        }

        return false;
    }

    public function parse_odds_data($odds, $args)
    {
        $done_types = [];
        $valid_types = ['money_line', 'over_under', 'point_spread'];
        $data = [];

        foreach ($odds as $odd) {
            if (in_array($odd['type'], $valid_types) && !in_array($odd['type'], $done_types)) {
                array_push($done_types, $odd['type']);
                $data[$odd['type']] = $odd;
            }
        }

        if (isset($data['point_spread'])) {
            if (substr($data['point_spread']['home_handicap'], 0, 1) == '-') {
                $args['meta_input']['shg_home_handicap_spread_odds'] = $data['point_spread']['home_handicap'];
                $args['meta_input']['shg_away_handicap_spread_odds'] = '+'.($data['point_spread']['home_handicap'] * -1);
            } else {
                $args['meta_input']['shg_home_handicap_spread_odds'] = '+'.$data['point_spread']['home_handicap'];
                $args['meta_input']['shg_away_handicap_spread_odds'] = '-'.$data['point_spread']['home_handicap'];
            }

            $args['meta_input']['shg_home_spread_odds'] = $data['point_spread']['home_odds'];
            $args['meta_input']['shg_away_spread_odds'] = $data['point_spread']['away_odds'];
        }

        if (isset($data['money_line'])) {
            $args['meta_input']['shg_home_money_odds'] = $data['money_line']['home_odds'];
            $args['meta_input']['shg_away_money_odds'] = $data['money_line']['away_odds'];
        }

        if (isset($data['over_under'])) {
            $args['meta_input']['shg_home_handicap_overunder_odds'] = 'O '.$data['over_under']['total'];
            $args['meta_input']['shg_away_handicap_overunder_odds'] = 'U '.$data['over_under']['total'];

            $args['meta_input']['shg_home_overunder_odds'] = $data['over_under']['over_odds'];
            $args['meta_input']['shg_away_overunder_odds'] = $data['over_under']['under_odds'];
        }

        $args['meta_input']['shg_game_id_odds'] = isset($data['over_under']['game_id']) ? $data['over_under']['game_id'] : '';
        $args['meta_input']['shg_external_id_odds'] = isset($data['over_under']['external_id']) ? $data['over_under']['external_id'] : '';
        $args['meta_input']['shg_sportsbook_odds'] = isset($data['over_under']['sportsbook']) ? $data['over_under']['sportsbook'] : '';
        $args['meta_input']['shg_date_odds'] = isset($data['over_under']['date']) ? $data['over_under']['date'] : '';

        return $args;
    }

    public function parse_data($post_id, $args, $attributes = [])
    {
        $game = $attributes['game'];
        $leagues = isset($attributes['sports_leagues_name']['leagues']) ? $attributes['sports_leagues_name']['leagues'] : [];
        $handicapper = isset($attributes['handicappers'][0]) ? $attributes['handicappers'][0] : [];

        if (isset($game['date'])) {
            $args['meta_input']['shg_game_date'] = $game['date'];
        }

        if (isset($game['home_team']) && !empty($game['home_team']) && isset($game['away_team']) && !empty($game['away_team'])) {
            $args['post_name'] = ucfirst($game['home_team']).' vs '.strtolower($game['away_team']).'/'.$post_id;
        }

        if (isset($game['league_id'])) {
            $args['meta_input']['shg_league'] = $game['league_id'];

            if (isset($leagues[$game['league_id']])) {
                $args['meta_input']['shg_league_name'] = $leagues[$game['league_id']];
            }
        }

        if (isset($game['id_sport'])) {
            $args['meta_input']['shg_sport_id'] = $game['id_sport'];

            if (is_array($attributes['authors']['leagues']) && isset($attributes['authors']['leagues'][$game['league_id']])) {
                $args['post_author'] = $attributes['authors']['leagues'][$game['league_id']];
            } elseif (is_array($attributes['authors']['sports']) && isset($attributes['authors']['sports'][$game['id_sport']])) {
                $args['post_author'] = $attributes['authors']['sports'][$game['id_sport']];
            }

            if (is_array($attributes['main_games']) && count($attributes['main_games']) > 0) {
                if (is_array($attributes['main_games']['leagues']) && isset($attributes['main_games']['leagues'][$game['league_id']])) {
                    $args['post_parent'] = $attributes['main_games']['leagues'][$game['league_id']];
                } elseif (is_array($attributes['main_games']['sports']) && isset($attributes['main_games']['sports'][$game['id_sport']])) {
                    $args['post_parent'] = $attributes['main_games']['sports'][$game['id_sport']];
                }
            }

            if (isset($attributes['sports_leagues_name']['sports'][$game['id_sport']])) {
                $args['meta_input']['shg_sport_name'] = $attributes['sports_leagues_name']['sports'][$game['id_sport']];
            }
        }

        if (isset($game['game_url']) && !empty($game['game_url'])) {
            $args['meta_input']['shg_game_url'] = $game['game_url'];
        }

        if (isset($game['home_team_id']) && !empty($game['home_team_id'])) {
            $args['meta_input']['shg_id_home_team'] = $game['home_team_id'];
        }

        if (isset($game['home_team']) && $game['home_team'] != '') {
            $args['meta_input']['shg_home_team'] = $game['home_team'];
        }

        $args['meta_input']['shg_home_score'] = (isset($game['home_score']) && $game['home_score'] != '') ? $game['home_score'] : 0;

        if (isset($game['home_image']) && $game['home_image'] != '') {
            $args['meta_input']['shg_home_image'] = $game['home_image'];
        }

        if (isset($game['visitor_team_id']) && !empty($game['visitor_team_id'])) {
            $args['meta_input']['shg_id_visitor_team'] = $game['visitor_team_id'];
        }

        if (isset($game['away_team']) && $game['away_team'] != '') {
            $args['meta_input']['shg_visitor_team'] = $game['away_team'];
        }

        $args['meta_input']['shg_visitor_score'] = (isset($game['visitor_score']) && $game['visitor_score'] != '') ? $game['visitor_score'] : 0;

        if (isset($game['visitor_image']) && $game['visitor_image'] != '') {
            $args['meta_input']['shg_visitor_image'] = $game['visitor_image'];
        }

        if (isset($game['game_picks_count'])) {
            $args['meta_input']['shg_game_picks_count'] = $game['game_picks_count'];
        }

        if (is_array($game['odds']) && count($game['odds']) > 0) {
            $args = $this->parse_odds_data($game['odds'], $args);
        }

        if (is_array($handicapper) && count($handicapper) > 0) {
            $args['meta_input']['shg_game_top_handicapper_id'] = $handicapper['id_handicapper'];
            $args['meta_input']['shg_game_top_handicapper_name'] = $handicapper['handicapper']['name'];
            $args['meta_input']['shg_game_top_handicapper_api_image'] = $handicapper['image'];
            $args['meta_input']['shg_game_top_handicapper_description'] = $handicapper['description'];
            $args['meta_input']['shg_game_results_rank'] = $handicapper['rank'];

            if (isset($handicapper['day_results']) && is_array($handicapper['day_results']) && count($handicapper['day_results']) > 0) {
                $args['meta_input']['shg_game_results_yesterday'] = (isset($handicapper['day_results']['yesterday']) && !empty($handicapper['day_results']['yesterday']))
                    ? $handicapper['day_results']['yesterday']
                    : '-';

                $args['meta_input']['shg_game_results_lastthreedays'] = (isset($handicapper['day_results']['lastthreeDays']) && !empty($handicapper['day_results']['lastthreeDays']))
                    ? $handicapper['day_results']['lastthreeDays']
                    : '-';

                $args['meta_input']['shg_game_results_lastsevendays'] = (isset($handicapper['day_results']['lastSevenDays']) && !empty($handicapper['day_results']['lastSevenDays']))
                    ? $handicapper['day_results']['lastSevenDays']
                    : '-';

                $args['meta_input']['shg_game_results_lastthirtydays'] = (isset($handicapper['day_results']['lastThirtyDays']) && !empty($handicapper['day_results']['lastThirtyDays']))
                    ? $handicapper['day_results']['lastThirtyDays']
                    : '-';
            }

            if (isset($handicapper['picks']) && is_array($handicapper['picks']) && count($handicapper['picks']) > 0) {
                $data = $handicapper['picks'];

                foreach ($data as $pick) {
                    $picks = [];
                    $picks_fields_count = 0;

                    if (isset($pick['id_sport']) && !empty($pick['id_sport'])) {
                        $picks['shg_pick_sport'] = $pick['id_sport'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['date_placed']) && !empty($pick['date_placed'])) {
                        $picks['shg_pick_date'] = $pick['date_placed'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['result']) && !empty($pick['result'])) {
                        $picks['shg_pick_status'] = $pick['result'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['home_name']) && !empty($pick['home_name'])) {
                        $picks['shg_pick_home_name'] = $pick['home_name'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['home_image']) && !empty($pick['home_image'])) {
                        $picks['shg_pick_home_image_api'] = $pick['home_image'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['visitor_name']) && !empty($pick['visitor_name'])) {
                        $picks['shg_pick_visitor_name'] = $pick['visitor_name'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['visitor_image']) && !empty($pick['visitor_image'])) {
                        $picks['shg_pick_visitor_image_api'] = $pick['visitor_image'];
                        $picks_fields_count++;
                    }

                    if (isset($pick['game_url']) && !empty($pick['game_url'])) {
                        $picks['shg_pick_game_url'] = $pick['game_url'];
                        $picks_fields_count++;
                    }

                    if ($picks_fields_count == 8) {
                        $args['picks'][] = $picks;
                    }
                }
            }
        }

        if (isset($game['picks']) && is_array($game['picks'])) {
            $data = $game['picks'];

            foreach ($data as $pick) {
                $picks_game = [];
                $picks_game_fields_count = 0;

                if (isset($pick['handicapper']['name']) && !empty($pick['handicapper']['name'])) {
                    $picks_game['shg_pick_game_handicapper_name'] = $pick['handicapper']['name'];
                    $picks_game_fields_count++;
                }

                if (isset($pick['handicapper']['image']) && !empty($pick['handicapper']['image'])) {
                    $picks_game['shg_pick_game_handicapper_image'] = $pick['handicapper']['image'];
                    $picks_game_fields_count++;
                }

                $picks_game['shg_pick_game_handicapper_package'] = 'Classic Package';
                if (isset($pick['handicapper']['group']) && !empty($pick['handicapper']['group'])) {
                    $picks_game['shg_pick_game_handicapper_package'] = $pick['handicapper']['group'];
                }

                $picks_game['shg_pick_game_handicapper_win'] = '0';
                if (isset($pick['handicapper']['stat']['handicapper_data']['win'])) {
                    $picks_game['shg_pick_game_handicapper_win'] = $pick['handicapper']['stat']['handicapper_data']['win'];
                }

                $picks_game['shg_pick_game_handicapper_lose'] = '0';
                if (isset($pick['handicapper']['stat']['handicapper_data']['lose'])) {
                    $picks_game['shg_pick_game_handicapper_lose'] = $pick['handicapper']['stat']['handicapper_data']['lose'];
                }

                if (isset($pick['handicapper']['stat']['handicapper_data']['filter_hierarchy_sport']) && !empty($pick['handicapper']['stat']['handicapper_data']['filter_hierarchy_sport'])) {
                    $picks_game['shg_pick_game_sport_name'] = trim($pick['handicapper']['stat']['handicapper_data']['filter_hierarchy_sport']);
                } else {
                    $picks_game['shg_pick_game_sport_name'] = !empty($attributes['sport_name']) ? ucfirst(strtolower(trim($attributes['sport_name']))) : 'Sport';
                }

                if (isset($pick['date_placed']) && !empty($pick['date_placed'])) {
                    $picks_game['shg_pick_game_date'] = $pick['date_placed'];
                    $picks_game_fields_count++;
                }

                $picks_game['shg_pick_game_sport_acronym'] = '-';
                if (isset($pick['handicapper']['sport'])) {
                    $picks_game['shg_pick_game_sport_acronym'] = trim($pick['handicapper']['sport']);
                }

                $picks_game['shg_pick_game_bet'] = '-';
                if (isset($pick['handicapper']['bet'])) {
                    $picks_game['shg_pick_game_bet'] = trim($pick['handicapper']['bet']);
                }

                if (isset($pick['teaser'])) {
                    $picks_game['shg_pick_game_teaser'] = trim($pick['teaser']);
                    $picks_game_fields_count++;
                }

                if (isset($game['home_image']) && !empty($game['home_image'])) {
                    $picks_game['shg_pick_game_home_image_api'] = $game['home_image'];
                    $picks_game_fields_count++;
                }

                if (isset($game['visitor_image']) && !empty($game['visitor_image'])) {
                    $picks_game['shg_pick_game_visitor_image_api'] = $game['visitor_image'];
                    $picks_game_fields_count++;
                }

                if (isset($pick['handicapper']['profile_url']) && !empty($pick['handicapper']['profile_url'])) {
                    $picks_game['shg_pick_game_url_profile'] = $pick['handicapper']['profile_url'];
                    $picks_game_fields_count++;
                }

                if ($picks_game_fields_count >= 7) {
                    $args['picks_game'][] = $picks_game;
                }
            }
        }

        return $args;
    }

    public function parse_data_simple($args, $content, $teams, $games)
    {
        if (isset($content['id'])) {
            $args['meta_input']['shg_external_id'] = $content['id'];
        }

        if (isset($content['game_id']) && !empty($content['game_id']) && isset($games[$content['game_id']]['start_date'])) {
            $args['meta_input']['shg_game_date'] = $games[$content['game_id']]['start_date'];
        }

        if (isset($content['sport_id'])) {
            $args['meta_input']['shg_sport_id'] = $content['sport_id'];
        }

        if (isset($content['home_team_id'])) {
            $args['meta_input']['shg_id_home_team'] = $content['home_team_id'];

            if (isset($teams[$content['home_team_id']]) && !empty($teams[$content['home_team_id']])) {
                if (isset($teams[$content['home_team_id']]['nickname']) && !empty(isset($teams[$content['home_team_id']]['nickname']))) {
                    $args['meta_input']['shg_home_team'] = $teams[$content['home_team_id']]['nickname'];
                }
            }
        }

        if (isset($content['visitor_team_id'])) {
            $args['meta_input']['shg_id_visitor_team'] = $content['visitor_team_id'];

            if (isset($teams[$content['visitor_team_id']]) && !empty($teams[$content['visitor_team_id']])) {
                if (isset($teams[$content['visitor_team_id']]['nickname']) && !empty(isset($teams[$content['visitor_team_id']]['nickname']))) {
                    $args['meta_input']['shg_visitor_team'] = $teams[$content['visitor_team_id']]['nickname'];
                }
            }
        }

        if (isset($content['extra_details']['images'][0]['preview_url'])) {
            $args['meta_input']['shg_game_api_image'] = $content['extra_details']['images'][0]['preview_url'];
        }

        return $args;
    }

    public function get_api_request_masterfeed($sports_leagues)
    {
        $api_request = '';
        $api_requests = [];
        $sports_categories = [];
        $api_base = get_field('sportshub_api_masterfeed_url', 'options');
        $api_token = get_field('sportshub_api_masterfeed_token', 'options');
        $content_types = get_field('shg_content_types', 'options');

        if (!is_array($sports_leagues) ||
            (is_array($sports_leagues) && count($sports_leagues) == 0) ||
            !is_array($content_types) ||
            (is_array($content_types) && count($content_types) == 0)) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Games: Sports and types content must be configured.', 'SportsHub Games')),
                'sports_leagues' => $sports_leagues,
                'content_types' => $content_types,
            ], true));

            return [];
        }

        foreach ($sports_leagues as $sport => $league) {
            if (!empty($sport)) {
                $api_url = (substr($api_base, -1) == '/') ? substr($api_base, 0, strlen($api_base) -1) : $api_base;
                $api_url .= '?date='.date('Y-m-d');
                //$api_url .= '?date=2025-03-01';
                $api_url .= '&sport_id='.$sport;

                if (is_array($league) && count($league) > 0) {
                    foreach ($league as $cat) {
                        foreach ($content_types as $type) {
                            if (is_array($type) && count($type) > 0 && !empty($type['shg_content_type_slug'])) {
                                $api_url_type = $api_url.'&league_id='.$cat.'&type='.$type['shg_content_type_slug'];
                                $api_request = $api_url_type.'&key='.$api_token;

                                $api_requests[] = $api_request;
                                $sports_categories[] = [
                                    'sport' => $sport,
                                    'category' => $cat,
                                    'type' => $type['shg_content_type_slug'],
                                ];
                            } else {
                                error_log(print_r([
                                    'message' => 'Invalid content type',
                                ], true));
                            }
                        }
                    }
                } else {
                    foreach ($content_types as $type) {
                        if (is_array($type) && count($type) > 0 && !empty($type['shg_content_type_slug'])) {
                            $api_url_type = $api_url.'&type='.$type['shg_content_type_slug'];
                            $api_request = $api_url_type.'&key='.$api_token;

                            $api_requests[] = $api_request;
                            $sports_categories[] = [
                                'sport' => $sport,
                                'category' => null,
                                'type' => $type['shg_content_type_slug'],
                            ];
                        } else {
                            error_log(print_r([
                                'message' => 'Invalid content type',
                            ], true));
                        }
                    }
                }
            }
        }

        return ['requests' => $api_requests, 'sports' => $sports_categories];
    }

    public function get_api_request_members($sports_leagues)
    {
        $api_base = get_field('sportshub_api_url', 'options');
        $api_token = get_field('sportshub_api_token', 'options');
        $content_types = get_field('shg_content_types_members', 'options');
        $range_days = $this->get_range_days();

        if (!is_array($sports_leagues) ||
            (is_array($sports_leagues) && count($sports_leagues) == 0) ||
            !is_array($content_types) ||
            (is_array($content_types) && count($content_types) == 0)) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Games: Sports and types content must be configured.', 'SportsHub Games')),
                'sports_leagues' => $sports_leagues,
                'content_types' => $content_types,
            ], true));

            return [];
        }

        $api_url = (substr($api_base, -1) == '/') ? substr($api_base, 0, strlen($api_base) -1) : $api_base;
        
        $start = date('Y-m-d');
        $api_url .= '?start_date=' . $start;
        if (!empty($range_days)) {
            $end = date('Y-m-d', strtotime("$start + $range_days days"));
            $api_url .= '&end_date=' . $end;
        }

        if (!empty($sports_leagues['sports'])) {
            $api_url .= '&sports='.$sports_leagues['sports'];
        }

        if (!empty($sports_leagues['leagues'])) {
            $api_url .= '&leagues='.$sports_leagues['leagues'];
        }

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

        return $api_url;
    }

    public function get_range_days()
    {
        if (!empty(get_option('sportshub_range_days'))) return get_option('sportshub_range_days');
        if (!empty(get_field('shg_range_days', 'options'))) return absint(get_field('shg_range_days', 'options'));

        return null;
    }

    public function get_api_request_teams()
    {
        $api_request = '';
        $api_base = (!empty(get_field('shg_teams_url', 'options')))
            ? get_field('shg_teams_url', 'options')
            : 'http://masterfeed.shnadmin.com/feed/media/teams';
        $api_token = get_field('sportshub_api_masterfeed_token', 'options');


        $api_request = $api_base.'?key='.$api_token;

        return $api_request;
    }

    public function get_api_request_games()
    {
        $api_request = '';
        $api_base = (!empty(get_field('shg_games_url', 'options')))
            ? get_field('shg_games_url', 'options')
            : 'http://masterfeed.shnadmin.com/feed/media/games';
        $api_token = get_field('sportshub_api_masterfeed_token', 'options');

        $api_request = $api_base.'?key='.$api_token;
        return $api_request;
    }

    public function get_sports_categories_url_params($sports_leagues, $parts) {
        if (!is_array($sports_leagues) || count($sports_leagues) == 0) return null;

        $sports = [];
        $categories = [];
        $leagues = [];
        $game_parts = [];

        foreach($sports_leagues as $key => $sport) {
            $category_param = 'NULL';
            $league_param = 'NULL';

            if (is_array($sport) && count($sport) > 0) {
                $category_param = $sport[0];
            }

            if (isset($parts[$key])) {
                $game_parts[] = $parts[$key];
            }

            $sports[] = $key;
            $categories[] = $category_param;
            $leagues[] = $league_param;
        }

        $params = [
            'sport='.implode(',', $sports),
            'category='.implode(',', $categories),
            'league='.implode(',', $leagues),
            'gamePart='.implode(',', $game_parts),
        ];

        return implode('&', $params);
    }

    public function getAllContents($contents) {
        $all_content_data = '';

        if (is_array($contents) && count($contents) > 0) {
            foreach ($contents as $type => $content) {
                $all_content_data .=  $content;
            }
        }

        return $all_content_data;
    }

    public function isTitleAndContentDuplicate($args, $cpt_slug) {
        wp_reset_postdata();

        $args_search = [
            'post_type' => $cpt_slug,
            'post_status' => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
            'title' => $args['post_title'],
        ];

        $query = new WP_Query($args_search);

        while ($query->have_posts()) {
            $query->the_post();
            $post = get_post();

            if (intval(get_post_meta($post->ID, 'shg_external_id', true)) === intval($args['meta_input']['shg_external_id'])) {
                continue;
            }

            if ($post->post_content === $args['post_content']) {
                return true;
            }
        }

        return false;
    }

    public function insert_auto_post($args, $cpt_slug, $attributes)
    {
        $helpers = New Sportshub_Games_Helpers;

        if ($helpers->isValidateContent()) {
            if ($this->isTitleAndContentDuplicate($args, $cpt_slug)) {
                return [
                    'type' => 'error',
                    'message' => 'Duplicate title and content in a post with a different ID.'
                ];
            }
        }

        wp_reset_postdata();

        $args_search = [
            'post_type' => $cpt_slug,
            'post_status' => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
            'meta_query' => [
                [
                    'key' => 'shg_external_id',
                    'value' => $args['meta_input']['shg_external_id'],
                    'compare' => '=',
                ],
            ],
        ];

        $game = $attributes['game'];
        $query = new WP_Query($args_search);

        if (!$query->have_posts()) {
            # Get local team image data
            $home_image = $this->uploadImage($args['meta_input']['shg_home_image']);
            if (!empty($home_image)) {
                $args['meta_input']['shg_home_local_url'] = $home_image;
            }

            # Get visitor team image data
            $visitor_image = $this->uploadImage($args['meta_input']['shg_visitor_image']);
            if (!empty($visitor_image)) {
                $args['meta_input']['shg_visitor_local_url'] = $visitor_image;
            }

            # Get Top Handicapper image data
            $hancicapper_image = $this->uploadImage($args['meta_input']['shg_game_top_handicapper_api_image']);
            if (!empty($hancicapper_image)) {
                $args['meta_input']['shg_game_top_handicapper_local_image'] = $hancicapper_image;
            }

            # Create CPT Game
            $post_id = wp_insert_post($args);

            if (isset($game['extra_details']['images'][0]['preview_url']) && !empty($game['extra_details']['images'][0]['preview_url'])) {
                # Get featured image game
                $featured_image_id = $this->uploadImage($game['extra_details']['images'][0]['preview_url'], 'ID');

                if (!empty($featured_image_id)) {
                    set_post_thumbnail($post_id, $featured_image_id);
                }
            }

            if (!is_wp_error($post_id)) {
                if (isset($args['picks']) && is_array($args['picks']) && count($args['picks']) > 0) {
                    foreach ($args['picks'] as $pick) {
                        # Get local team image pick
                        $home_image = $this->uploadImage($pick['shg_pick_home_image_api']);
                        if (!empty($home_image)) {
                            $pick['shg_pick_home_image_local'] = $home_image;
                        } else {
                            continue;
                        }

                        # Get visitor team image pick
                        $visitor_image = $this->uploadImage($pick['shg_pick_visitor_image_api']);
                        if (!empty($visitor_image)) {
                            $pick['shg_pick_visitor_image_local'] = $visitor_image;
                        } else {
                            continue;
                        }

                        add_row('shg_picks', $pick, $post_id);
                    }
                }

                if (isset($args['picks_game']) && is_array($args['picks_game']) && count($args['picks_game']) > 0) {
                    foreach ($args['picks_game'] as $picks_game) {
                        # Get handicapper logo image pick game
                        $handicapper_logo = $this->uploadImage($picks_game['shg_pick_game_handicapper_image']);
                        if (!empty($handicapper_logo)) {
                            $picks_game['shg_pick_game_handicapper_image_local'] = $handicapper_logo;
                        } else {
                            continue;
                        }

                        # Get local team image pick game
                        $home_image = $this->uploadImage($picks_game['shg_pick_game_home_image_api']);
                        if (!empty($home_image)) {
                            $picks_game['shg_pick_game_home_image_local'] = $home_image;
                        } else {
                            continue;
                        }

                        # Get visitor team image pick game
                        $visitor_image = $this->uploadImage($picks_game['shg_pick_game_visitor_image_api']);
                        if (!empty($visitor_image)) {
                            $picks_game['shg_pick_game_visitor_image_local'] = $visitor_image;
                        } else {
                            continue;
                        }

                        add_row('shg_picks_game', $picks_game, $post_id);
                    }
                }

                return ['type' => 'new', 'post_id' => $post_id, 'message' => ''];
            } else {
                return ['type' => 'error', 'post_id' => null, 'message' => $post_id->get_error_message()];
            }
        } 
        else {
            while ($query->have_posts()) {
                $query->the_post();
                $post = get_post();
            }

            #Update SHG Game Block
            $new_data = $this->updateBlockGameData($post->ID, $args);

            #Update CPT Game content and status
            $content_update = $this->getContentUpdated($post->post_content, $game);
            if (!empty($content_update)) {
                $new_data['post_content'] = $content_update;
            }

            #Update SHG Top Handicapper Block
            $new_data = $this->updateBlockTopHandicapperData($new_data, $args);

            #Update SHG Top Handicapper Picks
            if (isset($args['picks']) && is_array($args['picks']) && count($args['picks']) > 0) {
                while (delete_row('shg_picks', 1));

                foreach ($args['picks'] as $pick) {
                    # Get local team image pick
                    $home_image = $this->uploadImage($pick['shg_pick_home_image_api']);
                    if (!empty($home_image)) {
                        $pick['shg_pick_home_image_local'] = $home_image;
                    } else {
                        continue;
                    }

                    # Get visitor team image pick
                    $visitor_image = $this->uploadImage($pick['shg_pick_visitor_image_api']);
                    if (!empty($visitor_image)) {
                        $pick['shg_pick_visitor_image_local'] = $visitor_image;
                    } else {
                        continue;
                    }

                    add_row('shg_picks', $pick, $post->ID);
                }
            }

            #Update SHG Top Handicapper Block
            $new_data = $this->updateBlockTopHandicapperOddsData($new_data, $args);

            # Update CPT Game
            $post_id = wp_update_post($new_data);
            $post_featured_image_id = get_post_thumbnail_id($post_id);

            if (empty($post_featured_image_id) && isset($game['extra_details']['images']['preview_url']) && !empty($game['extra_details']['images']['preview_url'])) {
                # Get featured image game
                $featured_image_id = $this->uploadImage($game['extra_details']['images']['preview_url'], 'ID');

                if (!empty($featured_image_id)) {
                    set_post_thumbnail($post_id, $featured_image_id);
                }
            }

            #Update SHG Picks Game
            if (isset($args['picks_game']) && is_array($args['picks_game']) && count($args['picks_game']) > 0) {
                while (delete_row('shg_picks_game', 1));

                foreach ($args['picks_game'] as $pick_game) {
                    # Get handicapper logo image pick game
                    $handicapper_logo = $this->uploadImage($pick_game['shg_pick_game_handicapper_image']);
                    if (!empty($handicapper_logo)) {
                        $pick_game['shg_pick_game_handicapper_image_local'] = $handicapper_logo;
                    } else {
                        continue;
                    }

                    # Get local team image pick
                    $home_image = $this->uploadImage($pick_game['shg_pick_game_home_image_api']);
                    if (!empty($home_image)) {
                        $pick_game['shg_pick_game_home_image_local'] = $home_image;
                    } else {
                        continue;
                    }

                    # Get visitor team image pick
                    $visitor_image = $this->uploadImage($pick_game['shg_pick_game_visitor_image_api']);
                    if (!empty($visitor_image)) {
                        $pick_game['shg_pick_game_visitor_image_local'] = $visitor_image;
                    } else {
                        continue;
                    }

                    add_row('shg_picks_game', $pick_game, $post->ID);
                }
            }

            WP_CLI::line(__('Post already in the DB, ID: '. $post->ID, 'SportsHub Games'));
            return ['type' => 'duplicate', 'post_id' => $post->ID, 'message' => ''];
        }
    }

    public function getContentUpdated($post_content, $game)
    {
        $content_knup = trim($this->getKnupSportsContent($game));
        $content_preview = $this->getContentMembers($game);

        $contents = [
            'preview' => trim($content_preview['post_content']),
            'knup' => $content_knup,
        ];

        $all_content = $this->getAllContents($contents);

        if (empty(trim($post_content))) {
            return !empty($all_content) ? $all_content : null;
        }

        if (trim($post_content) == trim($content_preview['post_content'])) {
            if (!empty($content_knup)) {
                return trim($post_content).$content_knup;
            }

            return null;
        }

        if (trim($post_content) == trim($content_knup)) {
            if (!empty($content_preview['post_content'])) {
                return trim($content_preview['post_content']).trim($post_content);
            }

            return null;
        }

        return null;
    }

    public function updateBlockTopHandicapperOddsData($new_data, $args)
    {
        $new_data['meta_input']['shg_home_handicap_spread_odds'] = (isset($args['meta_input']['shg_home_handicap_spread_odds'])) ? $args['meta_input']['shg_home_handicap_spread_odds'] : '';
        $new_data['meta_input']['shg_away_handicap_spread_odds'] = (isset($args['meta_input']['shg_away_handicap_spread_odds'])) ? $args['meta_input']['shg_away_handicap_spread_odds'] : '';
        $new_data['meta_input']['shg_home_spread_odds'] = (isset($args['meta_input']['shg_home_spread_odds'])) ? $args['meta_input']['shg_home_spread_odds'] : '';
        $new_data['meta_input']['shg_away_spread_odds'] = (isset($args['meta_input']['shg_away_spread_odds'])) ? $args['meta_input']['shg_away_spread_odds'] : '';
        $new_data['meta_input']['shg_home_money_odds'] = (isset($args['meta_input']['shg_home_money_odds'])) ? $args['meta_input']['shg_home_money_odds'] : '';
        $new_data['meta_input']['shg_away_money_odds'] = (isset($args['meta_input']['shg_away_money_odds'])) ? $args['meta_input']['shg_away_money_odds'] : '';
        $new_data['meta_input']['shg_home_handicap_overunder_odds'] = (isset($args['meta_input']['shg_home_handicap_overunder_odds'])) ? $args['meta_input']['shg_home_handicap_overunder_odds'] : '';
        $new_data['meta_input']['shg_away_handicap_overunder_odds'] = (isset($args['meta_input']['shg_away_handicap_overunder_odds'])) ? $args['meta_input']['shg_away_handicap_overunder_odds'] : '';
        $new_data['meta_input']['shg_home_overunder_odds'] = (isset($args['meta_input']['shg_home_overunder_odds'])) ? $args['meta_input']['shg_home_overunder_odds'] : '';
        $new_data['meta_input']['shg_away_overunder_odds'] = (isset($args['meta_input']['shg_away_overunder_odds'])) ? $args['meta_input']['shg_away_overunder_odds'] : '';

        return $new_data;
    }

    public function updateBlockTopHandicapperData($new_data, $args)
    {
        $new_data['meta_input']['shg_game_top_handicapper_description'] = $args['meta_input']['shg_game_top_handicapper_description'];
        $new_data['meta_input']['shg_game_results_rank'] = $args['meta_input']['shg_game_results_rank'];
        $new_data['meta_input']['shg_game_results_yesterday'] = $args['meta_input']['shg_game_results_yesterday'];
        $new_data['meta_input']['shg_game_results_lastthreedays'] = $args['meta_input']['shg_game_results_lastthreedays'];
        $new_data['meta_input']['shg_game_results_lastsevendays'] = $args['meta_input']['shg_game_results_lastsevendays'];
        $new_data['meta_input']['shg_game_results_lastthirtydays'] = $args['meta_input']['shg_game_results_lastthirtydays'];

        if (!empty($args['meta_input']['shg_game_top_handicapper_api_image']) && empty($args['meta_input']['shg_game_top_handicapper_local_image'])) {
            $image = $this->uploadImage($args['meta_input']['shg_game_top_handicapper_api_image']);
            if (!empty($image)) {
                $new_data['meta_input']['shg_game_top_handicapper_local_image'] = $image;
            }
        }

        return $new_data;
    }

    public function updateBlockGameData($post_id, $args)
    {
        $new_data = [
            'ID' => $post_id,
            'meta_input' => [
                'shg_game_picks_count' => isset($args['meta_input']['shg_game_picks_count']) ? $args['meta_input']['shg_game_picks_count'] : 0,
                'shg_home_score' => $args['meta_input']['shg_home_score'],
                'shg_visitor_score' => $args['meta_input']['shg_visitor_score'],
            ]
        ];

        if (!empty($args['meta_input']['shg_home_image']) && empty($args['meta_input']['shg_home_local_url'])) {
            $image = $this->uploadImage($args['meta_input']['shg_home_image']);
            if (!empty($image)) {
                $new_data['meta_input']['shg_home_local_url'] = $image;
            }
        }

        if (!empty($args['meta_input']['shg_visitor_image']) && empty($args['meta_input']['shg_visitor_local_url'])) {
            $image = $this->uploadImage($args['meta_input']['shg_visitor_image']);
            if (!empty($image)) {
                $new_data['meta_input']['shg_visitor_local_url'] = $image;
            }
        }

        return $new_data;
    }

    public function uploadImage($image_url, $format = 'guid')
    {
        $helpers = New Sportshub_Games_Helpers;
        $image = $helpers->getNameFile($image_url);

        if (is_array($image) && isset($image['is_image']) && $image['is_image'] == true) {
            $attachment_check = $this->get_attachment('post_title', $image['name']);

            if (empty($attachment_check)) {
                # Download the image and upload it to the media library
                $attachment_id = media_sideload_image($image['image_url'], 0, $image['name'], 'id');

                if (is_wp_error($attachment_id)) {
                    error_log(print_r([
                        'message' => $attachment_id->get_error_message(),
                        'image' => $image,
                    ], true));

                    return '';
                }

                # Update image attachment with alt text
                update_post_meta($attachment_id, '_wp_attachment_image_alt', $image['alt']);

                # Get url of already stored image
                $attachment_check = $this->get_attachment('ID', $attachment_id);

                return $attachment_check[0][$format];
            } else {
                return $attachment_check[0][$format];
            }
        }

        return '';
    }

    public function insert_auto_post_content($args, $cpt_slug)
    {
        wp_reset_postdata();

        $args_search = [
            'post_type' => $cpt_slug,
            'meta_query' => [
                [
                    'key' => 'shg_external_id',
                    'value' => $args['meta_input']['shg_external_id'],
                    'compare' => '=',
                ],
            ],
        ];

        $helpers = New Sportshub_Games_Helpers;
        $query = new WP_Query($args_search);

        if (!$query->have_posts()) {
            # Get local image data
            $game_attachment_id = null;
            $game_image = $helpers->getNameFile($args['meta_input']['shg_game_api_image'], false);

            if (is_array($game_image) && isset($game_image['is_image']) && $game_image['is_image'] == true) {
                $attachment_game_check = $this->get_attachment('post_title', $game_image['name']);

                if (!is_array($attachment_game_check) || !isset($attachment_game_check[0]['guid']) || empty($attachment_game_check[0]['guid'])) {
                    # Download the image and upload it to the media library
                    $game_attachment_id = media_sideload_image($game_image['image_url'], 0, $game_image['name'], 'id');

                    if ($game_attachment_id instanceof WP_Error) {
                        error_log(print_r([
                            'errors' => $game_attachment_id->errors,
                            'args' => $args['meta_input'],
                        ], true));
                    } else {
                        # Update image attachment with alt text
                        update_post_meta($game_attachment_id, '_wp_attachment_image_alt', $game_image['alt']);

                        # Get url of already stored image
                        $attachment_game_check = $this->get_attachment('ID', $game_attachment_id);
                        $args['meta_input']['shg_game_local_image'] = $attachment_game_check[0]['guid'];
                    }
                } else {
                    $args['meta_input']['shg_game_local_image'] = $attachment_game_check[0]['guid'];
                }
            }

            # Create CPT Game
            $post_id = wp_insert_post($args);
            $attachment_id = null;

            if (!$game_attachment_id instanceof WP_Error && isset($game_attachment_id) && !empty($game_attachment_id)) {
                $attachment_id = $game_attachment_id;
            } elseif (isset($attachment_game_check[0]['ID']) && !empty($attachment_game_check[0]['ID'])) {
                $attachment_id = $attachment_game_check[0]['ID'];
            }

            if (!empty($attachment_id)) {
                set_post_thumbnail($post_id, $attachment_id);
            }

            $teams = $this->get_teams_data();

            if (
                isset($args['meta_input']['shg_id_home_team']) &&
                isset($args['meta_input']['shg_id_visitor_team']) &&
                isset($teams[$args['meta_input']['shg_id_home_team']]['name']) &&
                !empty($teams[$args['meta_input']['shg_id_home_team']]['name']) &&
                isset($teams[$args['meta_input']['shg_id_visitor_team']]['name']) &&
                !empty($teams[$args['meta_input']['shg_id_visitor_team']]['name'])
                ) {
                    $name = $teams[$args['meta_input']['shg_id_home_team']]['name'];
                    $name .= '-vs-';
                    $name .= $teams[$args['meta_input']['shg_id_visitor_team']]['name'];
                    $name .= '-preview-and-predictions-'.$post_id;

                    $update_data['ID'] = $post_id;
                    $update_data['post_name'] = sanitize_title($name);
                    $update_data['meta_input']['shg_game_url'] = sanitize_title($name);

                    wp_update_post($update_data);
            }

            if (!is_wp_error($post_id)) {
                return ['type' => 'new', 'post_id' => $post_id, 'message' => ''];
            } else {
                return ['type' => 'error', 'post_id' => null, 'message' => $post_id->get_error_message()];
            }
        } else {
            while ($query->have_posts()) {
                $query->the_post();
                $post_id = get_the_ID();
            }

            WP_CLI::line(__('Post already in the DB, ID: '. $post_id, 'SportsHub Games'));
            return ['type' => 'duplicate', 'post_id' => $post_id, 'message' => ''];
        }
    }

    public function get_content_request($params)
    {
        $api_request = '';
        $content_url = get_field('shg_content_url', 'option');
        $content_token = get_field('shg_content_token', 'option');

        if (empty($content_url) || empty($content_token)) {
            return $api_request;
        }

        $content_url = (substr($content_url, -1) == '/') ? substr($content_url, 0, strlen($content_url) -1) : $content_url;
        $content_url .= '?date='.date('Y-m-d');
        $content_url .= '&type='.$params['type'];
        $content_url .= '&sport_id='.$params['sport_id'];

        if (!empty($params['league_id'])) {
            $content_url .= '&league_id='.$params['league_id'];
        }

        if (!empty($params['home_team_id'])) {
            $content_url .= '&home_team_id='.$params['home_team_id'];
        }

        if (!empty($params['visitor_team_id'])) {
            $content_url .= '&visitor_team_id='.$params['visitor_team_id'];
        }

        $api_request = $content_url.'&key='.$content_token;

        return $api_request;
    }

    public function get_attachment($field, $value)
    {
        global $wpdb;
        $value = esc_sql($value);
        $attachment = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE $field = '$value' AND post_type = 'attachment'", ARRAY_A);

        if (is_array($attachment)) {
            return $attachment;
        }

        return null;
    }

    function parse_feed_file($file_path)
    {
        $file_contents = file_get_contents($file_path);

        if ($file_contents === false) {
            WP_CLI::line(__('Sportshub Games Error: Failed to read the file.', 'SportsHub Games'));

            return null;
        }

        $json_data = json_decode($file_contents, true);

        if ($json_data === null) {
            WP_CLI::line(__('Sportshub Games Error: Failed to decode the JSON.', 'SportsHub Games'));

            return null;
        }

        return $json_data;
    }

    public function getKnupSportsType() {
        $types = get_field('shg_content_types_members', 'options');
        if (!is_array($types) || count($types) == 0) return [];

        foreach ($types as $key => $type) {
            if ($type['shg_content_type_slug_members'] == 'knup_sports') {
                return $type;
            }
        }

        return [];
    }

    public function getKnupSportsContent($game) {
        $knup_data = [];
        $knup_type = [];
        $knup_content = '';

        if (isset($game['knup_preview']) && !empty($game['knup_preview'])) {
            $knup_data[0] = [
                'date' => $game['date'],
                'body' => $game['knup_preview'],
                'team-home' => $game['home_team'],
                'team-visitor' => $game['away_team'],
            ];

            $knup_type = $this->getKnupSportsType();

            if (is_array($knup_type) && isset($knup_type['shg_content_type_slug_members']) && !empty($knup_type['shg_content_type_slug_members']) && isset($knup_type['shg_content_type_title_members']) && !empty($knup_type['shg_content_type_title_members'])) {
                $knup_content = $this->generateContentMembers($knup_data, $knup_type['shg_content_type_slug_members'], $knup_type['shg_content_type_title_members']);
            }
        }

        return $knup_content;
    }
}
