<?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')));
            WP_CLI::line(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;

        $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;
        }

        $main_games = [];
        $main_game_id = null;
        $sports_main_games = get_field('shg_sports_main_games', 'options');

        if (is_array($sports_main_games) && count($sports_main_games) > 0) {
            foreach ($sports_main_games as $sport => $game) {
                $post_game = get_post($game['shg_game']);
                if (empty($game['shg_game']) || empty($post_game) || 'trash' == $post_game->post_status) continue;

                if ($game['shg_sport'] == 0) {
                    $main_game_id = $game['shg_game'];
                    continue;
                } else {
                    $main_games[$game['shg_sport']] = $game['shg_game'];
                }
            }
        }

        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;
        }

        $main_games = shMappingAuthorsMainsSportsLeaguesConverter($main_games, $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;
                    $cpt_slug = get_option('shg_slug');

                    foreach ($parse_results as $sports_leagues) {
                        if (is_array($sports_leagues['games']) && count($sports_leagues['games']) > 0) {
                            foreach ($sports_leagues['games'] as $games) {
                                if (isset($games['big_master_feed']['sports_direct']) && is_array($games['big_master_feed']['sports_direct']) && count($games['big_master_feed']['sports_direct']) > 0) {
                                    $game = $games['big_master_feed']['sports_direct'];

                                    // error_log(print_r([
                                    //     'authors' => $authors,
                                    //     'id_sport' => $games['id_sport'],
                                    //     'id_league' => $games['id_league'],
                                    // ], true));
                                    // error_log(print_r($game, true));
                                    //return;
                                    
                                    if (!isset($game['home']) || !is_array($game['home']) || count($game['home']) == 0) {
                                        return;
                                    }

                                    if (!isset($game['visitor']) || !is_array($game['visitor']) || count($game['visitor']) == 0) {
                                        return;
                                    }

                                    if (!isset($games['big_master_feed']['field_level_media'])) {
                                        return;
                                    }

                                    $data_types = $games['big_master_feed']['field_level_media'];

                                    $home_name = $this->getTeamName($game['home']);
                                    $visitor_name = $this->getTeamName($game['visitor']);
                                    $post_title = $this->getPostTitle($home_name, $visitor_name);

                                    $title_date = '';
                    
                                    try {
                                        $title_date = date('F jS Y', strtotime($game['start_date']));
                                    } catch (\Exception $exception) {
                                        error_log(print_r([
                                            'start_date', $game['start_date'],
                                            'exception', $exception->getMessage()
                                        ], true));
                                    }

                                    if (!empty($title_date)) {
                                        $post_title .= ' '.$title_date;
                                    }

                                    $status_content = $this->getContentMembers($data_types);
                                    //error_log(print_r([$status_content], true));
                                    //continue;

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

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

                                    $attributes = [
                                        'data' => $game,
                                        'authors' => $authors,
                                        'main_games' => $main_games,
                                        'games' => $games,
                                        'handicappers' => $sports_leagues['handicappers']
                                    ];

                                    $args = $this->parse_data($post_id, $args, $attributes);
                                    // error_log(print_r($args, true));
                                    // return;
                                    $response = $this->insert_auto_post($args, $cpt_slug, $attributes);

                                    //return;

                                    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));
                    }
                } 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)) {
                                        $cpt_slug = get_option('shg_slug');

                                        $post_title = 'Game Title';
                                        $post_name = $post_title;
                                        if (isset($content['title']) && !empty($content['title'])) {
                                            $post_title = ucfirst(strtolower($content['title']));
                                        }

                                        $args = [
                                            'post_title'    => $post_title,
                                            'post_name'     => $post_name,
                                            'post_type'     => $cpt_slug,
                                            'post_status'   => 'publish',
                                            'post_author'   => $author_general_id,
                                            'post_parent'   => $main_game_id,
                                            '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']];
                                                }
                                            }
                                        }

                                        $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, $cpt_slug);
                                        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'));
    }

    public function getContentMembers($data_types)
    {
        $content = '';
        $count_types = 0;
        $contents = [];
        
        $types = get_field('shg_content_types_members', 'options');
        $max_types = count($types);

        foreach ($types as $type) {
            if (isset($data_types[$type['shg_content_type_slug_members']][0]['body']) && !empty($data_types[$type['shg_content_type_slug_members']][0]['body'])) {
                $count_types++;
                $content .= $this->generateContentMembers($data_types[$type['shg_content_type_slug_members']], $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' => 'publish',
                'post_content' => $content,
            ];
        }

        if ($count_types > 0 && $count_types < $max_types && $contents['preview'] == true) {
            return [
                'post_status' => 'publish',
                '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 $nickname.' '.$name;
        }

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

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

    public function getPostTitle($home_team, $visitor_team)
    {
        if (empty($home_team)) {
            $home_team = 'name home team';
        }

        if (empty($visitor_team)) {
            $visitor_team = 'name visitor team';
        }

        return ucwords(strtolower($home_team)).' vs '.ucwords(strtolower($visitor_team)).' Picks and Predictions';
    }

    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;
                    }
                }
            }
        }

        return implode('', $paragraphs_content);
    }

    public function getTitle($template, $content)
    {
        try {
            $template = str_replace('[date]', date('F jS Y', strtotime($content[0]['date'])), $template);
            $template = str_replace('[title]', $content[0]['title'], $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';
        }

        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'] = $data['over_under']['game_id'];
        $args['meta_input']['shg_external_id_odds'] = $data['over_under']['external_id'];
        $args['meta_input']['shg_sportsbook_odds'] = $data['over_under']['sportsbook'];
        $args['meta_input']['shg_date_odds'] = $data['over_under']['date'];

        return $args;
    }

    public function parse_data($post_id, $args, $attributes = [])
    {
        $games = $attributes['games'];
        $game = $games['big_master_feed']['sports_direct'];

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

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

        if (isset($games['id_league'])) {
            $args['meta_input']['shg_league'] = $games['id_league'];
        }

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

            if (is_array($attributes['authors']['leagues']) && isset($attributes['authors']['leagues'][$games['id_league']])) {
                $args['post_author'] = $attributes['authors']['leagues'][$games['id_league']];
            } elseif (is_array($attributes['authors']['sports']) && isset($attributes['authors']['sports'][$games['id_sport']])) {
                $args['post_author'] = $attributes['authors']['sports'][$games['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'][$games['id_league']])) {
                    $args['post_parent'] = $attributes['main_games']['leagues'][$games['id_league']];
                } elseif (is_array($attributes['main_games']['sports']) && isset($attributes['main_games']['sports'][$games['id_sport']])) {
                    $args['post_parent'] = $attributes['main_games']['sports'][$games['id_sport']];
                }
            }
        }

        if (isset($game['category_name'])) {
            $args['meta_input']['shg_category'] = $game['category_name'];
        }

        $args['meta_input']['shg_game_url'] = 'https://members.sportshub.com/games-picks/'.$post_id;

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

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

        if (isset($game['home']['name']) && $game['home']['name'] != '') {
            $args['meta_input']['shg_home_city'] = $game['home']['name'];
        }

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

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

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

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

        if (isset($game['visitor']['name']) && $game['visitor']['name'] != '') {
            $args['meta_input']['shg_visitor_city'] = $game['visitor']['name'];
        }

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

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

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

        if (isset($games['game_stat'])) {
            $args['meta_input']['shg_game_stat'] = $games['game_stat'];
        }

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

        if (isset($attributes['handicappers'][0]) && is_array($attributes['handicappers'][0])) {
            $args['meta_input']['shg_game_top_handicapper_id'] = $attributes['handicappers'][0]['id_handicapper'];
            $args['meta_input']['shg_game_top_handicapper_name'] = $attributes['handicappers'][0]['handicapper']['name'];
            $args['meta_input']['shg_game_top_handicapper_api_image'] = $attributes['handicappers'][0]['image'];
            $args['meta_input']['shg_game_top_handicapper_description'] = $attributes['handicappers'][0]['description'];
            $args['meta_input']['shg_game_results_rank'] = $attributes['handicappers'][0]['rank'];
            $args['meta_input']['shg_game_results_sport_name'] = $attributes['handicappers'][0]['sport_name'];

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

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

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

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

            if (isset($attributes['handicappers'][0]['picks']) && is_array($attributes['handicappers'][0]['picks']) && count($attributes['handicappers'][0]['picks']) > 0) {
                $data = $attributes['handicappers'][0]['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;
                    }
                }
            }
        }

        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['league_id'])) {
            $args['meta_input']['shg_category'] = $content['league_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($teams[$content['home_team_id']]['city']) && !empty(isset($teams[$content['home_team_id']]['city']))) {
                    $args['meta_input']['shg_home_city'] = $teams[$content['home_team_id']]['city'];
                }
            }
        }

        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($teams[$content['visitor_team_id']]['city']) && !empty(isset($teams[$content['visitor_team_id']]['city']))) {
                    $args['meta_input']['shg_visitor_city'] = $teams[$content['visitor_team_id']]['city'];
                }
            }
        }

        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_parent_game($attributes) {
        if (isset($attributes['data']['sport']) && !empty($attributes['data']['sport']) && isset($attributes['data']['category']) && !empty($attributes['data']['category'])) {
            $key = $attributes['data']['sport'].'-'.$attributes['data']['category'];

            if (isset($attributes['main_games'][$key])) {
                return $attributes['main_games'][$key];
            }
        }

        if (isset($attributes['data']['sport']) && !empty($attributes['data']['sport'])) {
            $key = $attributes['data']['sport'];

            if (isset($attributes['main_games'][$key])) {
                return $attributes['main_games'][$key];
            }
        }

        return null;
    }

    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');

        /*error_log(print_r([
            'api_base' => $api_base,
            'api_token' => $api_token,
            'content_types' => $content_types,
            'sports_leagues' => $sports_leagues,
        ], true));*/

        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=2023-10-24';
                $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));
                        }
                    }
                }
            }
        }

        /*error_log(print_r([
            'api_base' => $api_base,
            'api_token' => $api_token,
            'content_types' => $content_types,
            'sports_leagues' => $sports_leagues,
            'api_requests' => $api_requests,
            'sports_categories' => $sports_categories,
        ], 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');

        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 [];
        }

        // error_log(print_r([
        //     'sports_leagues' => $sports_leagues,
        // ], true));

        // return;

        $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=2024-03-03';

        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_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 insert_auto_post($args, $cpt_slug, $attributes)
    {
        wp_reset_postdata();

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

        $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 (!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);
                    }
                }

                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
            $data_types = $attributes['games']['big_master_feed']['field_level_media'];
            $status_content = $this->getContentMembers($data_types);

            $new_data['post_status'] = $status_content['post_status'];
            $new_data['post_content'] = $status_content['post_content'];

            #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);

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

    public function updateBlockTopHandicapperOddsData($new_data, $args) 
    {
        $new_data['meta_input']['shg_home_handicap_spread_odds'] = $args['meta_input']['shg_home_handicap_spread_odds'];
        $new_data['meta_input']['shg_away_handicap_spread_odds'] = $args['meta_input']['shg_away_handicap_spread_odds'];
        $new_data['meta_input']['shg_home_spread_odds'] = $args['meta_input']['shg_home_spread_odds'];
        $new_data['meta_input']['shg_away_spread_odds'] = $args['meta_input']['shg_away_spread_odds'];
        $new_data['meta_input']['shg_home_money_odds'] = $args['meta_input']['shg_home_money_odds'];
        $new_data['meta_input']['shg_away_money_odds'] = $args['meta_input']['shg_away_money_odds'];
        $new_data['meta_input']['shg_home_handicap_overunder_odds'] = $args['meta_input']['shg_home_handicap_overunder_odds'];
        $new_data['meta_input']['shg_away_handicap_overunder_odds'] = $args['meta_input']['shg_away_handicap_overunder_odds'];
        $new_data['meta_input']['shg_home_overunder_odds'] = $args['meta_input']['shg_home_overunder_odds'];
        $new_data['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_stat' => $args['meta_input']['shg_game_stat'],
                'shg_game_picks_count' => $args['meta_input']['shg_game_picks_count'],
                '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)
    {
        $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]['guid'];
            } else {
                return $attachment_check[0]['guid'];
            }
        }

        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;
    }
}
