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

    public function getBlocksStylesLoad() {
        $i = 0;
        $blocks_load = [];
        
        global $shg;
        $shg = (!empty($shg)) ? $shg : Sportshub_Games::instance();

        $blocks = $shg->settings->getBlocks();

        foreach ($blocks as $block) {
            if ($block->isStylesLoad()) {
                $blocks_load[$block->getBlockName()] = $block;
            }
        }

        return $blocks_load;
    }

    public function isInstallGeneratePress() {
        $current_theme = wp_get_theme();

        # Check if the active theme is generatePress
        if ('generatepress' == $current_theme->get('TextDomain')) {
            return true;
        }

        # Check if the active theme is a child of a generatePress theme
        if ('generatepress' == $current_theme->get('Template')) {
            return true;
        }
        
        return false;
    }

    public function registerGeneratePressColors($colors, $saved_colors, $options) {
        $colors_new = [];
        foreach ($colors as $key => $color) {
            if (!in_array($color['slug'], $saved_colors)) {
                $colors_new[] = $color;
            }
        }

        if (is_array($colors_new) && count($colors_new) > 0) {
            $generatepress_colors = array_merge($options['global_colors'], $colors_new);
            $options['global_colors'] = $generatepress_colors;
            update_option('generate_settings', $options);
        }

        return $options;
    }

    public function registerGeneratePressStyles($styles, $saved_styles, $options) {
        $styles = $this->setDefaultStylesFields($styles);

        $styles_new = [];
        foreach ($styles as $key => $style) {
            if (!in_array($style['customSelector'], $saved_styles)) {
                $styles_new[] = $style;
            }
        }

        if (is_array($styles_new) && count($styles_new) > 0) {
            $generatepress_styles = array_merge($options['typography'], $styles_new);
            $options['typography'] = $generatepress_styles;
            update_option('generate_settings', $options);
        }

        return $options;
    }

    public function setDefaultStylesFields($styles) {
        $default_fields = [
            'customSelector' => '',
            'fontFamily' => '',
            'fontWeight' => '',
            'textTransform' => '',
            'textDecoration' => '',
            'fontStyle' => '',
            'fontSize' => '',
            'fontSizeTablet' => '',
            'fontSizeMobile' => '',
            'lineHeight' => '',
            'lineHeightTablet' => '',
            'lineHeightMobile' => '',
            'letterSpacing' => '',
            'letterSpacingTablet' => '',
            'letterSpacingMobile' => '',
            'marginBottom' => '',
            'marginBottomTablet' => '',
            'marginBottomMobile' => '',
            'marginBottomUnit' => '',
        ];

        $new_styles = [];
        foreach ($styles as $style) {
            $set_styles = array_merge($default_fields, $style);
            $set_styles['selector'] = 'custom';
            $set_styles['module'] = 'core';
            $set_styles['group'] = 'other';
            $new_styles[] = $set_styles;
        }

        return $new_styles;
    }

    public function getDefaultColors() {
        return [
            [
                'name' => __( 'Contrast', 'generatepress' ),
                'slug' => 'contrast',
                'color' => '#333333',
            ],
            [
                'name' => sprintf( __( 'Contrast %s', 'generatepress' ), '2' ),
                'slug' => 'contrast-2',
                'color' => '#555555',
            ],
            [
                'name' => sprintf( __( 'Contrast %s', 'generatepress' ), '3' ),
                'slug' => 'contrast-3',
                'color' => '#b4b4b4',
            ],
            [
                'name' => __( 'Base', 'generatepress' ),
                'slug' => 'base',
                'color' => '#f1f1f1',
            ],
            [
                'name' => sprintf( __( 'Base %s', 'generatepress' ), '2' ),
                'slug' => 'base-2',
                'color' => '#f5f5f5',
            ],
            [
                'name' => sprintf( __( 'Base %s', 'generatepress' ), '3' ),
                'slug' => 'base-3',
                'color' => '#eeeeee',
            ],
        ];
    }

    public function getBaseColors() {
        return [
            ['name' => 'color-white','slug' => 'color-white','color' => '#FFFFFF'],
            ['name' => 'color-black','slug' => 'color-black','color' => '#111111'],
            ['name' => 'color-primary','slug' => 'color-primary','color' => '#3a96e0'],
            ['name' => 'color-primary-dark','slug' => 'color-primary-dark','color' => '#03467d'],
            ['name' => 'color-primary-dark-light','slug' => 'color-primary-dark-light','color' => '#0160ac'],
            ['name' => 'color-gray','slug' => 'color-gray','color' => '#F1F1F1'],
            ['name' => 'color-gray-line','slug' => 'color-gray-line','color' => '#CCC'],
            ['name' => 'color-danger','slug' => 'color-danger','color' => '#e11414'],
            ['name' => 'color-danger-dark','slug' => 'color-danger-dark','color' => '#891010'],
            ['name' => 'color-danger-light','slug' => 'color-danger-light','color' => '#fc6363'],
            ['name' => 'color-warning','slug' => 'color-warning','color' => '#e69305'],
            ['name' => 'color-warning-dark','slug' => 'color-warning-dark','color' => '#9f6809'],
            ['name' => 'color-warning-light','slug' => 'color-warning-light','color' => '#f5c776'],
            ['name' => 'color-success','slug' => 'color-success','color' => '#00bc00'],
            ['name' => 'color-success-dark','slug' => 'color-success-dark','color' => '#244d0e'],
            ['name' => 'color-success-light','slug' => 'color-success-light','color' => '#68f96e'],
        ];
    }

    public function registerStylesCss($block, $styles) {
        $new_styles = [];
        foreach ($styles as $style) {
            if (!isset($style['customSelector']) || empty($style['customSelector'])) continue;

            $selector = $style['customSelector'];
            unset($style['customSelector']);
            
            $css_array = [];
            $css_array_tablet = [];
            $css_array_mobile = [];
            foreach ($style as $attribute => $value) {
                if (!$this->validAttribute($attribute)) continue;

                if (in_array($attribute, ['fontSizeTablet', 'lineHeightTablet', 'letterSpacingTablet'])) {
                    $tem_css_tablet = $this->convertAttribute($attribute, $value);
                    if (!empty($tem_css_tablet)) {
                        $css_array_tablet[] = $tem_css_tablet;
                    }

                    continue;
                }

                if (in_array($attribute, ['fontSizeMobile', 'lineHeightMobile', 'letterSpacingMobile'])) {
                    $tem_css_mobile = $this->convertAttribute($attribute, $value);
                    if (!empty($tem_css_mobile)) {
                        $css_array_mobile[] = $tem_css_mobile;
                    }

                    continue;
                }
                
                $tem_css = $this->convertAttribute($attribute, $value);
                if (!empty($tem_css)) {
                    $css_array[] = $tem_css;
                }
            }

            if (is_array($css_array) && count($css_array) > 0) {
                $new_styles[] = sprintf('%s { %s }', $selector,implode(' ', $css_array));
            }

            if (is_array($css_array_tablet) && count($css_array_tablet) > 0) {
                $new_styles[] = sprintf('@media (max-width: 1024px) { %s { %s }}', $selector,implode(' ', $css_array_tablet));
            }

            if (is_array($css_array_mobile) && count($css_array_mobile) > 0) {
                $new_styles[] = sprintf('@media (max-width: 768px) { %s { %s }}', $selector,implode(' ', $css_array_mobile));
            }
        }

        $block_name = $block->getBlockName();
        $css_file_block = $this->getCssFileBlock($block_name);

        if (empty($css_file_block)) {
           error_log(print_r([
                'message' => 'SH Games / registerStylesCss: Block css file not found.',
                'block_name' => $block_name,
            ], true));

            return '';
        }

        $this->setCssFileBlock($css_file_block, $new_styles);
    }

    public function validAttribute($attribute) {
        return in_array($attribute, ['fontWeight', 'fontSize', 'fontSizeTablet', 'fontSizeMobile', 'textTransform', 
            'textDecoration', 'fontStyle', 'lineHeight', 'lineHeightTablet', 'lineHeightMobile', 'letterSpacing', 
        'letterSpacingTablet', 'letterSpacingMobile']);
    }

    public function convertAttribute($attribute, $value) {
        #Options: normal, bold, 100, 200, 300, 400, 500, 600, 700, 800, 900
        if ($attribute == 'fontWeight') {
            return sprintf('font-weight: %s;', $value);
        }

        #Options: uppercase, lowercase, capitalize, initial
        if ($attribute == 'textTransform') {
            return sprintf('text-transform: %s;', $value);
        }

        #Options: none, underline
        if ($attribute == 'textDecoration') {
            return sprintf('text-decoration: %s;', $value);
        }

        #Options: normal, italic, oblique, initial
        if ($attribute == 'fontStyle') {
            return sprintf('font-style: %s;', $value);
        }

        #Options: 15px, 2.5rem, 1.7em, 10%
        if (in_array($attribute, ['fontSize', 'fontSizeTablet', 'fontSizeMobile'])) {
            return sprintf('font-size: %s;', $value);
        }

        #Options: 15px, 2.5rem, 1.7em, 10%
        if (in_array($attribute, ['lineHeight', 'lineHeightTablet', 'lineHeightMobile'])) {
            return sprintf('line-height: %s;', $value);
        }

        #Options: 15px, 2.5rem, 1.7em, 10%
        if (in_array($attribute, ['letterSpacing', 'letterSpacingTablet', 'letterSpacingMobile'])) {
            return sprintf('letter-spacing: %s;', $value);
        }

        return '';
    }

    public function getCssFileBlock($block_name) {
        try {
            if (!file_exists(SHGAMES_PLUGIN_DIR.'dist/manifest.json')) {
               error_log(print_r([
                    'message' => 'SH Games / getCssFileBlock: Manifest file not found.',
                    'block_name' => $block_name,
                ], true));
    
                return '';
            }
    
            $manifest = SHGAMES_PLUGIN_DIR.'dist/manifest.json';
            $blocks_data = file_get_contents($manifest);
            $blocks_data_array = json_decode($blocks_data, true);

            if (is_array($blocks_data_array) && count($blocks_data_array) > 0) {
                if (isset($blocks_data_array[str_replace('-', '_', $block_name).'.css'])) {
                    return $blocks_data_array[str_replace('-', '_', $block_name).'.css'];
                }
            }
        } catch (\Exception $exception) {
           error_log(print_r([
                'message' => sprintf('SH Games / getCssFileBlock: %s', $exception->getMessage()),
                'block_name' => $block_name,
            ], true));
        }

        return '';
    }

    public function setCssFileBlock($css_file, $styles) {
        try {
            # Check if the block styles file exists
            $file_name = SHGAMES_PLUGIN_DIR.'dist/'.$css_file;
            if (!file_exists($file_name)) {
               error_log(print_r([
                    'message' => 'SH Games / setCssFileBlock: Block style file not found.',
                    'css_file' => $css_file,
                ], true));
    
                return;
            }

            # Get the content of the styles file
            $check_content_file = file_get_contents($file_name);

            # Clean old styles
            $clear_css = preg_replace('/\/\*open-auto-code\*\/[\s\S]+?\/\*close-auto-code\*\//', '', $check_content_file);
            
            # Update possible new styles in the block
            $spaces = (strlen($check_content_file) == strlen($clear_css)) ? "\n\n" : "";
            $css_new = $clear_css.$spaces."/*open-auto-code*/".implode(' ', $styles)."/*close-auto-code*/";
            file_put_contents($file_name, $css_new, LOCK_EX);
        } catch (\Exception $exception) {
           error_log(print_r([
                'message' => sprintf('SH Games / setCssFileBlock: %s', $exception->getMessage()),
                'css_file' => $css_file,
                'styles' => $styles,
            ], true));
        }
    }
}
