<?php

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

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

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

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

    function __construct() {
    }

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

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

            return;
        }

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

            return;
        }

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

            return;
        }

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

            return;
        }

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

            return;
        }

        // Prevent concurrent executions (cron + manual) from creating duplicate posts.
        // Race in isTitleDuplicate + WP_Query-by-external_id allowed parallel processes
        // to both pass the duplicate check and insert the same preview multiple times.
        $shg_lock_key = 'shg_pull_running';
        if (get_transient($shg_lock_key)) {
            $lock_started_at = (int) get_transient($shg_lock_key);
            WP_CLI::warning(sprintf(
                __('Another sh-games pull is already running (started %d seconds ago). Exiting to avoid duplicates.', 'SportsHub Games'),
                time() - $lock_started_at
            ));
            return;
        }
        set_transient($shg_lock_key, time(), 30 * MINUTE_IN_SECONDS);
        // Release the lock on any exit path (normal return, exception, or fatal error).
        // shutdown_function runs even on fatal errors, which try/finally cannot catch.
        // The 30-minute TTL above is a safety net in case the PHP process is killed
        // before the shutdown handler runs (e.g. SIGKILL).
        register_shutdown_function(function () use ($shg_lock_key) {
            delete_transient($shg_lock_key);
        });

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

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

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

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

                if (empty($post_author)) continue;

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

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

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

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

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

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

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

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

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

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

        $main_games_original = $main_games;
        $main_games = shMappingAuthorsMainsSportsLeaguesConverter($main_games, $source);

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

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

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

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

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

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

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

                $sport_league_id = isset($sport['shg_sport_league']) ? $sport['shg_sport_league'] : null;
                if (!empty($sport_league_id)) {
                    $sport_leagues = shMappingSportsLeaguesConverterSingle($sport_league_id, $source);

                    if (is_array($sport_leagues) && count($sport_leagues) > 0) {
                        $request = $this->get_api_request_members($sport_leagues);
                        if (!empty($request) && isset($main_games_original[$sport_league_id])) {
                            $request['post_parent'] = $main_games_original[$sport_league_id];
                        }
                        $requests[] = $request;
                    }
                }
            }
        }

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

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

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

            return;
        }

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

        if ($source == self::SOURCE_MEMBERS) {
            if (is_array($requests) && count($requests) > 0) {
                foreach ($requests as $shg_request) {
                    WP_CLI::line(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $shg_request['request']));
                    error_log(sprintf(__('Attempting to retrieve data from %s', 'SportsHub Games'), $shg_request['request']));

                    $file_path = $this->getFilePath($shg_request);
                    $execute_request = $this->exe_request($shg_request['request'], $file_path);

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

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

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

                                        // Skip games whose scheduled date is before today. The API occasionally
                                        // returns historical games (observed: Jan 2026, Aug 2025) even when
                                        // start_date=today is requested. Creating posts for past games produces
                                        // posts with post_date=now + title="January 14th 2026" — visually
                                        // confusing and not useful for previews.
                                        if (!empty($game['date']) && strtotime($game['date']) < strtotime('today')) {
                                            $skipped_post++;
                                            continue;
                                        }

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

                                        $title_date = '';
                                        $home_name = $game['home_team'];
                                        $visitor_name =  $game['visitor_team'] ?? $game['away_team'] ?? '';
                                        $post_title = $this->getPostTitle($home_name, $visitor_name);

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

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

                                        $status_content = $this->getContentMembers($game);

                                        $contents = [
                                            'preview' => $status_content['post_content'],
                                            'knup' => $this->getKnupSportsContent($game),
                                        ];

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

                                        $request_parent = isset($shg_request['post_parent']) ? $shg_request['post_parent'] : $main_game_id;

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

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

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

                                        $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++;
                                            } elseif ($response['type'] == 'skipped') {
                                                $skipped_post++;
                                            } else {
                                                WP_CLI::Line($response['message']);
                                            }
                                        }
                                    }
                                }
                            }

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

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

                            if ($skipped_post > 0) {
                                error_log(sprintf(__('Sportshub Games: %s Posts skipped (published or manually edited).', 'SportsHub Games'), $skipped_post));
                                WP_CLI::line(sprintf(__('%s Posts skipped (published or manually edited).', 'SportsHub Games'), $skipped_post));
                            }

                            if ($analyzed_post > 0) {
                                error_log(sprintf(__('Sportshub Games: %s Posts were analyzed.', 'SportsHub Games'), $analyzed_post));
                                WP_CLI::line(sprintf(__('%s Posts were analyzed.', 'SportsHub Games'), $analyzed_post));
                            }
                        } else {
                            error_log('Sportshub Games: No data available for this pull.');
                            WP_CLI::line(__('No data available for this pull', 'SportsHub Games'));
                        }
                    } else {
                        return;
                    }
                }
            }
        } else {
            // Validate sports_leagues_array before passing to SH Mapping
            if (is_array($sports_leagues_array) && count($sports_leagues_array) > 0) {
                $invalid_keys = [];
                foreach ($sports_leagues_array as $key => $value) {
                    // Check if value is not an array and not an empty string (which is set at line 212)
                    if (!is_array($value) && $value !== '') {
                        $invalid_keys[] = [
                            'key' => $key,
                            'value' => $value,
                            'type' => gettype($value)
                        ];
                    }
                }
                
                if (count($invalid_keys) > 0) {
                    error_log(print_r([
                        'message' => 'SH Mapping: Invalid values found in sports_leagues_array before conversion',
                        'invalid_keys' => $invalid_keys,
                        'full_array' => $sports_leagues_array
                    ], true));
                    
                    // Clean up invalid values - remove non-array values (except empty strings)
                    foreach ($invalid_keys as $invalid) {
                        if (isset($sports_leagues_array[$invalid['key']])) {
                            unset($sports_leagues_array[$invalid['key']]);
                        }
                    }
                }
            }
            
            $sports_leagues_array_converted = shMappingSportsConverter($sports_leagues_array, $source, 'array');
            $shg_request = $this->get_api_request_masterfeed($sports_leagues_array_converted);

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

                return;
            }

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

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

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

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

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

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

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

                                foreach ($parse_results[0]['data-content'][0][0]['contents'] as $content) {
                                    if (!empty($parse_results)) {
                                        $cpt_slug = get_option('shg_slug');

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

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

                                        $args = [
                                            'post_title'    => $post_title,
                                            'post_name'     => $post_name,
                                            'post_type'     => $cpt_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' => 'The game does not contain the required data.',
                                                'shg_external_id' => (isset($args['meta_input']['shg_external_id'])) ? $args['meta_input']['shg_external_id'] : ''
                                            ], true));
                                            continue;
                                        }

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

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

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

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

                                if ($skipped_post > 0) {
                                    error_log(sprintf(__('Sportshub Games: %s Posts skipped (published or manually edited).', 'SportsHub Games'), $skipped_post));
                                    WP_CLI::line(sprintf(__('%s Posts skipped (published or manually edited).', 'SportsHub Games'), $skipped_post));
                                }
                        } else {
                            unlink($file_path);

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

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

    public function getFilePath($request) {
        $request_sport = isset($request['sport']) ? str_replace(["'", ',', ' '], '_', $request['sport']) : null;
        $filename = sprintf('SPORTS_HUB_GAMES_PULL_%s_%s.json', strtoupper($request_sport), date('Y-m-d-H-i-s'));

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

        return SHGAMES_PLUGIN_LOG_DIR . '/' . $filename;
    }

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

        $visitor_team_key = isset($game['visitor_team']) ? 'visitor_team' : 'away_team';
        if (isset($game[$visitor_team_key]) && !empty($game[$visitor_team_key])) {
            $valid++;
            $valid_data['away_team'] = $game[$visitor_team_key];
        } 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'] = '';
        }

        // Require at least team names (away_team and home_team)
        // Images are optional - posts will be created with default/placeholder images if missing
        if ($valid >= 2) {
            if ($valid < 4) {
                error_log(print_r([
                    'message' => 'SH Game: Creating post with missing images.',
                    'valid_data' => $valid_data,
                    'missing_data' => $missing_data,
                ], true));
            }
            return true;
        }

        error_log(print_r([
            'message' => 'SH Game: Incomplete equipment data - missing team names.',
            'valid_data' => $valid_data,
            'missing_data' => $missing_data,
        ], true));

        return false;
    }

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

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

        foreach ($types as $type) {
            $body = '';
            if ($type['shg_content_type_slug_members'] == 'preview') {
                if (isset($game['body']) && !empty($game['body'])) {
                    $body = $game['body'];
                    $data_game[0] = $game;
                }
            } elseif ($type['shg_content_type_slug_members'] == 'recap') {
                $recap_body = '';
                if (isset($game['recap'])) {
                    $recap_body = is_array($game['recap']) ? ($game['recap'][0]['body'] ?? '') : $game['recap'];
                }
                if (!empty($recap_body)) {
                    $body = $recap_body;
                    $data_game = [[
                        'body'         => $recap_body,
                        'date'         => $game['date'] ?? '',
                        'title'        => $game['title'] ?? '',
                        'team-home'    => $game['home_team'] ?? '',
                        'team-visitor' => $game['visitor_team'] ?? $game['away_team'] ?? '',
                    ]];
                }
            } else {
                if (isset($game[$type['shg_content_type_slug_members']][0]['body']) && !empty($game[$type['shg_content_type_slug_members']][0]['body'])) {
                    $body = $game[$type['shg_content_type_slug_members']][0]['body'];
                }
            }

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

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

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

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

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

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

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

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

        return '';
    }

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

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

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

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

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

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

        return false;
    }

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

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

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

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

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

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

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

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

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

        return $teams_array;
    }

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

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

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

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

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

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

        return $games_array;
    }

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

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

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

        return implode('', $paragraphs_content);
    }

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

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

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

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

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

        return implode('', $paragraphs_content);
    }

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

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

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

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

        return $template;
    }

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

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

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

        return '';
    }

    public function exe_request($request, $file_path)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            error_log(sprintf(__('Sportshub Games: cURL ERROR: %s.', 'SportsHub Games'), $curl_error));
            WP_CLI::line(sprintf(__('cURL ERROR: %s.', 'SportsHub Games'), $curl_error));
            return false;
        }

        $response_length = strlen($response);
        WP_CLI::line(sprintf(__('HTTP Code: %d, Response length: %d bytes', 'SportsHub Games'), $http_code, $response_length));

        if ($http_code !== 200) {
            error_log(sprintf(__('Sportshub Games: HTTP ERROR: Code %d, Response: %s', 'SportsHub Games'), $http_code, substr($response, 0, 200)));
            WP_CLI::line(sprintf(__('HTTP ERROR: Code %d', 'SportsHub Games'), $http_code));
            return false;
        }

        if ($response_length === 0) {
            error_log(sprintf(__('Sportshub Games: Empty response from API: %s', 'SportsHub Games'), $request));
            WP_CLI::line(sprintf(__('ERROR: Empty response from API', 'SportsHub Games')));
            return false;
        }

        $bytes_written = file_put_contents($file_path, $response);
        if ($bytes_written === false) {
            error_log(sprintf(__('Sportshub Games: Failed to write file: %s', 'SportsHub Games'), $file_path));
            WP_CLI::line(sprintf(__('ERROR: Failed to write file: %s', 'SportsHub Games'), $file_path));
            return false;
        }

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

        return true;
    }

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

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

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

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

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

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

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

        $args['meta_input']['shg_game_id_odds'] = $data['over_under']['game_id'];
        $args['meta_input']['shg_external_id_odds'] = $data['over_under']['external_id'];
        $args['meta_input']['shg_sportsbook_odds'] = $data['over_under']['sportsbook'];
        $args['meta_input']['shg_date_odds'] = $data['over_under']['date'];

        return $args;
    }

    public function parse_odds_data_v2($odds, $args)
    {
        if (isset($odds['money_line_home_odds'])) {
            $args['meta_input']['shg_home_money_odds'] = $odds['money_line_home_odds'];
        }
        if (isset($odds['money_line_visitor_odds'])) {
            $args['meta_input']['shg_away_money_odds'] = $odds['money_line_visitor_odds'];
        }
        if (isset($odds['spread_home_points'])) {
            $args['meta_input']['shg_home_handicap_spread_odds'] = $odds['spread_home_points'];
            $visitor_spread = (float) $odds['spread_home_points'] * -1;
            $args['meta_input']['shg_away_handicap_spread_odds'] = ($visitor_spread > 0 ? '+' : '') . $visitor_spread;
        }
        if (isset($odds['spread_home_odds'])) {
            $args['meta_input']['shg_home_spread_odds'] = $odds['spread_home_odds'];
        }
        if (isset($odds['spread_visitor_odds'])) {
            $args['meta_input']['shg_away_spread_odds'] = $odds['spread_visitor_odds'];
        }
        if (isset($odds['total_over_points'])) {
            $args['meta_input']['shg_home_handicap_overunder_odds'] = 'O ' . $odds['total_over_points'];
            $args['meta_input']['shg_away_handicap_overunder_odds'] = 'U ' . $odds['total_over_points'];
        }
        if (isset($odds['total_over_odds'])) {
            $args['meta_input']['shg_home_overunder_odds'] = $odds['total_over_odds'];
        }
        if (isset($odds['total_under_odds'])) {
            $args['meta_input']['shg_away_overunder_odds'] = $odds['total_under_odds'];
        }
        if (isset($odds['id_game'])) {
            $args['meta_input']['shg_game_id_odds'] = $odds['id_game'];
        }
        if (isset($odds['created_at'])) {
            $args['meta_input']['shg_date_odds'] = $odds['created_at'];
        }

        return $args;
    }

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

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

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

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

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

        $game_id_sport = $game['id_sport'] ?? (isset($game['picks'][0]['id_sport']) ? $game['picks'][0]['id_sport'] : null);
        if (isset($game_id_sport)) {
            $game['id_sport'] = $game_id_sport;
        }
        if (isset($game['id_sport'])) {
            $args['meta_input']['shg_sport_id'] = $game['id_sport'];

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

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

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

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

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

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

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

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

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

        $visitor_team_val = $game['visitor_team'] ?? $game['away_team'] ?? '';
        if (!empty($visitor_team_val)) {
            $args['meta_input']['shg_visitor_team'] = $visitor_team_val;
        }

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

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

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

        if (!empty($game['odds'])) {
            $odds = $game['odds'];
            // v2: odds is a flat object with named keys; v1: array of {type, ...} objects
            if (isset($odds['money_line_home_odds']) || isset($odds['spread_home_points']) || isset($odds['total_over_points'])) {
                $args = $this->parse_odds_data_v2($odds, $args);
            } elseif (is_array($odds) && count($odds) > 0) {
                $args = $this->parse_odds_data($odds, $args);
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $args;
    }

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

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

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

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

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

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

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

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

        return $args;
    }

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

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

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

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

    //     return null;
    // }

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

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

            return [];
        }

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

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

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

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

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

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

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

            return [];
        }

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

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

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

        return $sports_leagues;
    }

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

        return null;
    }

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


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

        return $api_request;
    }

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

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

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

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

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

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

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

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

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

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

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

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

        return $all_content_data;
    }

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

        // Use proper title search - WP_Query doesn't support 'title' directly
        $args_search = [
            'post_type' => $cpt_slug,
            'post_status' => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
            'posts_per_page' => -1,
            'no_found_rows' => true,
            's' => sanitize_text_field($args['post_title']),
        ];

        $query = new WP_Query($args_search);

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

            // Check exact title match (search is fuzzy, so we need to verify)
            if ($post->post_title !== $args['post_title']) {
                continue;
            }

            // Skip if it's the same external ID (it's an update, not a duplicate)
            $existing_external_id = get_post_meta($post->ID, 'shg_external_id', true);
            $new_external_id = isset($args['meta_input']['shg_external_id']) ? $args['meta_input']['shg_external_id'] : '';
            
            if (!empty($existing_external_id) && !empty($new_external_id) && 
                intval($existing_external_id) === intval($new_external_id)) {
                continue;
            }

            // Found a post with same title but different external ID = duplicate
            wp_reset_postdata();
            return true;
        }
        
        wp_reset_postdata();
        return false;
    }

    public function checkDuplicateByGameDetails($args, $cpt_slug) {
        // If we don't have key identifiers, can't check
        if (empty($args['meta_input']['shg_game_date']) || 
            empty($args['meta_input']['shg_id_home_team']) || 
            empty($args['meta_input']['shg_id_visitor_team'])) {
            return false;
        }

        wp_reset_postdata();

        $args_search = [
            'post_type' => $cpt_slug,
            'post_status' => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
            'posts_per_page' => 1,
            'no_found_rows' => true,
            'meta_query' => [
                'relation' => 'AND',
                [
                    'key' => 'shg_game_date',
                    'value' => $args['meta_input']['shg_game_date'],
                    'compare' => '=',
                ],
                [
                    'key' => 'shg_id_home_team',
                    'value' => $args['meta_input']['shg_id_home_team'],
                    'compare' => '=',
                ],
                [
                    'key' => 'shg_id_visitor_team',
                    'value' => $args['meta_input']['shg_id_visitor_team'],
                    'compare' => '=',
                ],
            ],
        ];

        $query = new WP_Query($args_search);
        $has_duplicate = $query->have_posts();
        
        wp_reset_postdata();
        return $has_duplicate;
    }

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

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

        // Fallback: Check by game details if external ID is missing
        if (empty($args['meta_input']['shg_external_id'])) {
            if ($this->checkDuplicateByGameDetails($args, $cpt_slug)) {
                WP_CLI::line(__('Duplicate found by game details (no external ID), skipping.', 'SportsHub Games'));
                return [
                    'type' => 'duplicate',
                    'post_id' => null,
                    'message' => 'Duplicate found by game details'
                ];
            }
        }

        wp_reset_postdata();

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

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

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

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

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

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

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

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

            if (!is_wp_error($post_id)) {
                # Inherit taxonomy from parent post
                if (!empty($args['post_parent'])) {
                    $parent_terms = wp_get_object_terms($args['post_parent'], 'previews_categories', ['fields' => 'ids']);
                    if (!is_wp_error($parent_terms) && !empty($parent_terms)) {
                        wp_set_object_terms($post_id, $parent_terms, 'previews_categories');
                    }
                }

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

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

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

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

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

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

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

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

            # Skip updating published posts to prevent overwriting editor changes
            if ($post->post_status === 'publish') {
                # Backfill missing team logos on published posts without overwriting other content
                $this->backfillTeamLogos($post->ID, $args);

                WP_CLI::line(__('Skipping published post ID: '. $post->ID, 'SportsHub Games'));
                return ['type' => 'skipped', 'post_id' => $post->ID, 'message' => 'Published post - skipped to preserve content'];
            }

            # Skip posts that have been manually edited (marked with meta field)
            if (get_post_meta($post->ID, 'shg_manually_edited', true) === '1') {
                WP_CLI::line(__('Skipping manually edited post ID: '. $post->ID, 'SportsHub Games'));
                return ['type' => 'skipped', 'post_id' => $post->ID, 'message' => 'Manually edited post - skipped to preserve changes'];
            }

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

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

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

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

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

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

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

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

                    $this->insertOrUpdatePickGame($pick_game, $post->ID);
                }
            }

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

    /**
     * Inserts or updates a row in the shg_picks ACF repeater field.
     *
     * A pick is considered a duplicate if it matches on:
     *   - sport id        (shg_pick_sport)
     *   - date placed     (shg_pick_date)
     *   - home team name  (shg_pick_home_name)
     *   - visitor team name (shg_pick_visitor_name)
     *
     * When a match is found the existing row is updated instead of
     * adding a new one, so odds/stats changes are reflected without
     * creating duplicates.
     */
    private function insertOrUpdatePick($new_pick, $post_id)
    {
        $existing_picks = get_field('shg_picks', $post_id);

        if (is_array($existing_picks) && count($existing_picks) > 0) {
            foreach ($existing_picks as $index => $existing_pick) {
                $same_sport = isset($existing_pick['shg_pick_sport'], $new_pick['shg_pick_sport']) &&
                    $existing_pick['shg_pick_sport'] == $new_pick['shg_pick_sport'];

                $same_date = isset($existing_pick['shg_pick_date'], $new_pick['shg_pick_date']) &&
                    $existing_pick['shg_pick_date'] === $new_pick['shg_pick_date'];

                $same_home = isset($existing_pick['shg_pick_home_name'], $new_pick['shg_pick_home_name']) &&
                    trim($existing_pick['shg_pick_home_name']) === trim($new_pick['shg_pick_home_name']);

                $same_visitor = isset($existing_pick['shg_pick_visitor_name'], $new_pick['shg_pick_visitor_name']) &&
                    trim($existing_pick['shg_pick_visitor_name']) === trim($new_pick['shg_pick_visitor_name']);

                if ($same_sport && $same_date && $same_home && $same_visitor) {
                    update_row('shg_picks', $index + 1, $new_pick, $post_id);
                    error_log(sprintf(
                        'SH Games / insertOrUpdatePick: Updated existing pick (row %d) on post %d',
                        $index + 1,
                        $post_id
                    ));
                    return;
                }
            }
        }

        add_row('shg_picks', $new_pick, $post_id);
        error_log(sprintf(
            'SH Games / insertOrUpdatePick: Added new pick on post %d',
            $post_id
        ));
    }

    /**
     * Inserts or updates a row in the shg_picks_game ACF repeater field.
     *
     * A pick is considered a duplicate if it matches on:
     *   - handicapper name (shg_pick_game_handicapper_name)
     *   - date placed      (shg_pick_game_date)
     *   - bet type         (shg_pick_game_bet)       e.g. Spread, Moneyline, Over/Under
     *   - pick selection   (shg_pick_game_teaser)    e.g. "PARIS SAINT GERMAIN"
     *
     * Different bet types from the same handicapper on the same game are
     * intentionally kept as separate rows.
     * When a match is found the existing row is updated instead of adding a
     * new one, so stat/odds changes are reflected without creating duplicates.
     */
    private function insertOrUpdatePickGame($new_pick, $post_id)
    {
        $existing_picks = get_field('shg_picks_game', $post_id);

        if (is_array($existing_picks) && count($existing_picks) > 0) {
            foreach ($existing_picks as $index => $existing_pick) {
                $same_handicapper = isset($existing_pick['shg_pick_game_handicapper_name'], $new_pick['shg_pick_game_handicapper_name']) &&
                    trim($existing_pick['shg_pick_game_handicapper_name']) === trim($new_pick['shg_pick_game_handicapper_name']);

                $same_date = isset($existing_pick['shg_pick_game_date'], $new_pick['shg_pick_game_date']) &&
                    $existing_pick['shg_pick_game_date'] === $new_pick['shg_pick_game_date'];

                $same_bet = isset($existing_pick['shg_pick_game_bet'], $new_pick['shg_pick_game_bet']) &&
                    trim($existing_pick['shg_pick_game_bet']) === trim($new_pick['shg_pick_game_bet']);

                $same_teaser = isset($existing_pick['shg_pick_game_teaser'], $new_pick['shg_pick_game_teaser']) &&
                    trim($existing_pick['shg_pick_game_teaser']) === trim($new_pick['shg_pick_game_teaser']);

                if ($same_handicapper && $same_date && $same_bet && $same_teaser) {
                    update_row('shg_picks_game', $index + 1, $new_pick, $post_id);
                    error_log(sprintf(
                        'SH Games / insertOrUpdatePickGame: Updated existing pick game (row %d) for "%s" on post %d',
                        $index + 1,
                        $new_pick['shg_pick_game_handicapper_name'],
                        $post_id
                    ));
                    return;
                }
            }
        }

        add_row('shg_picks_game', $new_pick, $post_id);
        error_log(sprintf(
            'SH Games / insertOrUpdatePickGame: Added new pick game for "%s" on post %d',
            $new_pick['shg_pick_game_handicapper_name'] ?? 'unknown',
            $post_id
        ));
    }

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

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

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

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

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

            return null;
        }

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

            return null;
        }

        return null;
    }

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

        return $new_data;
    }

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

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

        return $new_data;
    }

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

        # Backfill missing meta fields on existing posts
        $backfill_fields = [
            'shg_home_team', 'shg_visitor_team', 'shg_game_date',
            'shg_sport_name', 'shg_sport_id', 'shg_league', 'shg_league_name',
            'shg_home_image', 'shg_visitor_image', 'shg_game_url',
            'shg_id_home_team', 'shg_id_visitor_team',
        ];
        foreach ($backfill_fields as $field) {
            $existing = get_post_meta($post_id, $field, true);
            $new_val = isset($args['meta_input'][$field]) ? $args['meta_input'][$field] : '';
            if (!empty($new_val) && empty($existing)) {
                $new_data['meta_input'][$field] = $new_val;
                if (defined('WP_CLI') && WP_CLI) {
                    WP_CLI::line("  Backfilled {$field} on post {$post_id}");
                }
            }
        }

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

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

        return $new_data;
    }

    /**
     * Backfill missing team logos (home/visitor) on an existing post without
     * overwriting any other content. Safe to call for published posts.
     *
     * Only writes meta fields when they are currently empty and the API
     * provides the source image URL. This is the counterpart to
     * updateBlockGameData() that runs on posts which are skipped from the
     * regular update flow (e.g. published posts).
     *
     * @param int   $post_id The existing post ID to update.
     * @param array $args    The parsed args array from parse_data().
     * @return void
     */
    private static $sweptTeamPositions = [];

    private function isPlaceholderOrEmpty($value)
    {
        return empty($value) || strpos($value, 'default_picture') !== false;
    }

    /**
     * Sweep across all preview posts where a given team_id appears in the given
     * position (home|visitor) and replace placeholder logo URLs with the real
     * one. This is what allows past-game posts (which the pull never re-fetches)
     * to recover their logos once the API has the real URL for that team.
     */
    private function sweepTeamLogoAcrossPosts($team_id, $real_image_url, $position)
    {
        if (empty($team_id) || $this->isPlaceholderOrEmpty($real_image_url)) {
            return;
        }
        if ($position !== 'home' && $position !== 'visitor') {
            return;
        }

        $cache_key = $position . ':' . $team_id;
        if (isset(self::$sweptTeamPositions[$cache_key])) {
            return;
        }
        self::$sweptTeamPositions[$cache_key] = true;

        $cpt_slug = get_option('shg_slug');
        if (empty($cpt_slug)) {
            return;
        }

        $team_id_field = 'shg_id_' . $position . '_team';
        $api_image_field = 'shg_' . $position . '_image';
        $local_url_field = 'shg_' . $position . '_local_url';

        global $wpdb;
        $post_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT p.ID
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} m_team ON p.ID = m_team.post_id AND m_team.meta_key = %s AND m_team.meta_value = %s
             INNER JOIN {$wpdb->postmeta} m_img ON p.ID = m_img.post_id AND m_img.meta_key = %s AND m_img.meta_value LIKE %s
             WHERE p.post_type = %s",
            $team_id_field, (string) $team_id,
            $api_image_field, '%default_picture%',
            $cpt_slug
        ));

        if (empty($post_ids)) {
            return;
        }

        $local_url = $this->uploadImage($real_image_url);

        foreach ($post_ids as $post_id) {
            update_post_meta($post_id, $api_image_field, $real_image_url);
            if (!empty($local_url)) {
                update_post_meta($post_id, $local_url_field, $local_url);
            }
            if (defined('WP_CLI') && WP_CLI) {
                WP_CLI::line("  Sweep: replaced {$position} logo placeholder on post {$post_id} (team_id={$team_id})");
            }
        }
    }

    public function backfillTeamLogos($post_id, $args)
    {
        if (empty($post_id) || !is_array($args) || empty($args['meta_input'])) {
            return;
        }

        # Image fields are backfilled when missing OR when storing a placeholder URL
        $image_fields = ['shg_home_image', 'shg_visitor_image'];

        # Backfill missing meta fields (team names, date, sport, etc.)
        $backfill_fields = [
            'shg_home_team', 'shg_visitor_team', 'shg_game_date',
            'shg_sport_name', 'shg_sport_id', 'shg_league', 'shg_league_name',
            'shg_home_image', 'shg_visitor_image', 'shg_game_url',
            'shg_id_home_team', 'shg_id_visitor_team',
        ];
        foreach ($backfill_fields as $field) {
            $existing = get_post_meta($post_id, $field, true);
            $new_val = isset($args['meta_input'][$field]) ? $args['meta_input'][$field] : '';
            $is_image_field = in_array($field, $image_fields, true);
            $needs_backfill = $is_image_field
                ? $this->isPlaceholderOrEmpty($existing)
                : empty($existing);
            $new_val_usable = $is_image_field
                ? !$this->isPlaceholderOrEmpty($new_val)
                : !empty($new_val);
            if ($new_val_usable && $needs_backfill) {
                update_post_meta($post_id, $field, $new_val);
                if (defined('WP_CLI') && WP_CLI) {
                    WP_CLI::line("  Backfilled {$field} on post {$post_id}");
                }
            }
        }

        # Backfill post_parent if missing
        if (!empty($args['post_parent']) && get_post($post_id)->post_parent == 0) {
            wp_update_post(['ID' => $post_id, 'post_parent' => $args['post_parent']]);

            $parent_terms = wp_get_object_terms($args['post_parent'], 'previews_categories', ['fields' => 'ids']);
            if (!is_wp_error($parent_terms) && !empty($parent_terms)) {
                $existing_terms = wp_get_object_terms($post_id, 'previews_categories', ['fields' => 'ids']);
                if (empty($existing_terms)) {
                    wp_set_object_terms($post_id, $parent_terms, 'previews_categories');
                }
            }
        }

        # Backfill missing team logo images (also replaces placeholder URLs)
        $home_api_image = isset($args['meta_input']['shg_home_image']) ? $args['meta_input']['shg_home_image'] : '';
        $visitor_api_image = isset($args['meta_input']['shg_visitor_image']) ? $args['meta_input']['shg_visitor_image'] : '';

        $home_local_existing = get_post_meta($post_id, 'shg_home_local_url', true);
        $visitor_local_existing = get_post_meta($post_id, 'shg_visitor_local_url', true);

        if (!$this->isPlaceholderOrEmpty($home_api_image) && $this->isPlaceholderOrEmpty($home_local_existing)) {
            $image = $this->uploadImage($home_api_image);
            if (!empty($image)) {
                update_post_meta($post_id, 'shg_home_local_url', $image);
            }
        }

        if (!$this->isPlaceholderOrEmpty($visitor_api_image) && $this->isPlaceholderOrEmpty($visitor_local_existing)) {
            $image = $this->uploadImage($visitor_api_image);
            if (!empty($image)) {
                update_post_meta($post_id, 'shg_visitor_local_url', $image);
            }
        }

        # Sweep across past-game posts that have placeholders for this same team
        $home_team_id = isset($args['meta_input']['shg_id_home_team']) ? $args['meta_input']['shg_id_home_team'] : '';
        $visitor_team_id = isset($args['meta_input']['shg_id_visitor_team']) ? $args['meta_input']['shg_id_visitor_team'] : '';

        $this->sweepTeamLogoAcrossPosts($home_team_id, $home_api_image, 'home');
        $this->sweepTeamLogoAcrossPosts($visitor_team_id, $visitor_api_image, 'visitor');
    }

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

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

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

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

                    return '';
                }

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

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

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

        return '';
    }

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

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

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

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

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

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

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

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

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

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

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

            $teams = $this->get_teams_data();

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

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

                    wp_update_post($update_data);
            }

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

            # Skip updating published posts to prevent overwriting editor changes
            if ($post->post_status === 'publish') {
                WP_CLI::line(__('Skipping published post ID: '. $post_id, 'SportsHub Games'));
                return ['type' => 'skipped', 'post_id' => $post_id, 'message' => 'Published post - skipped to preserve content'];
            }

            # Skip posts that have been manually edited (marked with meta field)
            if (get_post_meta($post_id, 'shg_manually_edited', true) === '1') {
                WP_CLI::line(__('Skipping manually edited post ID: '. $post_id, 'SportsHub Games'));
                return ['type' => 'skipped', 'post_id' => $post_id, 'message' => 'Manually edited post - skipped to preserve changes'];
            }

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

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

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

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

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

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

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

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

        return $api_request;
    }

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

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

        return null;
    }

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

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

            return null;
        }

        $json_data = json_decode($file_contents, true);

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

            return null;
        }

        return $json_data;
    }

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

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

        return [];
    }

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

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

            $knup_type = $this->getKnupSportsType();

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

        return $knup_content;
    }
}
