<?php

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


/**
 * Class Sportshub_Games_Recaps_Helpers
 *
 * This class contains repetitive functions that
 * are used globally within the plugin.
 *
 * @package     SHGAMESR
 * @subpackage  Classes/Sportshub_Games_Recaps_Helpers
 * @author      IT
 * @since       1.0.0
 */
class Sportshub_Games_Recaps_Helpers {
    private $redis_cache;
    private $redis_cache_group;
    private $cache_dir;

    function __construct() {
        $this->redis_cache = $this->initRedis();
        $this->setRedisGroup();
        $this->cache_dir = wp_upload_dir()['basedir'].'/'.SHGAMESR_NAME_SLUG.'/';
    }

    public function get_cache_dir() {
        return $this->cache_dir;
    }

    public function webpack($file, $buildDirectory = 'dist') {
        static $manifest;
        static $manifestPath;

        if (is_null($manifest) || $manifestPath !== $buildDirectory) {
            $manifest = json_decode(
                file_get_contents(SHGAMESR_PLUGIN_URL.$buildDirectory.'/manifest.json'),
                true
            );

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return SHGAMESR_PLUGIN_URL.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }

    public function initRedis() {
        global $wp_object_cache;

        if (isset($wp_object_cache->redis) && $wp_object_cache->redis instanceof \Redis) {
            return true;
        }

        return false;
    }

    public function setRedisGroup($group = '') {
        $this->redis_cache_group = $group;
    }

    public function setRedis($key, $data, $expire = 0) {
        wp_cache_set($key, $data, $this->redis_cache_group, $expire);

        return true;
    }

    public function getRedis($key) {
        return wp_cache_get($key, $this->redis_cache_group);
    }

    public function deleteRedis($key) {
        wp_cache_delete($key, $this->redis_cache_group);

        return true;
    }

    public function getRedisKeySportsLeagues() {
        return 'shgames_recaps_sports_leagues_queue';
    }

    public function getRedisKeySportsLeaguesMasterfeeds() {
        return 'shgames_recaps_sports_leagues_masterfeeds_queue';
    }

    public function getRedisKeySports() {
        return 'shgames_recaps_sports_queue';
    }

    public function getRedisKeySportsMasterfeeds() {
        return 'shgames_recaps_sports_masterfeeds_queue';
    }

    public function getRedisKeySportsContents() {
        return 'shgames_recaps_sports_content_types';
    }

    public function getRedisKeyTeams() {
        return 'shgames_recaps_teams';
    }

    public function getRedisKeyGames() {
        return 'shgames_recaps_games';
    }

    public function getSporstLeaguesOptionsRecap($is_sub_title = false) {
        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHGAMESR);
            
            if (!$is_sub_title) {
                $key = $this->getRedisKeySports();
            } else {
                $key = $this->getRedisKeySportsLeagues();
            }

            $data_sports_leagues = $this->getRedis($key);
    
            if (!empty($data_sports_leagues)) {
                $unserialize_data = unserialize($data_sports_leagues);

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

        $sports_leagues_fields = get_field('shgame_recaps_sports_and_leagues', 'option');

        if (is_array($sports_leagues_fields) && count($sports_leagues_fields) > 0) {
            for ($i = 0; $i <= 1 ; $i++) {
                if ($i == 0) {
                    $is_sub_title = false;
                    $key = $this->getRedisKeySports();
                } else {
                    $is_sub_title = true;
                    $key = $this->getRedisKeySportsLeagues();
                }
    
                $sports_leagues = [];

                foreach ($sports_leagues_fields as $sport_league) {
                    if (is_array($sport_league['shgr_leagues']) && count($sport_league['shgr_leagues']) > 0 && $is_sub_title) {
                        $leagues = [];
                        $leagues[$sport_league['shgr_sport_id']] = $sport_league['shgr_sport_title'] .' - '. __('ANY CATEGORY');
    
                        foreach ($sport_league['shgr_leagues'] as $sub_title) {
                            $leagues[$sport_league['shgr_sport_id'].'-'.$sub_title['shgr_league_id']] = $sport_league['shgr_sport_title'] .' | '. $sub_title['shgr_league_title'];
                        }
                    } else {
                        $leagues = $sport_league['shgr_sport_title'];
                    }
    
                    if (is_array($leagues)) {
                        $sports_leagues[$sport_league['shgr_sport_title']] = $leagues;
                    } else {
                        $sports_leagues[$sport_league['shgr_sport_id']] = $leagues;
                    }
                }

                if ($this->initRedis() && is_array($sports_leagues) && count($sports_leagues) > 0) {
                    $this->setRedis($key, serialize($sports_leagues), SHGAMESR_REDIS_TIMEOUT);
                }
            }
        }
    }

    public function getSporstLeaguesMasterfeedsOptions($is_sub_title = false) {
        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHGAMESR);

            if (!$is_sub_title) {
                $key = $this->getRedisKeySportsMasterfeeds();
            } else {
                $key = $this->getRedisKeySportsLeaguesMasterfeeds();
            }

            $data_sports_leagues = $this->getRedis($key);
    
            if (!empty($data_sports_leagues)) {
                $unserialize_data = unserialize($data_sports_leagues);

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

        $sports_leagues_fields_masterfeed = get_field('shgame_recaps_sports_and_leagues_masterfeed', 'option');

        if (is_array($sports_leagues_fields_masterfeed) && count($sports_leagues_fields_masterfeed) > 0) {
            for ($i = 0; $i <= 1 ; $i++) {
                if ($i == 0) {
                    $is_sub_title = false;
                    $key = $this->getRedisKeySportsMasterfeeds();
                } else {
                    $is_sub_title = true;
                    $key = $this->getRedisKeySportsLeaguesMasterfeeds();
                }
    
                $sports_leagues = [];

                foreach ($sports_leagues_fields_masterfeed as $sport_league) {
                    if (is_array($sport_league['shgr_leagues_masterfeed']) && count($sport_league['shgr_leagues_masterfeed']) > 0 && $is_sub_title) {
                        $leagues = [];
                        $leagues[$sport_league['shgr_sport_id_masterfeed']] = $sport_league['shgr_sport_title_masterfeed'] .' - '. __('ANY CATEGORY');
    
                        foreach ($sport_league['shgr_leagues_masterfeed'] as $sub_title) {
                            $leagues[$sport_league['shgr_sport_id_masterfeed'].'-'.$sub_title['shgr_league_id_masterfeed']] = $sport_league['shgr_sport_title_masterfeed'] .' | '. $sub_title['shgr_league_title_masterfeed'];
                        }
                    } else {
                        $leagues = $sport_league['shgr_sport_title_masterfeed'];
                    }
    
                    if (is_array($leagues)) {
                        $sports_leagues[$sport_league['shgr_sport_title_masterfeed']] = $leagues;
                    } else {
                        $sports_leagues[$sport_league['shgr_sport_id_masterfeed']] = $leagues;
                    }
                }

                if ($this->initRedis() && is_array($sports_leagues) && count($sports_leagues) > 0) {
                    $this->setRedis($key, serialize($sports_leagues), SHGAMESR_REDIS_TIMEOUT);
                }
            }
        }
    }

    public function getNameFile($image_url, $is_logo = true)
    {
        $is_image = false;
        $file_name = '';
        $image_alt = '';
        $file_extension = '';
        $extensions_images = ['png', 'jpg', 'jpeg', 'gif', 'webp'];

        try {
            $parts = explode('/', $image_url);
            $image_name = $parts[count($parts) - 1];
            $image_name_parts = explode('.', $image_name);
            $file_extension = strtolower($image_name_parts[count($image_name_parts) - 1]);
            unset($image_name_parts[count($image_name_parts) - 1]);
            $file_name = implode('.', $image_name_parts);
            $title_image = $file_name;

            $image_alt = str_replace('_', ' ', $file_name);
            $image_alt = str_replace('-', ' ', $image_alt);
            $image_alt = str_replace('.', ' ', $image_alt);
            $image_alt = ucwords(strtolower($image_alt));

            $is_image = (in_array($file_extension, $extensions_images)) ? true : false;

            if ($is_logo) $image_alt .= ' Logo';
        } catch (\Exception $exception) {
            error_log(print_r([
                'is_logo' => $is_logo,
                'image_url' => $image_url,
                'exception' => $exception->getMessage(),
            ], true));
        }

        return [
            'is_image' => $is_image,
            'name' => $image_name,
            'title' => sanitize_title($title_image),
            'alt' => $image_alt,
            'extension' => $file_extension,
            'image_url' => $image_url,
        ];
    }

    public function getSporstContentTypes()
    {
        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHGAMESR);
            $key = $this->getRedisKeySportsContents();
            $types = $this->getRedis($key);
    
            if (!empty($types)) {
                $unserialize_data = unserialize($types);

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

        $types = [];
        $sports_content_types = get_field('shgr_content_types', 'option');

        if (is_array($sports_content_types) && count($sports_content_types) > 0) {
            foreach ($sports_content_types as $type) {
                $types[$type['shgr_content_type_slug']] = $type['shgr_content_type_title'];
            }

            if ($this->initRedis() && is_array($types) && count($types) > 0) {
                $this->setRedis($key, serialize($types), SHGAMESR_REDIS_TIMEOUT);
            }
        }

        return $types;
    }

    public function get_blocks_spaces($fields) {
        $styles = [];

        if (!empty($fields['top'])) {
            $styles[] = $fields['top']['top_type'].'-top: '.$fields['top']['top_space'].'rem';
        }

        if (!empty($fields['right'])) {
            $styles[] = $fields['right']['right_type'].'-right: '.$fields['right']['right_space'].'rem';
        }

        if (!empty($fields['bottom'])) {
            $styles[] = $fields['bottom']['bottom_type'].'-bottom: '.$fields['bottom']['bottom_space'].'rem';
        }

        if (!empty($fields['left'])) {
            $styles[] = $fields['left']['left_type'].'-left: '.$fields['left']['left_space'].'rem';
        }

        if (count($styles) > 0) {
            return implode('; ', $styles).';';
        }

        return '';
    }

    public function get_sporst_categories_titles($is_sub_title = false) {
        $sport_titles = [];
        $key = 'rdg_blocks_sports_categories';
        
        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHGAMESR);
            $data_titles = $this->getRedis($key);
    
            if (!empty($data_titles)) {
                $unserialize_data = unserialize($data_titles);

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

        $titles = get_field('sports_categories', 'option');
        
        if (is_array($titles) && count($titles) > 0) {
            foreach ($titles as $title) {
                if (is_array($title['categories']) && count($title['categories']) > 0 && $is_sub_title) {
                    $sport_titles[$title['sport_id']] = $title['sport_title'];

                    foreach ($title['categories'] as $sub_title) {
                        $sport_titles[$title['sport_id'].'-'.$sub_title['category_id']] = $title['sport_title'].' | '.$sub_title['category_title'];
                    }
                } else {
                    $sport_titles[$title['sport_id']] = $title['sport_title'];
                }
            }

            if ($this->initRedis() && is_array($sport_titles) && count($sport_titles) > 0) {
                $this->setRedis($key, serialize($sport_titles), REDIS_TIMEOUT);
            }
        }

        return $sport_titles;
    }

    function shgr_debug_blocks_games($params) {
        if (get_field('shgr_debug_block_games', 'options') != 'active') return false;

        if (is_user_logged_in() && current_user_can('administrator') && isset($params['type_game']) && $params['type_game'] != 'example' && $params['type_game'] != '') {
            return true;
        }

        return false;
    }
}
