<?php

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

/**
 * Class Sh_Handicappers_Helpers
 *
 * This class contains repetitive functions that
 * are used globally within the plugin.
 *
 * @package		SHHANDICAP
 * @subpackage	Classes/Sh_Handicappers_Helpers
 * @author		IT
 * @since		1.0.0
 */
class Sh_Handicappers_Helpers{

     public function output_text($text = '') {
         echo $text;
     }

     private $redis_cache;
     private $redis_cache_group;
 
     function __construct() {
         $this->redis_cache = $this->initRedis();
         $this->setRedisGroup();
     }
 
     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 getRedisKeyHandicappers() {
        return 'shh_handicapers';
    }

     public function getHadicappersOptions($file_path = null) {    
        $key = $this->getRedisKeyHandicappers();

        if ($this->initRedis()) {
            $this->setRedisGroup(REDIS_GROUP_SHHANDICAP);            
            $handicappers = $this->getRedis($key);
    
            if (!empty($handicappers) && $file_path == null) {
                $unserialize_data = unserialize($handicappers);
   
                if (is_array($unserialize_data) && count($unserialize_data) > 0) {
                    return $unserialize_data;
                }
            }
        }

        $url = get_field('shh_data_url', 'options');
        $request_url = $this->getApiUrl($url);
        $response = $this->getApiRequest($request_url);

        if ($file_path) {
            file_put_contents($file_path, $response['data']);

            return;
        }

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

            if ($response_json != null) {
                $handicapperOptions = [];     

                foreach ($response_json as $json_key => $item) {
                    $handicapperOptions[$item['id']] = $item['name'];
                }

                asort($handicapperOptions);
                                
                if ($this->initRedis() && is_array($handicapperOptions) && count($handicapperOptions) > 0) {
                    $this->setRedis($key, serialize($handicapperOptions), SHHANDICAP_REDIS_TIMEOUT);
                }
                    
                return $handicapperOptions;
            }
        }

        return [];
    }

    public function getApiUrl($url, $params='') {
        return $url.'?api_token='.$this->getToken().$params;
    }

    public function getToken() {
        return get_field('shh_token', 'options');
    }

    public function getApiRequest($request, $method = 'GET', $headers = []) {
        $curl = curl_init();
        $response = [];

        curl_setopt_array($curl, [
            CURLOPT_URL => $request,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
        ]);

        try {
            $api_response = curl_exec($curl);
            curl_close($curl);
        } catch (Exception $exception) {
            curl_close($curl);
            $response['http_code'] = 'api_request';

            return $response;
        }

        $response['http_code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $response['data'] = $api_response;
        
        return $response;
    }

    public function isJson($string) {
        if (empty($string)) {
            return null;
        }
    
        $decoded = json_decode($string, true);
    
        if (json_last_error() === JSON_ERROR_NONE) {
            return $decoded;
        }
    
        return null;
    }

    public function getAapiError($error, $attributes = null) {
        if ($error == 0) {
            $message = 'Invalid or unavailable URL.';
            error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

            return __($message);
        }

        if ($error == 404) {
            $message = 'Resource not found.';
            error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

            return __($message);
        }

        if ($error == 401) {
            $message = 'Not authorized.';
            error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

            return __($message);
        }
        
        if ($error == 'json_response') {
            $message = 'Invalid data format.';
            error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

            return __($message);
        }

        if ($error == 'api_request') {
            $message = 'The request could not be processed.';
            error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

            return __($message);
        }

        $message = 'The data could not be accessed, please try again later.';
        error_log(print_r(['error' => $error, 'message' => $message, 'attributes' => $attributes], true));

        return $message;
    }

    public function parseFeedFile($file_path) {
        $file = file_get_contents($file_path);
        $json = json_decode($file, true);

        if (json_last_error() != JSON_ERROR_NONE) {
            WP_CLI::line(sprintf(__('ERROR: %s', 'SportsHub Handicappers'), json_last_error_msg()));
            return false;
        }

        return $json;
    }

    public function getQueryParams($array) {
        $params = [];
    
        foreach ($array as $key => $value) {
            $params[] = $key . '=' . urlencode($value);
        }
    
        return implode('&', $params);
    }

    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 webpack($file, $buildDirectory = 'dist') {
        static $manifest;
        static $manifestPath;

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

            $manifestPath = $buildDirectory;
        }

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

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