<?php
class ftr_geral
{

    public static function juroComposto($capital, $tempo, $juros, $tipo = 0)
    {
        /* https://mepoupe.com/simuladores-online-de-investimentos/simulador-de-juros-composto/
           Para validar testes com juros compostos... util para testar parcelamento */

        $juros = !empty($juros) ? preg_replace('/[^0-9\s]+/', '.', $juros) : 0;
        settype($juros, 'float');

        $m = $capital * pow((1 + ($juros / 100)), $tempo);

        if ($tipo == 0) {
            return $m;
        } else {
            return ($m / $tempo);
        }
    }

    public static function MaskCard($tamanho, $inicio = '', $fim = '')
    {
        $numMask = $tamanho - (strlen($inicio) + strlen($fim));
        $string = $inicio;
        for ($cont = 0; $cont < $numMask; $cont++) {
            $string .= '*';
        }
        $string .= $fim;
        return $string;
    }

    public static function getUrlLink($arrayIgnore, $urls)
    {

        if (count($arrayIgnore) > 0) {
            foreach ($urls as $key => $value) {
                if (!in_array($key, $arrayIgnore) && !is_array($value)) {
                    $return[] = $key . '=' . $value;
                }
            }
        } else {
            foreach ($urls as $key => $value) {
                $return[] = $key . '=' . $value;
            }
        }

        if ($return) {
            $return =  implode("&", $return) . "";
        } else {
            $return = '';
        }

        return $return;
    }

    public static function ConvertCaracter($array = array())
    {
        $data = array();

        foreach ($array as $key => $value) {
            if (!is_string($value)) {
                $data[$key] =  $value;
            } else {
                $data[$key] = htmlspecialchars_decode($value);
            }
        }
        return $data;
        //return htmlspecialchars_decode($teste);
    }

    public static function isIsset($varconfig, $module = false)
    {

        $retorno = false;
        if (isset($varconfig)) {
            $retorno = ($module) ? $varconfig : true;
        } else {
            $retorno = false;
        }

        return $retorno;
    }

    public static function callJson($url, $posts = null)
    {

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //returns the transference value like a string
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded')); //sets the header
            curl_setopt($ch, CURLOPT_URL, $url); //oauth API
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 4000); //time out em segundos

            //descomentar as estas opçoes caso for testar curl local para que funcione com o ssl 'falso';
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

            if (isset($posts)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
            }

            $jsonresult = curl_exec($ch); //execute the conection
            if ($jsonresult === false) {
                throw new Exception(curl_error($ch));
            } else {
                $information = curl_getinfo($ch);
                curl_close($ch);
                $result = json_decode($jsonresult, true);
                return  $result;
            }
        } catch (Exception $e) {
            $log = new Log('errorCallJson.txt');
            $error  = 'Url: ' . $url . PHP_EOL;
            $error .= 'Excecao capturada: ' . $e->getMessage();
            $log->write($error);
            throw $e;
        }
    }

    public static function isSelected($value, $baseValue, $defaultValue = '')
    {

        $baseValue = ($baseValue !== '' && !is_null($baseValue)) ? $baseValue : $defaultValue;

        if ($baseValue !== '' && !is_null($baseValue)) {
            if ($value == $baseValue) {
                return "selected='selected'";
            } else {
                return null;
            }
        }
    }

    public static function isChecked($value, $baseValue, $defaultValue = '')
    {

        $baseValue = ($baseValue !== '' && !is_null($baseValue)) ? $baseValue : $defaultValue;

        if ($baseValue !== '' && !is_null($baseValue)) {
            if (is_array($baseValue) && in_array($value, $baseValue)) {
                return "checked='checked'";
            } elseif ($value == $baseValue) {
                return "checked='checked'";
            } else {
                return null;
            }
        }
    }


    public static function setTypeInArray($data)
    {

        $array = array();

        foreach ($data['type'] as $key => $value) {
            $default = isset($data['default']) ? $data['default'] : '';
            switch ($data['compare_type']) {
                case 'selected':
                    $status = isset($data['compare']) || isset($data['default']) ? ftr_geral::isSelected($key, $data['compare'], $default) : false;
                    break;
                case 'checked':
                    if (is_array($data['compare']) && array_key_exists($key, $data['compare'])) {
                        $status = isset($data['compare']) || isset($data['default']) ? ftr_geral::isChecked($key, $data['compare'][$key], $default) : false;
                    } else {
                        $status = isset($data['compare']) || isset($data['default']) ? ftr_geral::isChecked($key, $data['compare'], $default) : false;
                    }
                    break;
            }

            $array[] = array(
                'id' => $key,
                'name' => $value,
                'status' => $status
            );
        }

        return $array;
    }

    public static function isActive($value)
    {
        if ($value >= 1) {
            return "Habilitado";
        } else if ($value == 0) {
            return "Desabilitado";
        }
    }

    public static function isType($value, $arrayTypes, $typeDefault)
    {

        if (!is_null($value) && $value !== '' && in_array($value, array_keys($arrayTypes))) {
            return $value;
        } else {
            return $typeDefault;
        }
    }

    public static function AlterFile($file, $beginExp, $endExp, $action)
    {
        $linha = file($file, FILE_IGNORE_NEW_LINES);
        $inicio = $beginExp;
        $fim    = $endExp;
        for ($i = 0; $i < sizeof($linha); $i++) {
            if (strpos($linha[$i], $inicio)) {
                for ($j = $i + 1; $j < sizeof($linha); $j++) {
                    if (strpos($linha[$j], $fim)) {
                        file_put_contents($file, implode(PHP_EOL, $linha));
                    } else {
                        if ($action) {
                            if (!strstr($linha[$j], "#")) {
                                $linha[$j] = '#' . $linha[$j];
                            }
                        } else {
                            $linha[$j] = str_replace('#', '', $linha[$j]);
                        }
                    }
                }
            }
        }
    }

    public static function AlterHtaccess($file, $beginExp, $endExp, $dominio, $string)
    {

        $resDominio = ftr_geral::getDominioHtaccess($dominio['dominio']);

        if ($dominio['dominio_lista_escolar']) {
            $dominio_lista_escolar = ftr_geral::getDominioHtaccess($dominio['dominio_lista_escolar']);
            if (substr($dominio_lista_escolar, 0, 2) == '\.') {
                $dominio_lista_escolar = substr($dominio_lista_escolar, 2, (strlen($dominio_lista_escolar) - 2));
            }
            $string = str_replace('DOMINIO_LISTA_ESCOLAR', $dominio_lista_escolar, $string);
        }

        if (substr($resDominio, 0, 2) == '\.') {
            $resDominio = substr($resDominio, 2, (strlen($resDominio) - 2));
        }

        if ($resDominio) {
            $result = explode(PHP_EOL, str_replace('DOMINIO', $resDominio, $string));

            $linha  = file($file, FILE_IGNORE_NEW_LINES);
            $aux    = 0;
            for ($i = 0; $i < sizeof($linha); $i++) {
                if (strpos($linha[$i], $beginExp)) {
                    for ($j = $i + 1; $j < sizeof($linha); $j++) {
                        if (strpos($linha[$j], $endExp)) {
                            file_put_contents($file, implode(PHP_EOL, $linha));
                            break;
                        } else {
                            $linha[$j] = $result[$aux];
                            $aux++;
                        }
                    }
                }
            }
        }
    }

    public static function getDominioHtaccess($dominio)
    {
        if (strpos($dominio, '.futurasistemas') == false) {
            return implode('\.', array_map(function ($value) {
                $value = str_replace(['https://', 'http://', 'www'], '', $value);
                if ($value != '') {
                    if (strpos($value, '/') > 0) {
                        return substr($value, 0, strpos($value, '/'));
                    } else {
                        return $value;
                    }
                }
            }, explode('.', $dominio)));
        }
        return false;
    }

    public static function mask($val, $mask)
    {
        $maskared = '';
        $k = 0;
        for ($i = 0; $i <= strlen($mask) - 1; $i++) {
            if ($mask[$i] == '#') {
                if (isset($val[$k]))
                    $maskared .= $val[$k++];
            } else {
                if (isset($mask[$i]))
                    $maskared .= $mask[$i];
            }
        }
        return $maskared;
    }

    public static function validaDate($data)
    {
        $str = str_replace('/', '-', $data);
        $stamp = strtotime($str);
        if (is_numeric($stamp)) {
            $month = date('m', $stamp);
            $day   = date('d', $stamp);
            $year  = date('Y', $stamp);
            return checkdate($month, $day, $year);
        }
        return false;
    }


    public static function formatDate($data, $format, $hora = false)
    {
        $retorno = '';
        if ($hora) {
            $dataArray = explode(' ', $data);
            $data = $dataArray[0];
        }

        if ($format == 'br') {
            $retorno = implode('/', array_reverse(explode('-', $data)));
        } else {
            $retorno = implode('-', array_reverse(explode('/', $data)));
        }
        return ($hora) ? $retorno . ' ' . $dataArray[1] : $retorno;
    }

    public static function compareDate($data1, $data2, $compare)
    {

        switch ($compare) {
            case 'maior':
                return (strtotime(ftr_geral::formatDate($data1, 'en')) > strtotime(ftr_geral::formatDate($data2, 'en')));
                break;
            case 'maiorigual':
                return (strtotime(ftr_geral::formatDate($data1, 'en')) >= strtotime(ftr_geral::formatDate($data2, 'en')));
                break;
            case 'menor':
                return (strtotime(ftr_geral::formatDate($data1, 'en')) < strtotime(ftr_geral::formatDate($data2, 'en')));
                break;
            case 'menorigual':
                return (strtotime(ftr_geral::formatDate($data1, 'en')) <= strtotime(ftr_geral::formatDate($data2, 'en')));
                break;
            case 'igual':
                return (strtotime(ftr_geral::formatDate($data1, 'en')) == strtotime(ftr_geral::formatDate($data2, 'en')));
                break;
        }
    }

    public static function dateTimeZone($value)
    {

        $tz           = new DateTimeZone('America/Sao_Paulo');
        $dataquestion = new DateTime($value);
        $dataquestion->setTimeZone($tz);

        return $dataquestion->format('Y-m-d H:i:s');
    }

    public static function sqlIn($array = array())
    {

        $sqlIn = '(';
        foreach ($array as $key => $value) {
            $sqlIn .= $key . ',';
        }

        return substr($sqlIn, 0, -1) . ')';
    }

    public static function sqlOrderByAdd($orderby, $add)
    {
        if ($orderby == "") {
            return " ORDER BY " . $add;
        } else {
            return  ' ,' . $add;
        }
    }


    public static function getNovidadeModulo($dateValue)
    {

        $return = false;
        $data = new DateTime();
        $dataAtual =  strtotime($data->format('Y-m-d'));

        if (strpos($dateValue, '-') == true) {
            $data = DateTime::createFromFormat('Y-m-d', $dateValue);
            $dataFim = strtotime($data->format('Y-m-d') . ' +60 days');
            if ($dataFim >  $dataAtual) {
                $return = true;
            }
        }

        return $return;
    }

    public static function getUnicCodeAnalize()
    {
        return '&analyze=' . md5(uniqid(rand(), true));
    }

    public static function cripty($value, $chave)
    {
        return hash_hmac('sha256', $value, $chave);
    }

    public static function formatText($text, $qtdcaracter = null)
    {

        if (is_null($qtdcaracter)) {
            return strip_tags(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
        } else {
            return utf8_substr(strip_tags(html_entity_decode($text, ENT_QUOTES, 'UTF-8')), 0, $qtdcaracter) . '...';
        }
    }


    public static function getContentSql($filtro, $content)
    {
        $retorno = '';
        switch ($content) {
            case 1:
                $retorno = " = '" . $filtro . "'";
                break;
            case 2:
                $retorno = " LIKE '" . $filtro . "%'";
                break;
            case 3:
                $retorno = " LIKE '%" . $filtro . "'";
                break;
            default:
                $retorno = " LIKE '%" . $filtro . "%'";
                break;
        }
        return $retorno;
    }

    public static function getContentSqlValue($campo, $filtro, $content)
    {
        $retorno = '';
        switch ($content) {
            case 0:
                $retorno = $campo . ' > ' . $filtro;
                break;
            case 1:
                $retorno = $campo . ' >= ' . $filtro;
                break;
            case 2:
                $retorno = $campo . ' = ' . $filtro;
                break;
            case 3:
                $retorno = $campo . ' <= ' . $filtro;
                break;
            case 4:
                $retorno = $campo . ' < ' . $filtro;
                break;
            case 5:
                $retorno = $campo . ' <> ' . $filtro;
                break;
        }
        return $retorno;
    }

    public static function isEAN12($upccode)
    { // também conhecido como UPC
        $odd_sum = $even_sum = 0;
        if (strlen($upccode) != 12) return FALSE;
        $chars = str_split($upccode);
        for ($i = 0; $i < 11; $i++) {
            if ($i % 2 == 0) {
                $odd_sum += $chars[$i] * 3;
            } else {
                $even_sum += $chars[$i];
            }
        }
        $total_sum = $even_sum + $odd_sum;

        $modulo10 = $total_sum % 10;
        $check_digit = 10 - $modulo10;
        return (int)$chars[11] === $check_digit;
    }

    public static function isEAN8($upccode)
    { // também conhecido como GTIN
        $odd_sum = $even_sum = 0;
        if (strlen($upccode) != 8) return FALSE;
        $chars = str_split($upccode);
        for ($i = 0; $i < 7; $i++) {
            if ($i % 2 == 0) {
                $odd_sum += $chars[$i] * 3;
            } else {
                $even_sum += $chars[$i];
            }
        }
        $total_sum = $even_sum + $odd_sum;

        $modulo10 = $total_sum % 10;
        $check_digit = 10 - $modulo10;
        return (int)$chars[7] === $check_digit;
    }

    public static function isEAN13($upccode)
    { // também conhecido como EAN13 mesmo kkkk
        $odd_sum = $even_sum = 0;
        if (strlen($upccode) != 13) return FALSE;
        $chars = str_split($upccode);
        for ($i = 0; $i < 12; $i++) {
            if ($i % 2 == 0) {
                $odd_sum += $chars[$i];
            } else {
                $even_sum += $chars[$i] * 3;
            }
        }
        $total_sum = $even_sum + $odd_sum;

        $modulo10 = $total_sum % 10;
        $check_digit = 10 - $modulo10;
        return (int)$chars[12] === $check_digit;
    }


    public static function exibeMuduloLayout($layout)
    {
        if (isset($session->data['api_key'])) {
            if (($layout == Type_DisplayModuleOption::Tp_Todos) || ($layout == Type_DisplayModuleOption::Tp_Aplicativo)) {
                return true;
            }
        } else if (($layout == Type_DisplayModuleOption::Tp_Todos) || ($layout == Type_DisplayModuleOption::Tp_Ecommerce)) {
            return true;
        } else {
            return false;
        }
    }

    /*Remove parte de uma string a partir do caracter especificado*/
    public static function removeString($string, $caracter, $inicio = 0)
    {
        $posicao = strpos($string, $caracter);
        if ($posicao) {
            $retorno = substr($string, $inicio, $posicao);
        } else {
            $retorno = $string;
        }
        return $retorno;
    }

    public static function getDataZone($value)
    {
        $tz = new DateTimeZone('America/Sao_Paulo');
        $data = new DateTime($value);
        return $data->setTimeZone($tz);
    }

    public static function getDataZoneFormat($value)
    {
        $data = ftr_geral::getDataZone($value);
        return $data->format('d/m/Y H:m:s');
    }

    public static function setCookie($name, $value, $time = false)
    {
        if (is_array($value)) {
            $value = rawurlencode(json_encode($value));
        }
        if ($time) {
            setcookie($name, $value, $time);
        } else {
            setcookie($name, $value);
        }
    }

    public static function calculaDescontoPromocao($preco, $precoPromocao)
    {
        return round(($precoPromocao * 100) / $preco - 100) . "%";
    }

    public static function getArrayTypes($arrayTypes, $valueCampo, $valueDefault, $check = false)
    {
        $array = array();
        foreach ($arrayTypes as $key => $value) {
            $array[] = array(
                'value'       => $key,
                'description' => ucfirst($value),
                'description_value' => $value,
                'choice'      => ($check) ? ftr_geral::isChecked($key, $valueCampo, $valueDefault) : ftr_geral::isSelected($key, $valueCampo, $valueDefault)
            );
        }
        return $array;
    }

    public static function getDescriptionToTypes($array, $campo = 'select', $return = 'description')
    {
        return array_reduce($array, function ($result, $item) use (&$campo, &$return) {
            if (!is_null($item[$campo])) {
                $result = $item[$return];
            }
            return $result;
        }, 0);
    }

    public static function in_array_r($needle, $haystack, $strict = false)
    {
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && ftr_geral::in_array_r($needle, $item, $strict))) {
                return true;
            }
        }

        return false;
    }

    public static function MetrosToCm($cm)
    {
        return $cm * 100;
    }

    public static function removeAcentos($str)
    {
        $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'Ĳ', 'ĳ', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ŉ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
        $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
        return str_replace($a, $b, $str);
    }

    public static function getStrToIndex($texto)
    {
        //Para quando precisar transformar um texto em indice, util para as funções de template
        $texto = str_replace(".", "", $texto);
        $texto = str_replace(",", "", $texto);
        return strtoupper(str_replace(" ", "_", preg_replace("/&([^a-zA-Z0-9])[^a-zA-Z0-9]+;/i", "$1", ftr_geral::removeAcentos(trim($texto)))));
    }

    public static function getPaymentMethods($payment_method, $total)
    {

        if ($payment_method) {

            return array_filter(array_map(function ($array) use ($total) {

                if (isset($array['status']) && ($array['status'] == '0')){
                    return false;
                }

                if (isset($array['valor_minimo']) && ($array['valor_minimo'] != '') && ($total >= (float) preg_replace("/[^\.|,|0-9]/", "", $array['valor_minimo']))) {
                    return $array;
                } else if (isset($array['valor_minimo']) && ($array['valor_minimo'] == '')) {
                    return $array;
                } else {
                    return false;
                }
            }, $payment_method));
        }
    }

    public static function getPaymentDiscount($array_desconto, $total, $cart_total)
    {

        $desconto = false;
        array_walk($array_desconto, function ($array, $key) use ($total, &$desconto, &$cart_total) {
            if (isset($array['desconto']) && (!empty($array['desconto']))) {
                if ($array['tipo_desconto'] == Type_MarketplaceAdjustmentPrice::Tp_Percentual) {
                    $desconto = (((float) $array['desconto'] * $cart_total) / 100) * (-1);
                } else {
                    $desconto = ($array['desconto'] * (-1));
                }
            }
        });

        return $desconto;
    }

    public static function getLimitFireBird($data)
    {
        $limit = '';
        if (isset($data['start'])) {
            $limit .= 'first ' . $data['start'];

            if (isset($data['limit']) && ($data['limit'])) {
                $limit .= ' skip ' . $data['limit'];
            }
        }

        return $limit;
    }

    public static function isInDevelopping()
    {
        return ((defined('AMBIENTE_TESTE')) && (AMBIENTE_TESTE));
    }

    public static function setUrlRewrite($file, $folderPathLink, $exec)
    {

        $fileLinesList = array();
        $handle = fopen($file, 'r');
        while (!feof($handle)) {
            $fileLinesList[] = fgets($handle);
        }
        fclose($handle);

        foreach ($fileLinesList as $key => $linha) {

            if ((strpos($linha, "RewriteBase")) !== false) {
                if ($exec) {
                    $folderPathLink   = trim($folderPathLink);
                    $folderPathLink   = str_replace('\\', '/', $folderPathLink);

                    if (substr($folderPathLink, 0, 1) != "/") {
                        $folderPathLink = '/' . $folderPathLink;
                    }

                    if (substr($folderPathLink, strlen($folderPathLink) - 1, 1) != "/") {
                        $folderPathLink = $folderPathLink . '/';
                    }

                    $fileLinesList[$key] = "RewriteBase " . $folderPathLink . "\r\n";
                } else {

                    $fileLinesList[$key] = "#RewriteBase " . $folderPathLink . "\r\n";
                }
            }
        }

        $handle = fopen($file, 'w+');
        foreach ($fileLinesList as $linha) {
            fwrite($handle, $linha);
        }
        fclose($handle);
    }

    public static function removeMaskToInt($value)
    {
        return preg_replace('/\D/i', '', $value);
    }

    public static function removeMaskToDouble($value)
    {
        $value = $value = str_replace(['.', ','], ['', '.'], $value);
        return preg_replace('/[^\d\.]+/i', '', $value);
    }

    public static function getOrderAddressFormatted($order_info, $typeAddress)
    {
        switch ($typeAddress) {
            case Type_Address::Tp_Faturamento:
                return self::getAddressFormatted(
                    $order_info['payment_address_1'],
                    $order_info['payment_address_2'],
                    $order_info['payment_city'],
                    $order_info['payment_numero'],
                    $order_info['payment_complemento'],
                    $order_info['payment_postcode'],
                    $order_info['payment_zone'],
                    $order_info['payment_country'],
                    $order_info['payment_apelido'],
                    $order_info['payment_firstname'],
                    $order_info['payment_lastname'],
                    $order_info['payment_company']
                );
                break;
            case Type_Address::Tp_Entrega:
                return self::getAddressFormatted(
                    $order_info['shipping_address_1'],
                    $order_info['shipping_address_2'],
                    $order_info['shipping_city'],
                    $order_info['shipping_numero'],
                    $order_info['shipping_complemento'],
                    $order_info['shipping_postcode'],
                    $order_info['shipping_zone'],
                    $order_info['shipping_country'],
                    $order_info['shipping_apelido'],
                    $order_info['shipping_firstname'],
                    $order_info['shipping_lastname'],
                    $order_info['shipping_company']
                );
                break;
            case Type_Address::Tp_Retirada:
                if (
                    empty($order_info['pickup_address']) ||
                    empty($order_info['pickup_number']) ||
                    empty($order_info['pickup_neighborhood']) ||
                    empty($order_info['pickup_city'])
                ) {
                    return '';
                } else {
                    return self::getAddressFormatted(
                        $order_info['pickup_address'],
                        $order_info['pickup_neighborhood'],
                        $order_info['pickup_city'],
                        $order_info['pickup_number'],
                        $order_info['pickup_complement'],
                        $order_info['pickup_postcode'],
                        $order_info['pickup_zone']
                    );
                }
                break;
        }
    }

    public static function getAddressFormatted(
        $address,
        $neighborhood,
        $city,
        $number,
        $complement,
        $postcode,
        $zone,
        $country = '',
        $nickname = '',
        $firstname = '',
        $lastname = '',
        $company = ''
    ) {
        $format = '{nickname}' . "\n" . '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address}, {number}{complement}' . "\n" . "\n" . '{neighborhood}' . "\n" . '{city}' . "\n" . '{zone}' . "\n" . '{country}' . "\n" . '{postcode}';

        $find = array(
            '{address}',
            '{neighborhood}',
            '{city}',
            '{number}',
            '{complement}',
            '{postcode}',
            '{zone}',
            '{country}',
            '{nickname}',
            '{firstname}',
            '{lastname}',
            '{company}',
        );

        $replace = array(
            'address' => $address,
            'neighborhood' => $neighborhood,
            'city' => $city,
            'number' => $number,
            'complement' => $complement ? ', ' . $complement : '',
            'postcode' => $postcode,
            'zone' => $zone,
            'country' => $country,
            'nickname' => $nickname,
            'firstname' => $firstname,
            'lastname' => $lastname,
            'company' => $company,
        );

        return str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
    }

    public static function getParcelamento($total, $subtotal, $parcela_minima, $parametros_parcela)
    {
        $retorno = array();
        foreach ($parametros_parcela as $param_parcela) {
            if ((isset($param_parcela['val_minimo'])) && (!empty($param_parcela['val_minimo'])) && ($param_parcela['val_minimo'] > $total)) {
                continue;
            }
            if (!isset($param_parcela['num_parcela'])){
                continue;
            }

            switch ($param_parcela['tipo_calculo']) {
                case Type_CalculoParcelamento::SemJuros:
                    $parcela = $total / $param_parcela['num_parcela'];
                    $detalhe_parcela = ' (sem juros)';
                    break;
                case Type_CalculoParcelamento::Juros:
                    $parcela = ftr_geral::juroComposto($total, $param_parcela['num_parcela'], $param_parcela['percentual_calculo'], 1);
                    $detalhe_parcela = ' (juros de '.$param_parcela['percentual_calculo'].'% a.m)';
                    break;
                case Type_CalculoParcelamento::Desconto:
                    $parcela = ($total / $param_parcela['num_parcela']) - (($subtotal / $param_parcela['num_parcela']) * ($param_parcela['percentual_calculo'] / 100));
                    $detalhe_parcela = ' (desconto de '.$param_parcela['percentual_calculo'].'%)';
                    break;
            }

            $parcela = round($parcela, 2, PHP_ROUND_HALF_UP);

            if ($parcela >= $parcela_minima) {
                $retorno[$param_parcela['num_parcela']] = array(
                    'num_parcela'  => $param_parcela['num_parcela'],
                    'tipo_calculo' => $param_parcela['tipo_calculo'],
                    'percentual_calculo' => $param_parcela['percentual_calculo'] ?? 0,
                    'valor_parcela' => $parcela,
                    'detalhe_parcela' => $detalhe_parcela
                );
            } else {
                //alteração feita para que ao atigir o valor minimo de parcela, retorne as parcelas disponiveis
                return $retorno;
            }
        }

        return $retorno;
    }

    public static function getParcelamentoPadrao($total, $subtotal, $parametros_parcelamento)
    {
        /* Ajusta as configurações padrões do módulo para gerar os parametros por parcela */
        $parametros_parcela = array();
        for ($parc = 1; $parc <= $parametros_parcelamento['parcela_com_desconto']; $parc++) {
            if($parametros_parcelamento['desconto'] <= 0){
              continue;
            }
          $parametros_parcela[] = array (
                'num_parcela'  => $parc,
                'val_minimo'   => 0,
                'tipo_calculo' => Type_CalculoParcelamento::Desconto,
                'percentual_calculo' => $parametros_parcelamento['desconto']
            );
        }

        $parc = count($parametros_parcela) + 1 ;

        $percentual_calculo = 0 ;
        for ($parc; $parc <= $parametros_parcelamento['parcela_maxima_qtd']; $parc++) {
             if ($parc <= ($parametros_parcelamento['parcela_sem_juros'] + $parametros_parcelamento['parcela_com_desconto'])) {
                $tipo_calculo = Type_CalculoParcelamento::SemJuros;
            } else {
                $tipo_calculo = Type_CalculoParcelamento::Juros;
                $percentual_calculo = $parametros_parcelamento['juros'];
            }
            $parametros_parcela[] = array (
                'num_parcela'  => $parc,
                'val_minimo'   => 0,
                'tipo_calculo' => $tipo_calculo,
                'percentual_calculo' => $percentual_calculo
            );
        }

        return ftr_geral::getParcelamento($total, $subtotal, $parametros_parcelamento['parcela_minima_val'], $parametros_parcela);
    }

    public static function arraySort($array, $on, $order = SORT_ASC): array
    {
        $newArray = [];
        $sortableArray = [];

        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortableArray[$k] = $v2;
                        }
                    }
                } else {
                    $sortableArray[$k] = $v;
                }
            }

            switch ($order) {
                case SORT_ASC:
                    asort($sortableArray);
                    break;
                case SORT_DESC:
                    arsort($sortableArray);
                    break;
            }

            foreach ($sortableArray as $k => $v) {
                $newArray[] = $array[$k];
            }
        }

        return $newArray;
    }

    public static function toFloat($num): float
    {
        $dotPos = strrpos($num, '.');
        $commaPos = strrpos($num, ',');
        $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
            ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

        if (!$sep) {
            return floatval(preg_replace("/[^0-9]/", "", $num));
        }

        return floatval(
            preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
            preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
        );
    }

    public static function deleteFolder($dir){
        $files = array_diff(scandir($dir), array('.','..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file"))
                ? ftr_geral::deleteFolder("$dir/$file") //aqui o file pode ser uma pasta por isso ele chama a funcao novamente
                : unlink("$dir/$file");
        }
        rmdir($dir);
    }

    public static function base64url_encode($data)
    {
        $b64 = base64_encode($data);

        if ($b64 === false) {
            return false;
        }

        // Convert Base64 to Base64URL by replacing “+” with “-” and “/” with “_”
        $url = strtr($b64, '+/', '-_');

        // Remove padding character from the end of line and return the Base64URL result
        return rtrim($url, '=');
    }

    public static function base64url_decode($data, $strict = false)
    {
        // Convert Base64URL to Base64 by replacing “-” with “+” and “_” with “/”
        $b64 = strtr($data, '-_', '+/');

        // Decode Base64 string and return the original data
        return base64_decode($b64, $strict);
    }
}
