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

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

        $author_general_id = 1;
        $author_general = null;
        $sports_authors = get_field('shg_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['shg_sport_user'.$suffix]);

                if (empty($post_author)) continue;

                if ($author['shg_sport'.$suffix] == 0) {
                    $author_general = $author['shg_sport_user'.$suffix];
                    continue;
                } else {
                    $authors[$author['shg_sport'.$suffix]] = $author['shg_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('shg_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['shg_game'.$suffix]);
                if (empty($game['shg_game'.$suffix]) || empty($post_game) || 'trash' == $post_game->post_status) continue;

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

        $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'.$suffix, 'options')) && count(get_field('shg_sports_leagues'.$suffix, 'options')) > 0)
            ? get_field('shg_sports_leagues'.$suffix, 'options')
            : null;

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

                if (isset($sport['shg_sport_league'.$suffix]) && !empty($sport['shg_sport_league'.$suffix])) {
                    if (strpos($sport['shg_sport_league'.$suffix], '-')) {
                        list($sport_id, $league_id) = explode('-', $sport['shg_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['shg_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 = 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;
        }
        
        if (empty(get_option('shg_source')) || get_option('shg_source') == 'members') {
            $shg_request = $this->get_api_request($sports_leagues_array, $sports_leagues_parts);

            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 (!empty($parse_results)) {
                    $new_post = 0;
                    $existing_post = 0;
                    $cpt_slug = get_option('shg_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'])).' Picks and Predictions';
                        }
        
                        $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'));
                            $args['meta_input']['shg_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: %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 {
            $shg_request = $this->get_api_request_masterfeed($sports_leagues_array);

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

                                        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($content['date']))).' '.date('jS Y', strtotime($content['date']));
                                                } catch (\Exception $exception) {
                                                    error_log(print_r([
                                                        'game_date', $content['date'],
                                                        'exception', $exception->getMessage()
                                                    ], true));
                                                }
                                                $title .= (!empty($title_date)) ? $title_date : '';
                                                $args['post_title'] = $title;
                                        }

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

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

        return $teams_array;
    }

    public function generate_content($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);
        }

        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: 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_data($post_id, $args, $attributes = [])
    {
        if (isset($attributes['data']['game_date'])) {
            $args['meta_input']['shg_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']['shg_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']['shg_league'] = $attributes['data']['league'];
        }

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

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

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

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

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

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

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

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

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

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

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

        if (isset($attributes['data']['visitor_image']) && $attributes['data']['visitor_image'] != '') {
            $args['meta_input']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_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']['shg_opener_spread_visitor_odds'] = $attributes['data']['opener_game_odds'][0]['spread_visitor_odds'];
        }

        return $args;
    }

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

        if (isset($content['date'])) {
            $args['meta_input']['shg_game_date'] = $content['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($sports_leagues, $parts)
    {
        $api_request = '';
        $api_url = get_field('sportshub_api_url', 'options');
        $api_token = get_field('sportshub_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_api_masterfeed_url', 'options');
        $api_token = get_field('sportshub_api_masterfeed_token', 'options');
        $content_types = get_field('shg_content_types', 'options');

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

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

    public function get_api_request_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_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' => '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 team image data
            $home_image = $helpers->getNameFile($args['meta_input']['shg_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']['shg_home_local_url'] = $attachment_home_check[0]['guid'];
                } else {
                    $args['meta_input']['shg_home_local_url'] = $attachment_home_check[0]['guid'];
                }
            }

            # Get visitor team image data
            $visitor_image = $helpers->getNameFile($args['meta_input']['shg_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']['shg_visitor_local_url'] = $attachment_visitor_check[0]['guid'];
                } else {
                    $args['meta_input']['shg_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'));
            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' => '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;
    }
}
