<?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_recap details
 * 
 * HELPER COMMENT END
 */

WP_CLI::add_command('sportshub_games_recaps', 'Sportshub_Games_Recaps_CLI');

/**
 * Class Sportshub_Games_Recaps_CLI
 *
 * This class contains all WP CLI related features.
 *
 * @package         SHGAMESR
 * @subpackage      Classes/Sportshub_Games_Recaps_CLI
 * @author          IT
 * @since           1.0.0
 */
class Sportshub_Games_Recaps_CLI extends WP_CLI_Command {
    function __construct() {
    }

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

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

            return;
        }

        if (empty(get_option('shgr_source')) || get_option('shgr_source') == 'members') {
            $suffix = '';
        } else {
            $suffix = '_masterfeed';
        }

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

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

                if (empty($post_author)) continue;

                if ($author['shgr_sport'.$suffix] == 0) {
                    $author_general = $author['shgr_sport_user'.$suffix];
                    continue;
                } else {
                    $authors[$author['shgr_sport'.$suffix]] = $author['shgr_sport_user'.$suffix];
                }
            }
        }

        $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('shgr_sports_main_games'.$suffix, 'options');
        
        if (is_array($sports_main_games) && count($sports_main_games) > 0) {
            foreach ($sports_main_games as $sport => $game) {
                $post_game = get_post($game['shgr_game'.$suffix]);
                if (empty($game['shgr_game'.$suffix]) || empty($post_game) || 'trash' == $post_game->post_status) continue;

                if ($game['shgr_sport'.$suffix] == 0) {
                    $main_game_id = $game['shgr_game'.$suffix];
                    continue;
                } else {
                    $main_games[$game['shgr_sport'.$suffix]] = $game['shgr_game'.$suffix];
                }
            }
        }

        $sports_leagues_parts = [];
        $sports_leagues_data = (is_array(get_field('shgame_recaps_sports_and_leagues', 'options')) && count(get_field('shgame_recaps_sports_and_leagues', 'options')) > 0)
            ? get_field('shgame_recaps_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['shgr_sport_id']) && !empty($sport_part['shgr_sport_id']) && isset($sport_part['shgr_game_parts']) && !empty($sport_part['shgr_game_parts'])) {
                    $sports_leagues_parts[$sport_part['shgr_sport_id']] = $sport_part['shgr_game_parts'];
                }
            }
        }

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

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

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

                        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['shgr_sport_league'.$suffix];
                        
                        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 = SHGAMESR_PLUGIN_LOG_DIR . '/' . $filename;

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

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

            return;
        }

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

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

            return;
        }
        
        if (empty(get_option('shgr_source')) || get_option('shgr_source') == 'members') {
            $shgr_request = $this->get_api_request($sports_leagues_array, $sports_leagues_parts);

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

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

                if (!empty($parse_results)) {
                    $new_post = 0;
                    $existing_post = 0;
                    $cpt_slug = get_option('shgr_slug');
        
                    foreach ($parse_results as $game_picks) {
                        $post_title = 'Game Title';
                        if (isset($game_picks['visitor_team']) && !empty($game_picks['visitor_team']) && isset($game_picks['home_team']) && !empty($game_picks['visitor_team'])) {
                            $post_title = ucfirst(strtolower($game_picks['visitor_team'])).' vs '.ucfirst(strtolower($game_picks['home_team'])).' Recaps';
                        }
        
                        $title_date = '';
        
                        try {
                            $title_date = date('F jS Y', strtotime($game_picks['game_date']));
                        } catch (\Exception $exception) {
                            error_log(print_r([
                                'game_date', $game_picks['game_date'],
                                'exception', $exception->getMessage()
                            ], true));
                        }
        
                        if (!empty($title_date)) {
                            $post_title .= ' '.$title_date;
                        }
        
                        $args = [
                            'post_title'    => $post_title,
                            'post_type'     => $cpt_slug,
                            'post_status'   => 'publish',
                            'post_author'   => $author_general_id,
                            'post_parent'   => $main_game_id,
                        ];
        
                        $post_id = '';
                        if (isset($game_picks['id_game'])) {
                            WP_CLI::line(__('External ID: '. $game_picks['id_game'], 'SportsHub Games Recaps'));
                            $args['meta_input']['shgr_external_id'] = $game_picks['id_game'];
                            $post_id = $game_picks['id_game'];
                        }
        
                        $attributes = [
                            'data' => $game_picks,
                            'authors' => $authors,
                            'main_games' => $main_games,
                        ];
        
                        $args = $this->parse_data($post_id, $args, $attributes);
                        $response = $this->insert_auto_post($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']);
                            }
                        }
                    }
        
                    error_log(sprintf(__('SportsHub Games Recaps: %s Succesfully inserted posts.', 'SportsHub Games Recaps'), $new_post));
                    WP_CLI::line(sprintf(__('%s Succesfully inserted posts.', 'SportsHub Games Recaps'), $new_post));
        
                    if ($existing_post > 0) {
                        error_log(sprintf(__('SportsHub Games Recaps: %s Existing posts.', 'SportsHub Games Recaps'), $existing_post));
                        WP_CLI::line(sprintf(__('%s Existing posts.', 'SportsHub Games Recaps'), $existing_post));
                    }
                } else {
                    error_log('SportsHub Games Recaps: No data available for this pull.');
                    WP_CLI::line(__('No data available for this pull', 'SportsHub Games Recaps'));
                }
            } else {
                return;
            }
        } else {
            $shgr_request = $this->get_api_request_masterfeed($sports_leagues_array);

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

                return;
            }

            foreach ($shgr_request['requests'] as $key =>  $request) {
                if (!empty($request)) {
                    $sport = $shgr_request['sports'][$key]['sport'];
                    $category = $shgr_request['sports'][$key]['category'];
                    $type = $shgr_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 = SHGAMESR_PLUGIN_LOG_DIR . '/' . $filename;

                    WP_CLI::line(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games Recaps'), $request));
                    error_log(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games Recaps'), $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('shgr_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->generate_content($content['body']),
                                        ];

                                        $sport_key = (!empty($category)) ? $sport.'-'.$category : $sport;
                                        if (is_array($authors) && isset($authors[$sport_key]) && !empty($authors[$sport_key])) {
                                            $args['post_author'] = $authors[$sport_key];
                                        }

                                        if (is_array($main_games) && isset($main_games[$sport_key]) && !empty($main_games[$sport_key])) {
                                            $args['post_parent'] = $main_games[$sport_key];
                                        }

                                        $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.',
                                                'shgr_external_id' => (isset($args['meta_input']['shgr_external_id'])) ? $args['meta_input']['shgr_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 .= ' Recap ';

                                                try {
                                                    $title_date = '';
                                                    $title_date = strtoupper(date('F', strtotime($args['meta_input']['shgr_game_date']))).' '.date('jS Y', strtotime($args['meta_input']['shgr_game_date']));
                                                } catch (\Exception $exception) {
                                                    error_log(print_r([
                                                        'game_date', $args['meta_input']['shgr_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 Recaps: No data available for this pull.');
                                        WP_CLI::line(__('No data available for this pull', 'SportsHub Games Recaps'));
                                    }
                                }

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

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

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

    public function is_valid_args_simple($args)
    {
        $validate = true;
        $fields_required = [
            'shgr_external_id',
            'shgr_sport_id',
            'shgr_game_date',
            'shgr_id_home_team',
            'shgr_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 = SHGAMESR_PLUGIN_LOG_DIR . '/' . $filename_teams;
        $helpers = New Sportshub_Games_Recaps_Helpers;

        if ($helpers->initRedis()) {
            $helpers->setRedisGroup(REDIS_GROUP_SHGAMESR);
            $key = $helpers->getRedisKeyTeams();
            $teams = $helpers->getRedis($key);
    
            if (!empty($teams)) {
                return unserialize($teams);
            }
        }

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

        return $teams_array;
    }

    public function get_games_data()
    {
        $games_array = [];
        $filename_games =  'SPORTS_HUB_GAMES_INFO.json';
        $file_path_games = SHGAMESR_PLUGIN_LOG_DIR . '/' . $filename_games;
        $helpers = New Sportshub_Games_Recaps_Helpers;

        if ($helpers->initRedis()) {
            $helpers->setRedisGroup(REDIS_GROUP_SHGAMESR);
            $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), SHGAMESR_REDIS_TIMEOUT);
                }
            }
        }

        return $games_array;
    }

    public function generate_content($content)
    {
        $block_init = '<!-- wp:paragraph --><p class="shgr-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);
        }

        return implode('', $paragraphs_content);
    }

    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 Recaps: ERROR: %s.', 'SportsHub Games Recaps'), curl_error($ch)));
            WP_CLI::line(sprintf(__('ERROR: %s.', 'SportsHub Games Recaps'), curl_error($ch)));
        } else {
            file_put_contents($file_path, $response);
            curl_close($ch);

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

            return true;
        }

        return false;
    }

    public function parse_data($post_id, $args, $attributes = [])
    {
        if (isset($attributes['data']['game_date'])) {
            $args['meta_input']['shgr_game_date'] = $attributes['data']['game_date'];
        }

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

        if (isset($attributes['data']['sport'])) {
            $args['meta_input']['shgr_sport_id'] = $attributes['data']['sport'];

            if (is_array($attributes['authors']) && isset($attributes['authors'][$attributes['data']['sport']]) && !empty($attributes['authors'][$attributes['data']['sport']])) {
                $args['post_author'] = $attributes['authors'][$attributes['data']['sport']];
            }

            if (is_array($attributes['main_games']) && count($attributes['main_games']) > 0) {
                $parent = $this->get_parent_game($attributes);
                if (!empty($parent)) {
                    $args['post_parent'] = $parent;
                }
            }
        }

        if (isset($attributes['data']['league'])) {
            $args['meta_input']['shgr_league'] = $attributes['data']['league'];
        }

        if (isset($attributes['data']['category'])) {
            $args['meta_input']['shgr_category'] = $attributes['data']['category'];
        }

        if (isset($attributes['data']['game_stat'])) {
            $args['meta_input']['shgr_game_stat'] = $attributes['data']['game_stat'];
        }

        if (isset($attributes['data']['game_picks_count'])) {
            $args['meta_input']['shgr_game_picks_count'] = $attributes['data']['game_picks_count'];
        }

        if (isset($attributes['data']['game_url'])) {
            $args['meta_input']['shgr_game_url'] = $attributes['data']['game_url'];
        }

        if (isset($attributes['data']['id_home_team']) && $attributes['data']['id_home_team'] != '') {
            $args['meta_input']['shgr_id_home_team'] = $attributes['data']['id_home_team'];
        }

        if (isset($attributes['data']['home_team']) && $attributes['data']['home_team'] != '') {
            $args['meta_input']['shgr_home_team'] = $attributes['data']['home_team'];
        }

        if (isset($attributes['data']['home_score']) && $attributes['data']['home_score'] != '') {
            $args['meta_input']['shgr_home_score'] = $attributes['data']['home_score'];
        }

        if (isset($attributes['data']['home_image']) && $attributes['data']['home_image'] != '') {
            $args['meta_input']['shgr_home_image'] = $attributes['data']['home_image'];
        }

        if (isset($attributes['data']['id_visitor_team']) && $attributes['data']['id_visitor_team'] != '') {
            $args['meta_input']['shgr_id_visitor_team'] = $attributes['data']['id_visitor_team'];
        }

        if (isset($attributes['data']['visitor_team']) && $attributes['data']['visitor_team'] != '') {
            $args['meta_input']['shgr_visitor_team'] = $attributes['data']['visitor_team'];
        }

        if (isset($attributes['data']['visitor_score']) && $attributes['data']['visitor_score'] != '') {
            $args['meta_input']['shgr_visitor_score'] = $attributes['data']['visitor_score'];
        }

        if (isset($attributes['data']['visitor_image']) && $attributes['data']['visitor_image'] != '') {
            $args['meta_input']['shgr_visitor_image'] = $attributes['data']['visitor_image'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['money_line_home_odds']) && $attributes['data']['current_game_odds'][0]['money_line_home_odds'] != '') {
            $args['meta_input']['shgr_current_money_line_home_odds'] = $attributes['data']['current_game_odds'][0]['money_line_home_odds'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['money_line_visitor_odds']) && $attributes['data']['current_game_odds'][0]['money_line_visitor_odds'] != '') {
            $args['meta_input']['shgr_current_money_line_visitor_odds'] = $attributes['data']['current_game_odds'][0]['money_line_visitor_odds'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['total_over_points']) && $attributes['data']['current_game_odds'][0]['total_over_points'] != '') {
            $args['meta_input']['shgr_current_total_over_points'] = $attributes['data']['current_game_odds'][0]['total_over_points'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['total_over_odds']) && $attributes['data']['current_game_odds'][0]['total_over_odds'] != '') {
            $args['meta_input']['shgr_current_total_over_odds'] = $attributes['data']['current_game_odds'][0]['total_over_odds'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['total_under_points']) && $attributes['data']['current_game_odds'][0]['total_under_points'] != '') {
            $args['meta_input']['shgr_current_total_under_points'] = $attributes['data']['current_game_odds'][0]['total_under_points'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['total_under_odds']) && $attributes['data']['current_game_odds'][0]['total_under_odds'] != '') {
            $args['meta_input']['shgr_current_total_under_odds'] = $attributes['data']['current_game_odds'][0]['total_under_odds'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['spread_home_points']) && $attributes['data']['current_game_odds'][0]['spread_home_points'] != '') {
            $args['meta_input']['shgr_current_spread_home_points'] = $attributes['data']['current_game_odds'][0]['spread_home_points'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['spread_home_odds']) && $attributes['data']['current_game_odds'][0]['spread_home_odds'] != '') {
            $args['meta_input']['shgr_current_spread_home_odds'] = $attributes['data']['current_game_odds'][0]['spread_home_odds'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['spread_visitor_points']) && $attributes['data']['current_game_odds'][0]['spread_visitor_points'] != '') {
            $args['meta_input']['shgr_current_spread_visitor_points'] = $attributes['data']['current_game_odds'][0]['spread_visitor_points'];
        }

        if (isset($attributes['data']['current_game_odds'][0]['spread_visitor_odds']) && $attributes['data']['current_game_odds'][0]['spread_visitor_odds'] != '') {
            $args['meta_input']['shgr_current_spread_visitor_odds'] = $attributes['data']['current_game_odds'][0]['spread_visitor_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['money_line_home_odds']) && $attributes['data']['opener_game_odds'][0]['money_line_home_odds'] != '') {
            $args['meta_input']['shgr_opener_money_line_home_odds'] = $attributes['data']['opener_game_odds'][0]['money_line_home_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['money_line_visitor_odds']) && $attributes['data']['opener_game_odds'][0]['money_line_visitor_odds'] != '') {
            $args['meta_input']['shgr_opener_money_line_visitor_odds'] = $attributes['data']['opener_game_odds'][0]['money_line_visitor_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['total_over_points']) && $attributes['data']['opener_game_odds'][0]['total_over_points'] != '') {
            $args['meta_input']['shgr_opener_total_over_points'] = $attributes['data']['opener_game_odds'][0]['total_over_points'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['total_over_odds']) && $attributes['data']['opener_game_odds'][0]['total_over_odds'] != '') {
            $args['meta_input']['shgr_opener_total_over_odds'] = $attributes['data']['opener_game_odds'][0]['total_over_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['total_under_points']) && $attributes['data']['opener_game_odds'][0]['total_under_points'] != '') {
            $args['meta_input']['shgr_opener_total_under_points'] = $attributes['data']['opener_game_odds'][0]['total_under_points'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['total_under_odds']) && $attributes['data']['opener_game_odds'][0]['total_under_odds'] != '') {
            $args['meta_input']['shgr_opener_total_under_odds'] = $attributes['data']['opener_game_odds'][0]['total_under_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['spread_home_points']) && $attributes['data']['opener_game_odds'][0]['spread_home_points'] != '') {
            $args['meta_input']['shgr_opener_spread_home_points'] = $attributes['data']['opener_game_odds'][0]['spread_home_points'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['spread_home_odds']) && $attributes['data']['opener_game_odds'][0]['spread_home_odds'] != '') {
            $args['meta_input']['shgr_opener_spread_home_odds'] = $attributes['data']['opener_game_odds'][0]['spread_home_odds'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['spread_visitor_points']) && $attributes['data']['opener_game_odds'][0]['spread_visitor_points'] != '') {
            $args['meta_input']['shgr_opener_spread_visitor_points'] = $attributes['data']['opener_game_odds'][0]['spread_visitor_points'];
        }

        if (isset($attributes['data']['opener_game_odds'][0]['spread_visitor_odds']) && $attributes['data']['opener_game_odds'][0]['spread_visitor_odds'] != '') {
            $args['meta_input']['shgr_opener_spread_visitor_odds'] = $attributes['data']['opener_game_odds'][0]['spread_visitor_odds'];
        }

        return $args;
    }

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

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

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

        if (isset($content['league_id'])) {
            $args['meta_input']['shgr_category'] = $content['league_id'];
        }

        if (isset($content['home_team_id'])) {
            $args['meta_input']['shgr_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']['shgr_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']['shgr_home_city'] = $teams[$content['home_team_id']]['city'];
                }
            }
        }

        if (isset($content['visitor_team_id'])) {
            $args['meta_input']['shgr_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']['shgr_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']['shgr_visitor_city'] = $teams[$content['visitor_team_id']]['city'];
                }
            }
        }

        if (isset($content['extra_details']['images'][0]['preview_url'])) {
            $args['meta_input']['shgr_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($sports_leagues, $parts)
    {
        $api_request = '';
        $api_url = get_field('sportshub_recap_api_url', 'options');
        $api_token = get_field('sportshub_recap_api_token', 'options');
        $date = date('Y-m-d');

        $api_url = (substr($api_url, -1) == '/') ? substr($api_url, 0, strlen($api_url) -1) : $api_url;
        $sports_categories = $this->get_sports_categories_url_params($sports_leagues, $parts);

        $api_url .= '?date='.$date;

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

        //$api_url .= '&recordsQty=5';
        $api_url .= '&completeGames=1';
        $api_request = $api_url.'&api_token='.$api_token;
        
        return $api_request;
    }

    public function get_api_request_masterfeed($sports_leagues)
    {
        $api_request = '';
        $api_requests = [];
        $sports_categories = [];
        $api_base = get_field('sportshub_recap_api_masterfeed_url', 'options');
        $api_token = get_field('sportshub_recap_api_masterfeed_token', 'options');
        $content_types = get_field('shgr_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([
                'messaje' => sprintf(__('SportsHub Games Recaps: Sports and types content must be configured.', 'SportsHub Games Recaps')),
                '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 .= '&sport_id='.$sport;

                if (is_array($league) && count($league) > 0) {
                    foreach ($league as $cat) {
                        $api_url .= '&league_id='.$cat;

                        foreach ($content_types as $type) {
                            if (is_array($type) && count($type) > 0 && !empty($type['shgr_content_type_slug'])) {
                                $api_url_type = $api_url.'&type='.$type['shgr_content_type_slug'];
                                $api_request = $api_url_type.'&key='.$api_token;
        
                                $api_requests[] = $api_request;
                                $sports_categories[] = [
                                    'sport' => $sport,
                                    'category' => $cat,
                                    'type' => $type['shgr_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['shgr_content_type_slug'])) {
                            $api_url_type = $api_url.'&type='.$type['shgr_content_type_slug'];
                            $api_request = $api_url_type.'&key='.$api_token;
    
                            $api_requests[] = $api_request;
                            $sports_categories[] = [
                                'sport' => $sport,
                                'category' => null,
                                'type' => $type['shgr_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_teams()
    {
        $api_request = '';
        $api_base = (!empty(get_field('shgr_teams_url', 'options')))
            ? get_field('shgr_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('shgr_games_url', 'options')))
            ? get_field('shgr_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)
    {
        wp_reset_postdata();

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

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

        if (!$query->have_posts()) {
            # Get local team image data
            $home_image = $helpers->getNameFile($args['meta_input']['shgr_home_image']);

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

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

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

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

            # Get visitor team image data
            $visitor_image = $helpers->getNameFile($args['meta_input']['shgr_visitor_image']);

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

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

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

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

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

            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 Recaps'));
            return ['type' => 'duplicate', 'post_id' => $post_id, 'message' => ''];
        }
    }

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

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

        $helpers = New Sportshub_Games_Recaps_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']['shgr_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']['shgr_game_local_image'] = $attachment_game_check[0]['guid'];
                    }
                } else {
                    $args['meta_input']['shgr_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']['shgr_id_home_team']) &&
                isset($args['meta_input']['shgr_id_visitor_team']) &&
                isset($teams[$args['meta_input']['shgr_id_home_team']]['name']) && 
                !empty($teams[$args['meta_input']['shgr_id_home_team']]['name']) &&
                isset($teams[$args['meta_input']['shgr_id_visitor_team']]['name']) &&
                !empty($teams[$args['meta_input']['shgr_id_visitor_team']]['name'])
                ) {
                    $name = $teams[$args['meta_input']['shgr_id_home_team']]['name'];
                    $name .= '-vs-';
                    $name .= $teams[$args['meta_input']['shgr_id_visitor_team']]['name'];
                    $name .= '-recap-'.$post_id;
                    
                    $update_data['ID'] = $post_id;
                    $update_data['post_name'] = sanitize_title($name);
                    $update_data['meta_input']['shgr_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 Recaps'));
            return ['type' => 'duplicate', 'post_id' => $post_id, 'message' => ''];
        }
    }

    public function get_content_request($params)
    {
        $api_request = '';
        $content_url = get_field('shgr_content_url', 'option');
        $content_token = get_field('shgr_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 Recaps Error: Failed to read the file.', 'SportsHub Games Recaps'));

            return null;
        }

        $json_data = json_decode($file_contents, true);

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

            return null;
        }

        return $json_data;
    }
}
