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

WP_CLI::add_command('sportshub_recaps', 'Sportshub_Recaps_CLI');

/**
 * Class Sportshub_Recaps_CLI
 *
 * This class contains all WP CLI related features.
 *
 * @package         SHRECAPS
 * @subpackage      Classes/Sportshub_Recaps_CLI
 * @author          IT
 * @since           1.0.0
 */
class Sportshub_Recaps_CLI extends WP_CLI_Command {
    CONST SOURCE_MEMBERS = 'members';
    CONST SOURCE_MASTERFEED = 'masterfeed';
    CONST MODE_SINGLE = 'single';
    CONST MODE_GROUPED = 'grouped';

    function __construct() {
    }

    public function details($args, $assoc_args) {
        WP_CLI::line(sprintf(__('Plugin name: %s', SHRECAPS_NAME_SLUG), SHRECAPS_NAME));
        WP_CLI::line(sprintf(__('Plugin version: %s', SHRECAPS_NAME_SLUG), SHRECAPS_VERSION));
    }

    public function pull($args, $assoc_args)
    {
        if (get_option('shr_status') != 1) {
            error_log(sprintf(__('Sportshub Recaps CLI: Plugin disabled.', SHRECAPS_NAME_SLUG)));
            WP_CLI::line(sprintf(__('Sportshub Recaps CLI: Plugin disabled.', SHRECAPS_NAME_SLUG)));

            return;
        }

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

            WP_CLI::line(sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary.', SHRECAPS_NAME_SLUG)));

            return;
        }

        // It is validated that the SH Mapping utility plugin is installed.
        if (!function_exists('shMappingSportsLeaguesNamesConverter')) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary. Function shMappingSportsLeaguesNamesConverter is required.', SHRECAPS_NAME_SLUG)),
            ], true));

            WP_CLI::line(sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary. Function shMappingSportsLeaguesNamesConverter is required.', SHRECAPS_NAME_SLUG)));

            return;
        }

        // It is validated that the SH Mapping utility plugin is installed.
        if (!function_exists('shMappingAuthorsMainsSportsLeaguesConverter')) {
            error_log(print_r([
                'message' => sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary. Function shMappingAuthorsMainsSportsLeaguesConverter is required.', SHRECAPS_NAME_SLUG)),
            ], true));

            WP_CLI::line(sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary. Function shMappingAuthorsMainsSportsLeaguesConverter is required.', SHRECAPS_NAME_SLUG)));

            return;
        }

        // The source determines the type of content the post will have.
        $source = (empty(get_option('shr_source')) || get_option('shr_source') == self::SOURCE_MEMBERS) ? self::SOURCE_MEMBERS : self::SOURCE_MASTERFEED;

        // The conversion of possible IDs for both sports and leagues is obtained.
        $sports_leagues_name = shMappingSportsLeaguesNamesConverter($source);

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

        // The list of authors is obtained, as well as the general author.
        if (is_array($sports_authors) && count($sports_authors) > 0) {
            foreach ($sports_authors as $sport => $author) {
                $post_author = get_user_by('ID', $author['shr_sport_user']);

                if (empty($post_author)) continue;

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

        // With the list of authors above, the authors are assigned for each sport and league.
        $authors = shMappingAuthorsMainsSportsLeaguesConverter($authors, $source);

        // The general author ID is assigned.
        $author_general = (isset($author_general)) ? get_user_by('id', $author_general) : null;
        if (!empty($author_general)) {
            $author_general_id = $author_general->ID;
        }

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

        // Get the list of images.
        if (is_array($sports_images) && count($sports_images) > 0) {
            foreach ($sports_images as $sport_image) {
                if (!isset($sport_image['shr_sport']) || !isset($sport_image['shr_image'])) continue;
                $images[$sport_image['shr_sport']] = $sport_image['shr_image'];
            }
        }

        if (isset($images[0])) {
            // If the image is set to sport 0, this is taken as the default image.
            $sport_featured_image_default = $images[0];
            unset($images[0]);
        }

        // Taking the list of images, return the images by sport or league
        $sports_images = shMappingAuthorsMainsSportsLeaguesConverter($images, $source);

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

        // Get the list of parent posts.
        if (is_array($sports_main_games) && count($sports_main_games) > 0) {
            foreach ($sports_main_games as $sport => $game) {
                $post_game = get_post($game['shr_game']);
                if (empty($game['shr_game']) || empty($post_game) || 'trash' == $post_game->post_status) continue;

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

        // From the list of post parents, parents are assigned to each possible IDs by sport or league.
        $main_games = shMappingAuthorsMainsSportsLeaguesConverter($main_games, $source);

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

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

            WP_CLI::line(sprintf(__('Sportshub Recaps CLI: Error while trying to recover the teams.', SHRECAPS_NAME_SLUG)));

            return;
        }

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

        $creation_mode = (!empty(get_field('shr_recaps_creation_mode', 'options'))) 
            ? get_field('shr_recaps_creation_mode', 'options') : self::MODE_SINGLE;

        if ($creation_mode == self::MODE_SINGLE) {
            $title_format = (!empty(get_field('shr_single_title_format', 'options'))) 
                ? get_field('shr_single_title_format', 'options') 
                : '[team-home] vs [team-visitor] [date]';
        } else {
            $title_format = (!empty(get_field('shr_grouped_title_format', 'options'))) 
                ? get_field('shr_grouped_title_format', 'options') 
                : '[sport] - [league] Games [date]';
        }

        if ($source == self::SOURCE_MEMBERS) {
            $sports_leagues_array = [];
            $sports_leagues = (is_array(get_field('shr_sports_leagues', 'options')) && count(get_field('shr_sports_leagues', 'options')) > 0)
                ? get_field('shr_sports_leagues', 'options')
                : null;

            // Get the list of sports and leagues.
            $config_sports = [];
            $config_leagues = [];
            $requests = [];

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

                    if (isset($sport['shr_sport_league']) && !empty($sport['shr_sport_league'])) {
                        if (!strpos($sport['shr_sport_league'], '-')) {
                            $config_sports[$sport['shr_sport_league']] = '';
                            $config_leagues[$sport['shr_sport_league']] = 'League - '.$sport['shr_sport_league'];
                        } else {
                            $config_leagues[$sport['shr_sport_league']] = 'League - '.$sport['shr_sport_league'];
                        }
                    }
                }

                if (is_array($config_leagues) && count($config_leagues) > 0 && is_array($config_sports) && count($config_sports) > 0) {
                    foreach ($config_leagues as $league_id => $league) {
                        $isUnset = false;
                        if (strpos($league_id, '-')) {
                            $isUnset = true;
                            list($sport_id, $league_key) = explode('-', $league_id);
                        } else {
                            $sport_id = $league_id;
                        }

                        if (isset($config_sports[$sport_id]) && $isUnset) {
                            unset($config_leagues[$league_id]);
                        } 
                    }
                }

                if (is_array($config_leagues) && count($config_leagues) > 0) {
                    foreach ($config_leagues as $league_id => $league) {
                        $sports_leagues_converted = shMappingSportsLeaguesConverterSingle($league_id, $source);

                        if (is_array($sports_leagues_converted) && count($sports_leagues_converted) > 0) {
                            $requests[] = $this->get_api_request_members($sports_leagues_converted);
                        }
                    }
                }  
            }

            if (!is_array($requests) || count($requests) == 0) {
                error_log(print_r(sprintf(__('Sportshub Recaps CLI: No data available for this pull.', SHRECAPS_NAME_SLUG)), true));

                return;
            }

            $posts_data = [];

            foreach ($requests as $request) {
                if (is_array($request) && count($request) > 0) {
                    $request_league = null;
                    $shr_request = $request['url'];

                    #TODO: Crear un metodo para obtener el nombre del file
                    $request_sport = isset($request['sport']) ? $request['sport'] : null;
                    $filename = sprintf('SPORTS_HUB_RECAPS_PULL_%s_%s.json', strtoupper($request_sport), date('Y-m-d-H-i-s'));

                    if (isset($request['league']) && !empty($request['league'])) {
                        $request_league = $request['league'];
                        $filename = sprintf('SPORTS_HUB_RECAPS_PULL_%s_%s_%s.json', strtoupper($request_sport), strtoupper($request_league), date('Y-m-d-H-i-s'));
                    }

                    $file_path = SHRECAPS_PLUGIN_LOG_DIR . '/' . $filename;

                    WP_CLI::line(sprintf(__('Sportshub Recaps CLI: Attempting to retrieve data from %s', SHRECAPS_NAME_SLUG), $shr_request));
                    error_log(sprintf(__('Sportshub Recaps CLI: Attempting to retrieve data from %s', SHRECAPS_NAME_SLUG), $shr_request));

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

                        // error_log(print_r(get_option('shr_slug'), true));

                        if (is_array($parse_results) && count($parse_results) > 0) {
                            $new_post = 0;
                            $existing_post = 0;
                            $analyzed_post = 0;
                            $published_post = 0;
                            $cpt_slug = get_option('shr_slug');

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

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

                                        $title_date = '';
                                        $content_title[0]['team-home'] = $game['home_team'];
                                        $content_title[0]['team-visitor'] = $game['away_team'];
                                        $content_title[0]['date'] = $game['date'];
                                        $content_title[0]['sport'] = $request['sport'];
                                        $content_title[0]['league'] = (isset($request['league']) && !empty($request['league'])) ? $request['league'] : '';
                                        $post_title = $this->getTitle($title_format, $content_title);
                                        $status_content = $this->getContentMembers($game);

                                        if ($creation_mode == self::MODE_SINGLE) {
                                            if (!isset($status_content['post_content']) || empty($status_content['post_content'])) {
                                                error_log(print_r([
                                                    'message' => sprintf(__('Sportshub Recaps CLI: The game does not contain the required data.', SHRECAPS_NAME_SLUG)),
                                                    'shr_external_id' => (isset($game['id'])) ? $game['id'] : '',
                                                    'status_content' => $status_content,
                                                ], true));

                                                continue;
                                            }

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

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

                                            $handicapper = $this->getHandicappersData($sports_leagues['handicappers']);

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

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

                                            if (is_array($response) && isset($response['type'])) {
                                                if ($response['type'] == 'new') {
                                                    $new_post++;
                                                } elseif ($response['type'] == 'duplicate') {
                                                    $existing_post++;
                                                } else {
                                                    WP_CLI::Line($response['message']);
                                                }
                                            }
                                        } else {
                                            #TODO: Crear Posts unificados
                                            // error_log(print_r([
                                            //     'date' => $game['date'],
                                            //     'sport' => $game['id_sport'],
                                            //     'league' => $game['league_id'],
                                            //     'title' => $post_title,
                                            //     'request' => $request
                                            // ], true));

                                            // error_log(print_r($game, true));
                                            #TODO: buscar todos los status, pero si esta publicado, no actualizarlo
                                            #TODO: no funciona la busqueda por title, hay que hacer un query custom

                                            try {
                                                #TODO: validar si el title existe en $posts_data, si existe, se salta la consulta
                                                global $wpdb;
                                                $post = null;
                                                $title_slug = sprintf('"%s"', strtolower(str_replace(["'", '"', ' '], '-', $post_title)));

                                                #TODO: debo utilizar $posts_data para identificar la primera vez que se ejecuta el comando en cada post
                                                #TODO: Si $posts_data no tiene ese title, se hace empty el content de ese page grouped

                                                $posts_clear = true;
                                                if (isset($posts_data[$title_slug])) {
                                                    $posts_clear = false;
                                                    $post_grouped_id = $wpdb->get_results($wpdb->prepare("
                                                        SELECT * 
                                                        FROM {$wpdb->posts}
                                                        WHERE post_type = %s
                                                        AND post_status != 'auto-draft'
                                                        AND ID = %s
                                                    ", $cpt_slug, $posts_data[$title_slug]));

                                                    if (isset($post_grouped_id[0]) && is_object($post_grouped_id[0])) {
                                                        $post = $post_grouped_id[0];
                                                    }
                                                } else {
                                                    $post_grouped = $wpdb->get_results($wpdb->prepare("
                                                        SELECT * 
                                                        FROM {$wpdb->posts}
                                                        WHERE post_type = %s
                                                        AND post_status != 'auto-draft'
                                                        AND post_title = %s
                                                    ", $cpt_slug, $post_title));

                                                    if (isset($post_grouped[0]) && is_object($post_grouped[0])) {
                                                        $post = $post_grouped[0];
                                                    }
                                                }

                                                #TODO: Si no es draft, saltar
                                                if (is_object($post) && $post->post_status != 'draft') {
                                                    $published_post++;
                                                    continue;
                                                }

                                                if (is_object($post)) {
                                                    #TODO: agregar el nuevo recap al que ya existe

                                                    //$status_content = $this->getContentMembers($game);
                                                    if (!isset($status_content['post_content']) || empty($status_content['post_content'])) {
                                                        error_log(print_r([
                                                            'message' => sprintf(__('Sportshub Recaps CLI: The game does not contain the required data.', SHRECAPS_NAME_SLUG)),
                                                            'shr_external_id' => (isset($game['id'])) ? $game['id'] : '',
                                                            'status_content' => $status_content,
                                                        ], true));

                                                        continue;
                                                    }

                                                    $new_data = [
                                                        'ID' => $post->ID,
                                                        'post_title'    => $post_title,
                                                        'post_type'     => $cpt_slug,
                                                        'post_status'   => $status_content['post_status'],
                                                        'post_author'   => $author_general_id,
                                                        'post_parent'   => $main_game_id,
                                                        'post_content'  => $post->post_content.$status_content['post_content'],
                                                    ];

                                                    if ($posts_clear) {
                                                        $new_data['post_content'] = $status_content['post_content'];
                                                        $posts_data[$title_slug] = $post->ID;
                                                    }

                                                    # Create CPT Game
                                                    $post_id = wp_update_post($new_data);
                                                    if (!is_wp_error($post_id)) {
                                                        $existing_post++;
                                                        //error_log('Agregar el nuevo recap al que ya existe: '.$post_id);
                                                    }
                                                } else {
                                                    $args = [
                                                        'post_title'    => $post_title,
                                                        'post_type'     => $cpt_slug,
                                                        'post_status'   => $status_content['post_status'],
                                                        'post_author'   => $author_general_id,
                                                        'post_parent'   => $main_game_id,
                                                        'post_content'  => $status_content['post_content'],
                                                    ];

                                                    # Create CPT Game
                                                    $post_id = wp_insert_post($args);
                                                    if (!is_wp_error($post_id)) {
                                                        $posts_data[$title_slug] = $post_id;
                                                        // $post = get_post($post_id);
                                                        $new_post++;
                                                    }
                                                }
                                            } catch (\Exception $exception) {
                                                //throw $exception;
                                            }

                                            /*else {
                                                $args = [
                                                    'post_title'    => $post_title,
                                                    'post_type'     => $cpt_slug,
                                                    'post_status'   => $status_content['post_status'],
                                                    'post_author'   => $author_general_id,
                                                    'post_parent'   => $main_game_id,
                                                    'post_content'  => $analyzed_post.' + ',
                                                ];

                                                # Create CPT Game
                                                $post_id = wp_insert_post($args);
                                                if (!is_wp_error($post_id)) {
                                                    $posts_data["'".$post_title."'"] = $post_id;
                                                    // $post = get_post($post_id);
                                                }
                                            }*/

                                            // $query = new WP_Query(['post_type' => $cpt_slug, 'post_title' => $post_title]);

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

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

                                            //         error_log(print_r([
                                            //             'post' => get_the_title(),
                                            //         ], true));  

                                            //         $posts_data["'".get_the_title()."'"] = get_the_ID();
                                            //         wp_reset_postdata();
                                            //     }
                                            // }

                                            //------------------------------------------------------------------

                                            // if ($query->have_posts()) {
                                            //     // error_log(print_r([
                                            //     //     'edit' => '11111111111',
                                            //     //     // 'post_title' => $post_title,
                                            //     //     // 'post_ID' => $post->ID,
                                            //     // ], true));  
                                            // } else {
                                            //     $args = [
                                            //         'post_title'    => $post_title,
                                            //         'post_type'     => $cpt_slug,
                                            //         'post_status'   => $status_content['post_status'],
                                            //         'post_author'   => $author_general_id,
                                            //         'post_parent'   => $main_game_id,
                                            //         'post_content'  => $analyzed_post.' + ',
                                            //     ];

                                            //     # Create CPT Game
                                            //     $post_id = wp_insert_post($args);
                                            //     if (!is_wp_error($post_id)) {
                                            //         $posts_data["'".$post_title."'"] = $post_id;
                                            //         // $post = get_post($post_id);
                                            //     }
                                            // }



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

                                            //         $posts_data[$post->post_title] = $post->ID;
                                            //         wp_reset_postdata();
                                            //     }
                                            // } else {
                                            //     $args = [
                                            //         'post_title'    => $post_title,
                                            //         'post_type'     => $cpt_slug,
                                            //         'post_status'   => $status_content['post_status'],
                                            //         'post_author'   => $author_general_id,
                                            //         'post_parent'   => $main_game_id,
                                            //         'post_content'  => $analyzed_post.' + ',
                                            //     ];

                                            //     # Create CPT Game
                                            //     $post_id = wp_insert_post($args);
                                            //     if (!is_wp_error($post_id)) {
                                            //         $posts_data[$post_title] = $post_id;
                                            //         // $post = get_post($post_id);
                                            //     }
                                            // }

                                            
                                            
                                            // if (!is_wp_error($post_id)) {
                                            //     $posts_data[$post_title] = $post_id;
                                            // }


                                            // exit();
                                        }
                                    }
                                }
                            }

                            //error_log(print_r($posts_data, true));

                            error_log(sprintf(__('Sportshub Recaps CLI: %s Posts were analyzed.', SHRECAPS_NAME_SLUG), $analyzed_post));
                            error_log(sprintf(__('Sportshub Recaps CLI: %s Succesfully inserted posts.', SHRECAPS_NAME_SLUG), $new_post));

                            if ($existing_post > 0) {
                                error_log(sprintf(__('Sportshub Recaps CLI: %s Existing posts.', SHRECAPS_NAME_SLUG), $existing_post));
                            }

                            if ($published_post > 0) {
                                error_log(sprintf(__('Sportshub Recaps CLI: %s Posts published.', SHRECAPS_NAME_SLUG), $published_post));
                            }
                        } else {
                            error_log('Sportshub Recaps CLI: No data available for this pull.');
                            WP_CLI::line(__('Sportshub Recaps CLI: No data available for this pull', SHRECAPS_NAME_SLUG));
                        }

                        // error_log(print_r([
                        //     'request_sport' => $request_sport,
                        //     'request_league' => $request_league,
                        //     'file_path' => $file_path,
                        //     'request' => $request['url'],
                        // ], true));
                    }
                }
            }
        } else {
            if (!function_exists('shMappingSportsConverter')) {
                error_log(print_r([
                    'message' => sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary.', SHRECAPS_NAME_SLUG)),
                ], true));

                WP_CLI::line(sprintf(__('Sportshub Recaps CLI: The installation of SH Mapping is necessary.', SHRECAPS_NAME_SLUG)));

                return;
            }

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

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

                return;
            }

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

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

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

                    WP_CLI::line(sprintf(__('Attempting to retrieve data from %s', SHRECAPS_NAME_SLUG), $request));
                    error_log(sprintf(__('Attempting to retrieve data from %s', SHRECAPS_NAME_SLUG), $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('shr_slug');

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

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

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

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

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

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

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

                                        if (
                                            isset($content['home_team_id']) &&
                                            isset($content['visitor_team_id']) &&
                                            isset($teams[$content['home_team_id']]['name']) &&
                                            !empty($teams[$content['home_team_id']]['name']) &&
                                            isset($teams[$content['visitor_team_id']]['name']) &&
                                            !empty($teams[$content['visitor_team_id']]['name'])
                                            ) {
                                                $title = $teams[$content['home_team_id']]['name'];
                                                $title .= ' vs. ';
                                                $title .= $teams[$content['visitor_team_id']]['name'];
                                                $title .= ' Pick & Prediction ';
                                                try {
                                                    $title_date = '';
                                                    $title_date = strtoupper(date('F', strtotime($args['meta_input']['shr_game_date']))).' '.date('jS Y', strtotime($args['meta_input']['shr_game_date']));
                                                } catch (\Exception $exception) {
                                                    error_log(print_r([
                                                        'game_date', $args['meta_input']['shr_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 Recaps CLI: No data available for this pull.');
                                        WP_CLI::line(__('No data available for this pull', SHRECAPS_NAME_SLUG));
                                    }
                                }

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

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

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

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

    private function getHandicappersData($handicappers)
    {
        if (is_array($handicappers) && count($handicappers) > 0) {
            $handicapper = null;

            foreach ($handicappers as $item) {
                $handicapper = $item;
                if (is_array($item['picks']) && count($item['picks']) > 0) break;
            }

            return $handicapper;
        }

        return [];
    }

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

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

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

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

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

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

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

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

        return false;
    }

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

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

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

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

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

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

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

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

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

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

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

        return '';
    }

    public function is_valid_args_simple($args)
    {
        $validate = true;
        $fields_required = [
            'shr_external_id',
            'shr_sport_id',
            'shr_game_date',
            'shr_id_home_team',
            'shr_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_RECAPS_TEAMS.json';
        $file_path_teams = SHRECAPS_PLUGIN_LOG_DIR . '/' . $filename_teams;
        $helpers = New Sportshub_Recaps_Helpers;

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

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

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

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

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

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

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

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

        return $teams_array;
    }

    public function get_games_data()
    {
        $games_array = [];
        $filename_games =  'SPORTS_HUB_RECAPS_INFO.json';
        $file_path_games = SHRECAPS_PLUGIN_LOG_DIR . '/' . $filename_games;
        $helpers = New Sportshub_Recaps_Helpers;
        
        $key = $helpers->getRedisKeyGames();
        if ($helpers->initRedis()) {
            $helpers->setRedisGroup(REDIS_GROUP_SHRECAPS);
            $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), SHRECAPS_REDIS_TIMEOUT);
                }
            }
        }

        return $games_array;
    }

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

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

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

        return implode('', $paragraphs_content);
    }

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

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

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

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

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

        return implode('', $paragraphs_content);
    }

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

            $title = (isset($content[0]['title']) && !empty($content[0]['title'])) ? $content[0]['title'] : '';
            $template = str_replace('[title]', $title, $template);

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

            $visitor = (isset($content[0]['team-visitor']) && !empty($content[0]['team-visitor'])) ? $content[0]['team-visitor'] : '';
            $template = str_replace('[team-visitor]', $visitor, $template);

            $sport = (isset($content[0]['sport']) && !empty($content[0]['sport'])) ? $content[0]['sport'] : '';
            $template = str_replace('[sport]', $sport, $template);

            $league = (isset($content[0]['league']) && !empty($content[0]['league'])) ? $content[0]['league'] : '';
            $template = str_replace('[league]', $league, $template);
        } catch (\Exception $exception) {
            error_log(print_r([
                'template' => $template,
                'content' => $content,
                'message' => 'Sportshub Recaps CLI: '.$exception->getMessage(),
            ], true));
        }

        return preg_replace('/\s+/', ' ', $template);
    }

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

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

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

        return '';
    }

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

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

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

            return true;
        }

        return false;
    }

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

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

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

            $args['meta_input']['shr_home_spread_odds'] = $data['point_spread']['home_odds'];
            $args['meta_input']['shr_away_spread_odds'] = $data['point_spread']['away_odds'];
        }

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

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

            $args['meta_input']['shr_home_overunder_odds'] = $data['over_under']['over_odds'];
            $args['meta_input']['shr_away_overunder_odds'] = $data['over_under']['under_odds'];
        }

        $args['meta_input']['shr_game_id_odds'] = $data['over_under']['game_id'];
        $args['meta_input']['shr_external_id_odds'] = $data['over_under']['external_id'];
        $args['meta_input']['shr_sportsbook_odds'] = $data['over_under']['sportsbook'];
        $args['meta_input']['shr_date_odds'] = $data['over_under']['date'];

        return $args;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if (is_array($handicapper) && count($handicapper) > 0) {
            $args['meta_input']['shr_game_top_handicapper_id'] = $handicapper['id_handicapper'];
            $args['meta_input']['shr_game_top_handicapper_name'] = $handicapper['handicapper']['name'];
            $args['meta_input']['shr_game_top_handicapper_api_image'] = $handicapper['image'];
            $args['meta_input']['shr_game_top_handicapper_description'] = $handicapper['description'];
            $args['meta_input']['shr_game_results_rank'] = $handicapper['rank'];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $args;
    }

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

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

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

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

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

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

        return $args;
    }

    // public function get_parent_game($attributes) {
    //     if (isset($attributes['data']['sport']) && !empty($attributes['data']['sport']) && isset($attributes['data']['category']) && !empty($attributes['data']['category'])) {
    //         $key = $attributes['data']['sport'].'-'.$attributes['data']['category'];

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

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

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

    //     return null;
    // }

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

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

            return [];
        }

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

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

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

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

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

    public function get_api_request_members($sports_leagues)
    {
        $api_base = get_field('shr_api_url', 'options');
        $api_token = get_field('shr_api_token', 'options');
        $content_types = get_field('shr_content_types_members', 'options');
        $range_days = $this->get_range_days();

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

            return [];
        }

        $api_url = (substr($api_base, -1) == '/') ? substr($api_base, 0, strlen($api_base) -1) : $api_base;
        $now = date('Y-m-d');

        if (!empty($range_days)) {
            $start = date('Y-m-d', strtotime("$now - $range_days days"));
        } else {
            $start = $now;
        }

        $api_url .= '?start_date=' . $start;
        $api_url .= '&end_date=' . $now;

        if (isset($sports_leagues['league']) && !empty($sports_leagues['league'])) {
            $api_url .= '&leagues='.$sports_leagues['league_id'];
        } else {
            $api_url .= '&sports='.$sports_leagues['sport_id'];
        }

        $api_url .= '&api_token='.$api_token;
        $sports_leagues['url'] = $api_url;

        return $sports_leagues;
    }

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

        return null;
    }

    public function get_api_request_teams()
    {
        $api_request = '';
        $api_base = (!empty(get_field('shr_teams_url', 'options')))
            ? get_field('shr_teams_url', 'options')
            : 'http://masterfeed.shnadmin.com/feed/media/teams';
        $api_token = get_field('shr_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('shr_games_url', 'options')))
            ? get_field('shr_games_url', 'options')
            : 'http://masterfeed.shnadmin.com/feed/media/games';
        $api_token = get_field('shr_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 isTitleAndContentDuplicate($args, $cpt_slug) {
        wp_reset_postdata();

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

        $query = new WP_Query($args_search);

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

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

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

        return false;
    }

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

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

        wp_reset_postdata();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    public function updateBlockTopHandicapperOddsData($new_data, $args)
    {
        $new_data['meta_input']['shr_home_handicap_spread_odds'] = (isset($args['meta_input']['shr_home_handicap_spread_odds'])) ? $args['meta_input']['shr_home_handicap_spread_odds'] : '';
        $new_data['meta_input']['shr_away_handicap_spread_odds'] = (isset($args['meta_input']['shr_away_handicap_spread_odds'])) ? $args['meta_input']['shr_away_handicap_spread_odds'] : '';
        $new_data['meta_input']['shr_home_spread_odds'] = (isset($args['meta_input']['shr_home_spread_odds'])) ? $args['meta_input']['shr_home_spread_odds'] : '';
        $new_data['meta_input']['shr_away_spread_odds'] = (isset($args['meta_input']['shr_away_spread_odds'])) ? $args['meta_input']['shr_away_spread_odds'] : '';
        $new_data['meta_input']['shr_home_money_odds'] = (isset($args['meta_input']['shr_home_money_odds'])) ? $args['meta_input']['shr_home_money_odds'] : '';
        $new_data['meta_input']['shr_away_money_odds'] = (isset($args['meta_input']['shr_away_money_odds'])) ? $args['meta_input']['shr_away_money_odds'] : '';
        $new_data['meta_input']['shr_home_handicap_overunder_odds'] = (isset($args['meta_input']['shr_home_handicap_overunder_odds'])) ? $args['meta_input']['shr_home_handicap_overunder_odds'] : '';
        $new_data['meta_input']['shr_away_handicap_overunder_odds'] = (isset($args['meta_input']['shr_away_handicap_overunder_odds'])) ? $args['meta_input']['shr_away_handicap_overunder_odds'] : '';
        $new_data['meta_input']['shr_home_overunder_odds'] = (isset($args['meta_input']['shr_home_overunder_odds'])) ? $args['meta_input']['shr_home_overunder_odds'] : '';
        $new_data['meta_input']['shr_away_overunder_odds'] = (isset($args['meta_input']['shr_away_overunder_odds'])) ? $args['meta_input']['shr_away_overunder_odds'] : '';

        return $new_data;
    }

    public function updateBlockTopHandicapperData($new_data, $args)
    {
        $new_data['meta_input']['shr_game_top_handicapper_description'] = $args['meta_input']['shr_game_top_handicapper_description'];
        $new_data['meta_input']['shr_game_results_rank'] = $args['meta_input']['shr_game_results_rank'];
        $new_data['meta_input']['shr_game_results_yesterday'] = $args['meta_input']['shr_game_results_yesterday'];
        $new_data['meta_input']['shr_game_results_lastthreedays'] = $args['meta_input']['shr_game_results_lastthreedays'];
        $new_data['meta_input']['shr_game_results_lastsevendays'] = $args['meta_input']['shr_game_results_lastsevendays'];
        $new_data['meta_input']['shr_game_results_lastthirtydays'] = $args['meta_input']['shr_game_results_lastthirtydays'];

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

        return $new_data;
    }

    public function updateBlockGameData($post_id, $args)
    {
        $new_data = [
            'ID' => $post_id,
            'meta_input' => [
                'shr_game_picks_count' => isset($args['meta_input']['shr_game_picks_count']) ? $args['meta_input']['shr_game_picks_count'] : 0,
                'shr_home_score' => $args['meta_input']['shr_home_score'],
                'shr_visitor_score' => $args['meta_input']['shr_visitor_score'],
            ]
        ];

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

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

        return $new_data;
    }

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

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

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

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

                    return '';
                }

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

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

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

        return '';
    }

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

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

        $helpers = New Sportshub_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']['shr_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']['shr_game_local_image'] = $attachment_game_check[0]['guid'];
                    }
                } else {
                    $args['meta_input']['shr_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']['shr_id_home_team']) &&
                isset($args['meta_input']['shr_id_visitor_team']) &&
                isset($teams[$args['meta_input']['shr_id_home_team']]['name']) &&
                !empty($teams[$args['meta_input']['shr_id_home_team']]['name']) &&
                isset($teams[$args['meta_input']['shr_id_visitor_team']]['name']) &&
                !empty($teams[$args['meta_input']['shr_id_visitor_team']]['name'])
                ) {
                    $name = $teams[$args['meta_input']['shr_id_home_team']]['name'];
                    $name .= '-vs-';
                    $name .= $teams[$args['meta_input']['shr_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']['shr_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, SHRECAPS_NAME_SLUG));
            return ['type' => 'duplicate', 'post_id' => $post_id, 'message' => ''];
        }
    }

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

            return null;
        }

        $json_data = json_decode($file_contents, true);

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

            return null;
        }

        return $json_data;
    }

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

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

        return [];
    }
}
