<?php

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


/**
 * Class Sportshub_Games_Helpers
 *
 * This class contains repetitive functions that
 * are used globally within the plugin.
 *
 * @package     SHGAMES
 * @subpackage  Classes/Sportshub_Games_Helpers
 * @author      IT
 * @since       1.0.0
 */
class Sportshub_Games_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'].'/'.SHGAMES_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(SHGAMES_PLUGIN_URL.$buildDirectory.'/manifest.json'),
                true
            );

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return SHGAMES_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_sports_leagues_queue';
    }

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

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

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

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

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

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

            if (!$is_sub_title) {
                $key = $this->getRedisKeySports();
            } else {
                $key = $this->getRedisKeySportsLeagues();
            }

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

        $sports_leagues_fields = get_field('shgame_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['shg_leagues']) && count($sport_league['shg_leagues']) > 0 && $is_sub_title) {
                        $leagues = [];
                        $leagues[$sport_league['shg_sport_id']] = $sport_league['shg_sport_title'] .' - '. __('ANY CATEGORY');
    
                        foreach ($sport_league['shg_leagues'] as $sub_title) {
                            $leagues[$sport_league['shg_sport_id'].'-'.$sub_title['shg_league_id']] = $sport_league['shg_sport_title'] .' | '. $sub_title['shg_league_title'];
                        }
                    } else {
                        $leagues = $sport_league['shg_sport_title'];
                    }
    
                    if (is_array($leagues)) {
                        $sports_leagues[$sport_league['shg_sport_title']] = $leagues;
                    } else {
                        $sports_leagues[$sport_league['shg_sport_id']] = $leagues;
                    }
                }

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

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

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

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

        $sports_leagues_fields_masterfeed = get_field('shgame_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['shg_leagues_masterfeed']) && count($sport_league['shg_leagues_masterfeed']) > 0 && $is_sub_title) {
                        $leagues = [];
                        $leagues[$sport_league['shg_sport_id_masterfeed']] = $sport_league['shg_sport_title_masterfeed'] .' - '. __('ANY CATEGORY');
    
                        foreach ($sport_league['shg_leagues_masterfeed'] as $sub_title) {
                            $leagues[$sport_league['shg_sport_id_masterfeed'].'-'.$sub_title['shg_league_id_masterfeed']] = $sport_league['shg_sport_title_masterfeed'] .' | '. $sub_title['shg_league_title_masterfeed'];
                        }
                    } else {
                        $leagues = $sport_league['shg_sport_title_masterfeed'];
                    }
    
                    if (is_array($leagues)) {
                        $sports_leagues[$sport_league['shg_sport_title_masterfeed']] = $leagues;
                    } else {
                        $sports_leagues[$sport_league['shg_sport_id_masterfeed']] = $leagues;
                    }
                }

                if ($this->initRedis() && is_array($sports_leagues) && count($sports_leagues) > 0) {
                    $this->setRedis($key, serialize($sports_leagues), SHGAMES_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_SHGAMES);
            $key = $this->getRedisKeySportsContents();
            $types = $this->getRedis($key);
    
            if (!empty($types)) {
                return unserialize($types);
            }
        }

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

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

            if ($this->initRedis() && is_array($types) && count($types) > 0) {
                $this->setRedis($key, serialize($types), SHGAMES_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_SHGAMES);
            $data_titles = $this->getRedis($key);
    
            if (!empty($data_titles)) {
                return unserialize($data_titles);
            }
        }

        $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 shg_debug_blocks_games($params) {
        if (get_field('shg_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;
    }
}
