<?php

	if ( ! defined( 'ABSPATH' ) ) exit;

        require_once __DIR__ . "/../Kernel/API/Entity/DigitalSignage4_DemandeEntity.php";
	

    class DigitalSignage4_Tools
    {
        public static function getUrlRedirect($page)
        {
            return 'admin.php?page=' . $page;
        }
		
		public static function get_site_logo_url(){
			
			$custom_logo_id = get_theme_mod('custom_logo'); // Récupère l'ID du logo
			$logo = wp_get_attachment_image_src($custom_logo_id, 'full'); // Récupère l'URL du logo
			if (has_custom_logo()) {
				return esc_url($logo[0]); // Retourne l'URL absolue du logo
			} else {
				return self::getModuleUrl()."Files/no.png";
			}
		}

        public static function redirectAdmin($page)
        {
            if (self::isPrestashop()) {
                switch ($page) {

                    case 'DigitalSignageSettings':
                        header('Location: ' . 'index.php?controller=Reglages&token=' . DigitalSignage4_Tools2::getAdminTokenLite('Reglages'));
                        break;

                    case 'DigitalSignageHome':
                        header('Location: ' . 'index.php?controller=Accueil&token=' . DigitalSignage4_Tools2::getAdminTokenLite('Accueil'));
                        break;

                    default:
                        header('Location: ' . isset($_SERVER['REQUEST_URI'])?sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])):"");
                        break;

                }
            } else {
                header('Location: ' . self::getUrlRedirect($page));
            }


            exit;
        }

        public static function isHttps()
        {
            return isset($_SERVER['HTTPS']) && sanitize_text_field(wp_unslash($_SERVER['HTTPS'])) == 'on';
        }

        public static function isPrestashop()
        {
            return defined('_PS_VERSION_');
        }

        public static function getModuleImgUrl()
        {
            return esc_url(self::getModuleUrl() . "kernel/Views/img/");
        }

        public static function reverseMagicQuote($var) // Fonction qui supprime l'effet des magic quotes
        {
            if (is_array($var)) { // Si la variable passée en argument est un array, on appelle la fonction stripslashes_r dessus
                return array_map(array('DigitalSignage4_Tools', 'reverseMagicQuote'), $var);
            } else { // Sinon, un simple stripslashes suffit
                return stripslashes($var);
            }
        }

        public static function getAcaciaRedirectionPageUrl($page,$trial="no")
        {
            $lang = substr(get_bloginfo('language'), 0, 2);
            $cms = "wordpress";
            $siteUrl = urlencode(home_url());
            $currency = urlencode(get_option('woocommerce_currency'));
            return esc_url("https://productvideo.io/redirection/ds4_redirect.php?page=" . $page . "&lang=" . $lang . "&cms=" . $cms . "&website=" . $siteUrl . "&currency=" . $currency."&trial=".$trial);
        }


        public static function getModuleUrl()
        {
            return esc_url(str_replace('/Classes', "", plugin_dir_url(__FILE__)));
        }

        public static function getModuleVideoUrl()
        {
            //return esc_url(self::getModuleUrl() . "Videos/");
			$upload_dir = wp_upload_dir();
			return esc_url($upload_dir['baseurl'] . '/' . 'ds4' . '/Videos/');
        }

        public static function getShopBaseUrl()
        {
            return "";
        }

        public static function getModuleImgDir()
        {
            return (self::getModuleDir() . '../Files/');
        }

        public static function getModuleDir()
        {
            return (plugin_dir_path(__FILE__));
        }

        public static function getProductsUrl()
        {
            if (self::isPrestashop()) {
                return esc_url(Context::getContext()->link->getAdminLink('AdminProducts', true));
            } else {
                return esc_url(get_admin_url() . "edit.php?post_type=product");
            }
        }


        /**
         * @param DigitalSignage4_DemandeEntity[] $videos
         */
        public static function convertPoductIdToLink($videos)
        {
            return array_map(
                function ($video) {
                    $product = wc_get_product($video->getProductId());

                    if ($product) {
                        $permalink = $product->get_permalink();
                        $video->setProductId("<a target='_blank' href='" . $permalink . "'>" . $product->get_name() . "</a>");
                    }

                    return $video;
                },
                $videos
            );
        }

        public static function displayError($error)
        {
            echo ('<div class="error"><p>' . esc_html($error). '</p></div>');
        }


        public static function callDS4DemandeAPI($datas)	{
                $responseAPI = null;

                try {
                        // Préparation des arguments pour la requête
                        $args = [
                                'method'  => 'POST',
                                'timeout' => 5,
                                'headers' => [
                                        'Content-Type' => 'application/x-www-form-urlencoded',
                                        'Authorization' => DigitalSignage4_ForfaitManager::instance()->getToken()
                                ],
                                'body'    => $datas,
                        ];

                        // Effectuer la requête
                        $response = wp_remote_post("https://api.productvideo.io/API_v2/Demande/", $args);

                        // Vérification de la réussite de la requête
                        if (is_wp_error($response)) {
                                echo esc_html($response->get_error_message());
                                die();
                        }

                        $http_code = wp_remote_retrieve_response_code($response);
                        if ($http_code === 200) {
                                // Récupération du corps de la réponse
                                $responseAPI = wp_remote_retrieve_body($response);
                        } else {
                                echo esc_html("Ressource introuvable : " . $http_code);
                        }
                } catch (\Throwable $th) {
                        throw $th;
                }

                return $responseAPI;
        }
        /**
         * retourne le numero de version du module Digital Signage
         * @return mixed
         */
        public static function getModuleInformations()
        {
            return get_plugin_data(__DIR__ . '/../digitalsignage4.php', false, false);
        }

        public static function getWordpressBasePath()
        {
            $currentPath = isset($_SERVER['SCRIPT_FILENAME'])?sanitize_text_field(wp_unslash($_SERVER['SCRIPT_FILENAME'])):"";
            $pathExploded = explode('wp-content', $currentPath);
            return $pathExploded[0];
        }

        public static function getWooCommerceDevice($currency = '', $defaultCurrency = "EUR")
        {
            if (!$currency) {
                $currency = $defaultCurrency;
                if (function_exists("get_woocommerce_currency")) {
                    $currency = get_woocommerce_currency();
                }
            }

            $symbols = apply_filters('woocommerce_currency_symbols', array(
                'AED' => 'د.إ',
                'AFN' => '؋',
                'ALL' => 'L',
                'AMD' => 'AMD',
                'ANG' => 'ƒ',
                'AOA' => 'Kz',
                'ARS' => '$',
                'AUD' => '$',
                'AWG' => 'ƒ',
                'AZN' => 'AZN',
                'BAM' => 'KM',
                'BBD' => '$',
                'BDT' => '৳ ',
                'BGN' => 'лв.',
                'BHD' => '.د.ب',
                'BIF' => 'Fr',
                'BMD' => '$',
                'BND' => '$',
                'BOB' => 'Bs.',
                'BRL' => 'R$',
                'BSD' => '$',
                'BTC' => '฿',
                'BTN' => 'Nu.',
                'BWP' => 'P',
                'BYR' => 'Br',
                'BZD' => '$',
                'CAD' => '$',
                'CDF' => 'Fr',
                'CHF' => 'CHF',
                'CLP' => '$',
                'CNY' => '¥',
                'COP' => '$',
                'CRC' => '₡',
                'CUC' => '$',
                'CUP' => '$',
                'CVE' => '$',
                'CZK' => 'Kč',
                'DJF' => 'Fr',
                'DKK' => 'DKK',
                'DOP' => 'RD$',
                'DZD' => 'د.ج',
                'EGP' => 'EGP',
                'ERN' => 'Nfk',
                'ETB' => 'Br',
                'EUR' => '€',
                'FJD' => '$',
                'FKP' => '£',
                'GBP' => '£',
                'GEL' => 'ლ',
                'GGP' => '£',
                'GHS' => '₵',
                'GIP' => '£',
                'GMD' => 'D',
                'GNF' => 'Fr',
                'GTQ' => 'Q',
                'GYD' => '$',
                'HKD' => '$',
                'HNL' => 'L',
                'HRK' => 'Kn',
                'HTG' => 'G',
                'HUF' => 'Ft',
                'IDR' => 'Rp',
                'ILS' => '₪',
                'IMP' => '£',
                'INR' => '₹',
                'IQD' => 'ع.د',
                'IRR' => '﷼',
                'IRT' => 'تومان',
                'ISK' => 'kr.',
                'JEP' => '£',
                'JMD' => '$',
                'JOD' => 'د.ا',
                'JPY' => '¥',
                'KES' => 'KSh',
                'KGS' => 'сом',
                'KHR' => '៛',
                'KMF' => 'Fr',
                'KPW' => '₩',
                'KRW' => '₩',
                'KWD' => 'د.ك',
                'KYD' => '$',
                'KZT' => 'KZT',
                'LAK' => '₭',
                'LBP' => 'ل.ل',
                'LKR' => 'රු',
                'LRD' => '$',
                'LSL' => 'L',
                'LYD' => 'ل.د',
                'MAD' => 'د.م.',
                'MDL' => 'MDL',
                'MGA' => 'Ar',
                'MKD' => 'ден',
                'MMK' => 'Ks',
                'MNT' => '₮',
                'MOP' => 'P',
                'MRO' => 'UM',
                'MUR' => '₨',
                'MVR' => '.ރ',
                'MWK' => 'MK',
                'MXN' => '$',
                'MYR' => 'RM',
                'MZN' => 'MT',
                'NAD' => '$',
                'NGN' => '₦',
                'NIO' => 'C$',
                'NOK' => 'kr',
                'NPR' => '₨',
                'NZD' => '$',
                'OMR' => 'ر.ع.',
                'PAB' => 'B/.',
                'PEN' => 'S/.',
                'PGK' => 'K',
                'PHP' => '₱',
                'PKR' => '₨',
                'PLN' => 'zł',
                'PRB' => 'р.',
                'PYG' => '₲',
                'QAR' => 'ر.ق',
                'RMB' => '¥',
                'RON' => 'lei',
                'RSD' => 'дин.',
                'RUB' => '₽',
                'RWF' => 'Fr',
                'SAR' => 'ر.س',
                'SBD' => '$',
                'SCR' => '₨',
                'SDG' => 'ج.س.',
                'SEK' => 'kr',
                'SGD' => '$',
                'SHP' => '£',
                'SLL' => 'Le',
                'SOS' => 'Sh',
                'SRD' => '$',
                'SSP' => '£',
                'STD' => 'Db',
                'SYP' => 'ل.س',
                'SZL' => 'L',
                'THB' => '฿',
                'TJS' => 'ЅМ',
                'TMT' => 'm',
                'TND' => 'د.ت',
                'TOP' => 'T$',
                'TRY' => '₺',
                'TTD' => '$',
                'TWD' => 'NT$',
                'TZS' => 'Sh',
                'UAH' => '₴',
                'UGX' => 'UGX',
                'USD' => '$',
                'UYU' => '$',
                'UZS' => 'UZS',
                'VEF' => 'Bs F',
                'VND' => '₫',
                'VUV' => 'Vt',
                'WST' => 'T',
                'XAF' => 'Fr',
                'XCD' => '$',
                'XOF' => 'Fr',
                'XPF' => 'Fr',
                'YER' => '﷼',
                'ZAR' => 'R',
                'ZMW' => 'ZK',
            ));

            $currency_symbol = isset($symbols[$currency]) ? $symbols[$currency] : '';

            return apply_filters('woocommerce_currency_symbol', $currency_symbol, $currency);
        }
    }
