<?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_DIR.$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 getRedisKeySportsContentsMembers() {
        return 'shgames_sports_content_types_members';
    }

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

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

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

        try {
            // Validate that $image_url is a non-empty string before explode()
            if (!is_string($image_url) || empty($image_url)) {
                return ['status' => false, 'message' => 'Invalid image URL'];
            }
            
            $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 getSporstContentTypesMembers()
    {
        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHGAMES);
            $key = $this->getRedisKeySportsContentsMembers();
            $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('shg_content_types_members', 'option');

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

            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)) {
                $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 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;
    }

    function isConfigBlock($block_config = '')
    {
        $configs = get_field('shg_content_types_members', 'option');

        if (empty($block_config) || !is_array($configs) || count($configs) == 0) {
            return false;
        }

        foreach ($configs as $config) {
            if (isset($config['shg_content_type_slug_members']) && $config['shg_content_type_slug_members'] == $block_config) {
                return true;
            }
        }

        return false;
    }

    function getContentTypeBlock($types = [])
    {
        if (!is_array($types) || count($types) == 0) return [];

        $types_data = [];
        $types_config = (!empty(get_field('shg_content_types_members', 'options'))) ? get_field('shg_content_types_members', 'options') :[];

        foreach ($types_config as $type) {
            if (in_array($type['shg_content_type_slug_members'], $types)) {
                $types_data[$type['shg_content_type_slug_members']] = $type;
            }
        }

        return $types_data;
    }

    private function getTeamsFromGame($post_id)
    {
        return [
            'home_team' => !empty(get_field('shg_home_team', $post_id)) ? get_field('shg_home_team', $post_id) : '',
            'visitor_team' => !empty(get_field('shg_visitor_team', $post_id)) ? get_field('shg_visitor_team', $post_id) : '',
        ];
    }

    public function getTitle($title, $post_id)
    {
        $placeholders = $this->getTeamsFromGame($post_id);

        $title = str_replace('[home-team]', $placeholders['home_team'], $title);
        $title = str_replace('[team-home]', $placeholders['home_team'], $title);
        $title = str_replace('[visitor-team]', $placeholders['visitor_team'], $title);
        $title = str_replace('[team-visitor]', $placeholders['visitor_team'], $title);

        return $title;
    }

    public function isValidateContent()
    {
        return (get_field('shg_content_validate_content', 'options') != null) 
            ? boolval(get_field('shg_content_validate_content', 'options')) 
            : false;
    }
}
