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

WP_CLI::add_command('sh_handicappers', 'Sh_Handicappers_CLI');

/**
 * Class Sh_Handicappers_CLI
 *
 * This class contains all WP CLI related features.
 *
 * @package		SHHANDICAP
 * @subpackage	Classes/Sh_Handicappers_CLI
 * @author		IT
 * @since		1.0.0
 */
class Sh_Handicappers_CLI extends WP_CLI_Command {
    private $helpers;
    /**
     * Our Sh_Handicappers_CLI constructor 
     * to run the plugin CLI logic.
     *
     * @since 1.0.0
     */
    function __construct(){
        $this->helpers = New Sh_Handicappers_Helpers;
    }

    /**
     * Get plugin details
     *
     * ## OPTIONS
     *
     * None. Returns basic info regarding the plugin instance.
     *
     * ## EXAMPLES
     *
     * To access this feature, type the following into your console:
     * wp sh_handicappers details
     *
     * @param		array $args
     * @param		array $assoc_args
     * @return		void
     */
    public function details($args, $assoc_args) {
        WP_CLI::line(sprintf(__('Plugin name: %s', 'SH Handicappers'), SHHANDICAP_NAME));
        WP_CLI::line(sprintf(__('Plugin version: %s', 'SH Handicappers'), SHHANDICAP_VERSION));
    }

    public function pull($args, $assoc_args) {
        $this->removeLogsFiles();

        if (get_option('shh_status', 0) != 1) {
            error_log(sprintf(__('Sportshub Handicappers: Plugin disabled.', 'SportsHub Handicappers')));
            WP_CLI::line(sprintf(__('Sportshub Handicappers: Plugin disabled.', 'SportsHub Handicappers')));
            return;
        }

        $hancicappers_selected = get_field('sh_handicappers', 'options');
        if (!is_array($hancicappers_selected)) {
            error_log(sprintf(__('Sportshub Handicappers: No handicappers selected.', 'SportsHub Handicappers')));
            WP_CLI::line(sprintf(__('Sportshub Handicappers: No handicappers selected.', 'SportsHub Handicappers')));
            return;
        }

        $ids = array_column($hancicappers_selected, 'shh_handicapper');
        $filename = 'SHH_PULL_' . date('Y-m-d-H-i-s') . '.json';
        $file_path = SHHANDICAP_PLUGIN_LOG_DIR . '/' . $filename;
        $this->helpers->getHadicappersOptions($file_path);
        $all_hancicappers = $this->helpers->parseFeedFile($file_path);

        if (!is_array($all_hancicappers) || empty($all_hancicappers)) {
            error_log(sprintf(__('Sportshub Handicappers: No handicappers data found.', 'SportsHub Handicappers')));
            WP_CLI::line(sprintf(__('Sportshub Handicappers: No handicappers data found.', 'SportsHub Handicappers')));
            return;
        }

        $handicappers_data = [];
        $new_post = 0;
        $existing_post = 0;

        foreach ($all_hancicappers as $item) {
            if (in_array($item['id'], $ids)) {
                $summary = $this->getSummaryData($item['id']);

                if (count($summary) == 0) {
                    error_log('No summary data for handicapper ID: ' . $item['id']);
                    continue;
                }

                $sports_ranks = $this->getSportRanks($summary['sports_ranks']);
                $today_picks = $this->getTodayPicks($summary['today_picks']);
                $bets_stats = $summary['bets_stats'] ?? [];
                $top_strikes = $summary['top_strikes'] ?? [];
                $handicapper_basic_data = $summary['handicapper_basic_data'] ?? [];
                $handicappers_data = [
                    'id' => $item['id'],
                    'name' => $item['name'],
                    'bio' => $item['bio'],
                    'image' => $item['image'],
                    'last_days' => $item['last_days'],
                    'last_days_amount' => $item['last_days_amount'],
                    'subscribers_plan' => $item['subscribers_plan'],
                    'sub_groups' => $item['sub_groups'],
                    'day_results' => serialize($summary['day_results']),
                    'bets_stats' => serialize($bets_stats),
                    'top_strikes' => serialize($top_strikes),
                    'handicapper_basic_data' => serialize($handicapper_basic_data),
                    'sports_ranks' => serialize($sports_ranks),
                    'today_picks' => serialize($today_picks),
                ];

                $response = $this->insertPostContent($handicappers_data);
                if (is_wp_error($response)) {
                    error_log(sprintf(__('Sportshub Handicappers: Error inserting post for handicapper ID %s.', 'SportsHub Handicappers'), $item['id']));
                    WP_CLI::line(sprintf(__('Error inserting post for handicapper ID %s.', 'SportsHub Handicappers'), $item['id']));
                    continue;
                }

                if (is_array($response) && isset($response['type'])) {
                    if ($response['type'] == 'new') {
                        $new_post++;
                    } elseif ($response['type'] == 'duplicate') {
                        $existing_post++;
                    } else {
                        WP_CLI::Line($response['message']);
                    }
                }
            }
        }

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

        if ($existing_post > 0) {
            error_log(sprintf(__('SportsHub Handicappers: %s Succesfully updated posts.', 'SportsHub Handicappers'), $existing_post));
            WP_CLI::line(sprintf(__('%s Succesfully updated posts.', 'SportsHub Handicappers'), $existing_post));
        }

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

    public function getTitleHandicapper($capper) {
        return str_replace('[HANDICAPPERNAME]', $capper, get_option('shh_post_placeholder'));
    }

    public function insertPostContent($data)
    {
        wp_reset_postdata();
        $shh = Sh_Handicappers::instance();

        $args_search = [
            'post_type' => $shh->get_slug(false),
            'meta_query' => [
                [
                    'key' => 'shh_handicapper_id',
                    'value' => $data['id'],
                    'compare' => '=',
                ],
            ],
        ];

        $post_id = null;
        $query = new WP_Query($args_search);
        $last_days_amount = $this->getLastDaysAmount($data);
        $package_ids = $this->getPackageIdsFromSubscribersPlan($data['subscribers_plan'] ?? []);

        if (!$query->have_posts()) {
            $post_id = wp_insert_post([
                'post_type' => $shh->get_slug(false),
                'post_name' => $data['name'],
                'post_title' => $this->getTitleHandicapper($data['name']),
                'meta_input' => [
                    'shh_handicappers_name' => $data['name'],
                    'shh_handicapper_summary' => null,
                    'shh_handicapper_bio' => $data['bio'], #$this->getContentFormat($data['bio'])
                    'shh_package_ids' => $package_ids,
                    'shh_sub_groups_ids' => isset($data['sub_groups'][0]['id']) ? $data['sub_groups'][0]['id'] : '',
                    'shh_last_days_amount' =>  $last_days_amount,
                    'shh_handicapper_id' => $data['id'],
                    'shh_image_url' => $data['image'],
                    'shh_day_results' => $data['day_results'],
                    'shh_bets_stats' => $data['bets_stats'], 
                    'shh_handicapper_basic_data' => $data['handicapper_basic_data'], 
                    'shh_top_strikes' => $data['top_strikes'], 
                    'shh_sports_ranks' => $data['sports_ranks'],
                    'shh_today_picks' => $data['today_picks']
                ],
                'post_status' => 'publish'
            ]);

            if (!is_wp_error($post_id)) {              
                # Get local capper image
                $capper_image = $this->setLocalImage($data['image']);

                if (is_array($capper_image)) {
                    if (isset($capper_image['url']) && !empty($capper_image['url'])) {
                        update_post_meta($post_id, 'ssh_image_url', $capper_image['url']);
                    }

                    if (isset($capper_image['id']) && !empty($capper_image['id'])) {
                        set_post_thumbnail($post_id, $capper_image['id']);
                    }
                }
            }

            if (!is_wp_error($post_id)) {
                WP_CLI::line(__('New Post, ID: '. $post_id, 'SportsHub Handicappers'));

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

                wp_update_post([
                    'ID' => $post_id,
                    'meta_input' => [
                        'shh_handicappers_name' =>  $data['name'],
                        'shh_handicapper_bio' =>  $data['bio'],
                        'shh_package_ids' => $package_ids,
                        'shh_sub_groups_ids' => isset($data['sub_groups'][0]['id']) ? $data['sub_groups'][0]['id'] : '',
                        'shh_last_days_amount' =>  $last_days_amount,
                        'shh_day_results' =>  $data['day_results'],
                        'shh_bets_stats' =>  $data['bets_stats'],
                        'shh_handicapper_basic_data' =>  $data['handicapper_basic_data'],
                        'shh_top_strikes' =>  $data['top_strikes'],
                        'shh_sports_ranks' =>  $data['sports_ranks'],
                        'shh_today_picks' =>  $data['today_picks']
                    ]
                ]);
    
                $capper_image = $this->setLocalImage($data['image']);
                if (is_array($capper_image)) {
                    if (isset($capper_image['url']) && !empty($capper_image['url'])) {
                        update_post_meta($post_id, 'shh_image_url', $capper_image['url']);
                    }
    
                    if (isset($capper_image['id']) && !empty($capper_image['id'])) {
                        set_post_thumbnail($post_id, $capper_image['id']);
                    }
                }
            }

            WP_CLI::line(__('Update Post, ID: '. $post_id, 'SportsHub Handicappers'));
            return ['type' => 'duplicate', 'post_id' => $post_id, 'message' => ''];
        }
    }

    public function getLastDaysAmount($handicapper) {
        if (!isset($handicapper['last_days']) || !isset($handicapper['last_days_amount'])) {
            return '';
        }

        if ($handicapper['last_days_amount'] < 0) {
            $currency = '-$';
            $last_days_amount = str_replace('-', '', $handicapper['last_days_amount']);
        } else {
            $currency = '+$';
            $last_days_amount = $handicapper['last_days_amount'];
        }

        $last_days = $handicapper['last_days'] ?? 0;

        return "Won in the last " . $last_days . " days: " . $currency . $last_days_amount;
    }

    /**
     * Extrae todos los IDs de subscribers_plan y los devuelve como string separado por coma.
     *
     * @param array $subscribers_plan Array de planes (cada uno con clave 'id').
     * @return string IDs separados por coma, o string vacío si no hay ninguno.
     */
    public function getPackageIdsFromSubscribersPlan($subscribers_plan) {
        if (!is_array($subscribers_plan) || empty($subscribers_plan)) {
            return '';
        }
        $ids = [];
        foreach ($subscribers_plan as $plan) {
            if (isset($plan['id']) && $plan['id'] !== '' && $plan['id'] !== null) {
                $ids[] = (string) $plan['id'];
            }
        }
        return implode(',', $ids);
    }

    public function setLocalImage($image_url) {
        if (empty($image_url)) {
            return [
                'id' => null,
                'url' => null,
            ];
        }

        $image_object = $this->helpers->getNameFile($image_url, false);
        $attachment_id = null;
        $image_object_url = null;

        if (is_array($image_object) && isset($image_object['is_image']) && $image_object['is_image'] == true) {
            $attachment_capper_check = $this->getAttachment('post_title', $image_object['name']);

            if (empty($attachment_capper_check)) {
                $attachment_id = media_sideload_image($image_object['image_url'], 0, $image_object['name'], 'id');

                if (is_wp_error($attachment_id)) {
                    error_log('Error on upload image: ' . $attachment_id->get_error_message());
                    return [
                        'id' => null,
                        'url' => null,
                    ];
                }

                if ($attachment_id) {
                    update_post_meta($attachment_id, '_wp_attachment_image_alt', $image_object['alt']);
                }

                $attachment_capper_check = $this->getAttachment('ID', $attachment_id);
                $image_object_url = $attachment_capper_check[0]['guid'] ?? null;
            } else {
                $attachment_id = $attachment_capper_check[0]['ID'];
                $image_object_url = $attachment_capper_check[0]['guid'];
            }
        }

        return [
            'id' => $attachment_id,
            'url' => $image_object_url,
        ];
    }

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

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

        return $block_init.strip_tags($content).$block_end;
    }

    public function getSummaryData($handicapperId) {
        $params = $this->helpers->getQueryParams(['handicapper' => $handicapperId]);
        $url = get_field('shh_summary_url', 'options');

        if (empty($url)) {
            error_log('shh_summary_url is not set in options');
            return [];
        }

        $summaryUrl = $this->helpers->getApiUrl($url, '&'.$params);       
        $summaryRequest = $this->helpers->getApiRequest($summaryUrl);

        if ($summaryRequest['http_code'] == 200) {
            $response_json = $this->helpers->isJson($summaryRequest['data']);

            if ($response_json != null) {
                return $response_json;
            } else {
                error_log('Invalid JSON response from API');
            }
        } else {
            error_log('API request failed with HTTP code: ' . $summaryRequest['http_code']);
        }

        return [];
    }

    public function getSportNameById($sportId) {
        $sports = [
            '1' => 'MLB',
            '2' => 'MAT',
            '3' => 'NBA',
            '4' => 'NFL',
            '5' => 'NHL',
            '6' => 'SOC',
            '7' => 'TOU',
            '8' => 'CBB',
            '9' => 'CFF',
            '10' => 'RBT'
        ];
        
        return $sports[$sportId];
    }

    public function getSports() {
        $url = get_field('shh_sports_url', 'options');
        $sportUrl = $this->helpers->getApiUrl($url);
        $sportsRequest = $this->helpers->getApiRequest($sportUrl);

        if ($sportsRequest['http_code'] == 200) {
            $response_json = $this->helpers->isJson($sportsRequest['data']);            

            if ($response_json != null) {
                $data = json_decode($sportsRequest['data'], true);

                $sports = [];
                foreach ($data as $item) {
                    $sports[$item['id']] = $item['sport_name'];
                }

                return $sports;
            }
        }

        return [];
    }

    public function getSportRanks($sports_ranks) {
        if (!is_array($sports_ranks) || empty($sports_ranks)) {
            return [];
        }
    
        $sports_ranks_sort = [];
        foreach ($sports_ranks as $key => $row) {
            if (isset($row['rank'])) {
                $sports_ranks_sort[] = $row['rank'];
            }
        }
    
        array_multisort($sports_ranks_sort, SORT_ASC, $sports_ranks);
    
        $sports_rank_order = array_map(function ($sport_rank) {
            if (!isset($sport_rank['id_sport'])) {
                return null;
            }
            $sportName = $this->getSportNameById($sport_rank['id_sport']);
            return [
                'sport' => $sportName,
                'rank' => $sport_rank['rank'],
            ];
        }, $sports_ranks);
    
        $sports_rank_order = array_filter($sports_rank_order, function ($item) {
            return $item !== null;
        });
    
        return $sports_rank_order;
    }


    public function getTodayPicks($today_picks) {
        if (!is_array($today_picks) || empty($today_picks)) {
            return [];
        }

        return array_map(function ($today_pick) {
            $pick_details = $today_pick['pick_details'][0] ?? [];
            $game = $pick_details['game'] ?? [];
            $formatted_date = $this->formatDate($game['game_date'] ?? '');
            $sport_name = $this->getSportNameById($game['id_sport'] ?? '');
            $visitor_team = $game['id_visitor_team'] ?? [];
            $visitor_image = $this->getTeamImage($visitor_team);
            $visitor_id = $visitor_team['id'] ?? '';
            $home_team = $game['id_home_team'] ?? [];
            $home_image = $this->getTeamImage($home_team);
            $home_id = $home_team['id'] ?? '';

            return [
                'status' => $today_pick['status'] ?? '',
                'description' => $pick_details['description'] ?? '',
                'game_date' => $formatted_date,
                'sport_name' => $sport_name,
                'visitor_name' => $visitor_team['name'] ?? '',
                'home_name' => $home_team['name'] ?? '',
                'visitor_id' => $visitor_id,
                'visitor_url' => $visitor_image['url'] ?? '',
                'home_id' => $home_id,
                'home_url' => $home_image['url'] ?? '',
            ];
        }, $today_picks);
    }

    private function getTeamImage($team) {
        if (isset($team['image']) && !empty($team['image'])) {
            return $this->setLocalImage($team['image']);
        }
        return [];
    }

    function removeLogsFiles() {
        $log_lifetime_in_days = get_option('options_shh_logs_lifetime', 0);
        $log_lifetime_in_seconds = $log_lifetime_in_days * 24 * 60 * 60;
        $log_directory = SHHANDICAP_PLUGIN_LOG_DIR;

        if (!file_exists($log_directory)) {
            wp_mkdir_p($log_directory);
        }
        
        $message = false;
        $log_files = glob($log_directory . '/*');
        
        foreach ($log_files as $log_file) {
            if (filemtime($log_file) < time() - $log_lifetime_in_seconds) {
                unlink($log_file);
                $message = true;
            }
        }

        if ($message) {
            WP_CLI::line(sprintf(__('Sportshub Handicappers: Remove old log files.', 'SportsHub Handicappers')));
        }

        return true;
    }

    public function formatDate($date) {
        $date = new DateTime($date);
        $date_formatted = $date->format('d/m');
        $hora_formatted = $date->format('H:i');
        return $date_formatted . ' | ' . $hora_formatted;
    }
}
