<?php

class Funcao
{
    static function i18n($t_list, $key, $return = false)
    {
        $result = "";
        if (array_key_exists($key, $t_list)) {
            $result = $t_list[$key];
        } else {
            $result = 'Tradução não encontrada';
        }
        if ($return) {
            return $result;
        } else {
            echo $result;
        }
    }

    static function msg($type, $msg, $return = false)
    {
        $type = strtolower($type);
        $mensagem = "";
        if ($type == "success" || $type == "sucesso") {
            $mensagem = '<div class="ui success center aligned message">' . $msg . '</div>';
        } else if ($type == "alert" || $type == "alerta") {
            $mensagem = '<div class="ui warning center aligned message">' . $msg . '</div>';
        } else if ($type == "Info" || $type == "informacao") {
            $mensagem = '<div class="ui info center aligned message">' . $msg . '</div>';
        } else if ($type == "Error" || $type == "erro") {
            $mensagem = '<div class="ui red left aligned message">' . $msg . '</div>';
        } else {
            $mensagem = '<div class="ui red center aligned message">' . $msg . '</div>';
        }

        if ($return) {
            return $mensagem;
        } else {
            echo $mensagem;
        }
    }

    static function removeIndex($arraydados)
    {
        foreach (array_keys($arraydados) as $key) {
            if (is_numeric($key)) {
                unset($arraydados[$key]);
            } else if (intval($key)) {;
                unset($arraydados[$key]);
            }
        }
        return $arraydados;
    }

    static function removeIndexSub($arraydados)
    {
        foreach ($arraydados as &$subarray) {
            foreach (array_keys($subarray) as $key) {
                if (is_numeric($key)) {
                    unset($subarray[$key]);
                } else if (intval($key)) {
                    unset($subarray[$key]);
                }
            }
        }
        return $arraydados;
    }

    static function BlackList($key, $blacklist)
    {
        foreach ($blacklist as $filter) {
            if (strpos($key, $filter) !== false) {
                return true;
            }
        }
        return false;
    }

    static function remove_caracter_especial_virgula_json($json_string)
    {
        $array_json = explode(',', $json_string);
        foreach ($array_json as $key => $item) {
            $array_json[$key] = trim(preg_replace('/,\s*[\W\s]+/', ',', $item));
        }
        return $array_json;
    }

    // Funções de data 
    function dataHora()
    {
        return date("Y-m-d H:i:s");
    }


    static function ConvertDateToMysql($date)
    {
        if ($date != null) {
            if (str_contains($date, '-')) {
                $dt = $date;
                return $dt;
            } else {
                $d = $date;
                $dt = DateTime::createFromFormat('d/m/Y', $d);
                $dt = $dt->format('Y-m-d');
                return $dt;
            }
        } else {
            return null;
        }
    }

    static function ConvertSearchDateToMysql($date)
    {
        if ($date != null) {
            switch (strlen($date)) {
                case '2':
                    $d = $date;
                    $dt = DateTime::createFromFormat('d', $d);
                    $dt = $dt->format('d');
                    return $dt;
                    break;
                case '4':
                    if (str_contains($date, '/')) {
                        return null;
                    } else {
                        $d = $date;
                        $dt = DateTime::createFromFormat('Y', $d);
                        $dt = $dt->format('Y');
                        return $dt;
                    }
                    break;
                case '5':
                    if (str_contains($date, '-')) {
                        $d = self::ConvertToInt($date);
                        $dt = DateTime::createFromFormat('Y', $d);
                        $dt = $dt->format('Y');
                        return $dt;
                    } else {
                        $d = $date;
                        $dt = DateTime::createFromFormat('d/m', $d);
                        $dt = $dt->format('m-d');
                        return $dt;
                    }
                    break;
                case '7':
                    if (str_contains($date, '-')) {
                        $d = $date;
                        $dt = DateTime::createFromFormat('Y-m', $d);
                        $dt = $dt->format('Y-m');
                        return $dt;
                    } else {
                        $d = $date;
                        $dt = DateTime::createFromFormat('m/Y', $d);
                        $dt = $dt->format('Y-m');
                        return $dt;
                    }
                    break;
                case '10':
                    if (str_contains($date, '-')) {
                        $dt = $date;
                        return $dt;
                    } else {
                        $d = $date;
                        $dt = DateTime::createFromFormat('d/m/Y', $d);
                        $dt = $dt->format('Y-m-d');
                        return $dt;
                    }
                    break;
                default:
                    return null;
                    break;
            }
        } else {
            return null;
        }

        if (str_contains($date, '-')) {
            $dt = $date;
            return $dt;
        } else {
            $d = $date;
            $dt = DateTime::createFromFormat('d/m/Y', $d);
            $dt = $dt->format('Y-m-d');
            return $dt;
        }
    }


    static function ConvertDateFromMysql($date)
    {
        if (is_null($date)) {
            return null;
        } else {
            $date = new DateTime($date);
            return $date->format("d/m/Y");
        }
    }

    function ConvertDatetimeToMysql($date)
    {
        if ($date != null) {
            if (str_contains($date, '-')) {
                $dt = $date;
            } else {
                $d = $date;
                if (strlen($d) > 16) {
                    $dt = DateTime::createFromFormat('d/m/Y H:i:s', $d);
                    $dt = $dt->format('Y-m-d H:i:s');
                } elseif (strlen($d) <= 16 && strlen($d) >= 14) {
                    $dt = DateTime::createFromFormat('d/m/Y H:i', $d);
                    $dt = $dt->format('Y-m-d H:i:00');
                } else {
                    $dt = DateTime::createFromFormat('d/m/Y H', $d);
                    $dt = $dt->format('Y-m-d H:00:00');
                }
            }

            return $dt;
        } else {
            return null;
        }
    }

    static function ConvertDatetimeFromMysql($date)
    {
        if (is_null($date)) {
            echo "";
        } else {
            $date = new DateTime($date);
            return $date->format("d/m/Y H:i:s");
        }
    }
    function DataPadrao($date)
    {
        if (is_null($date)) {
            echo "";
        } else {
            $date = new DateTime($date);
            return $date->format("d/m/Y");
        }
    }

    static function getBase64Size($base64Image, $unit = 'Mb',  $show_unit = true)
    { //return memory size in B, KB, MB
        try {
            $size_in_bytes = (int) (strlen(rtrim($base64Image, '=')) * 3 / 4);
            $size_in_kb    = $size_in_bytes / 1024;
            $size_in_mb    = $size_in_kb / 1024;

            switch ($unit) {
                case 'Mb':
                    $unit = 'size_in_mb';
                    break;
                case 'Kb':
                    $unit = 'size_in_kb';
                    break;
                case 'B':
                    $unit = 'size_in_bytes';
                    break;
                default:
                    return 'Unidade não permitida use Mb, Kb ou B';
                    break;
            }

            return number_format((float) $$unit, 2, '.', '') . ($show_unit == false ? '' : ' Mb');
        } catch (Exception $e) {
            return $e;
        }
    }

    static function ConvertToInt($var)
    {
        if ($var) {
            $var = preg_replace('#[^0-9]#', '', $var);
            return $var;
        }
        return null;
    }

    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;
    }

    static function BRL($value)
    { // CONVERTE VALOR EM REAIS
        return 'R$ ' . number_format($value, 2, ',', '.');
    }

    static function BRL_INPUT($value)
    { // CONVERTE VALOR EM REAIS
        $value = str_replace(".", "", $value);
        $value = str_replace(",", ".", $value);
        return number_format($value, 2, '.', '');
    }

    static function BRL_replace($value)
    { // CONVERTE VALOR EM REAIS
        $value = str_replace(".", "", $value);
        return str_replace(",", ".", $value);
    }

    static function changeArrayPrefix($array_name)
    {
        $array = 'array_' . $array_name;
        $$array  = array();
        if ($_POST[$array_name]) {
            foreach ($_POST[$array_name] as $key => $value) {
                $$array[$array_name . '_' . $key] = $value;
                unset($array[$key]);
            }
            return $$array;
        } else {
            return array();
        }
    }

    static function replaceArrayPrefix($array_name, $campo)
    {
        for ($i = 0; $i < count($array_name); $i++) {
            $array_prefix = $array_name[$i] . '_';
            $campo_novo = explode($array_prefix, $campo);
            if (count($campo_novo) > 1) {
                $campo_novo = $array_name[$i] . '[' . $campo_novo[1] . ']';
                break;
            }
        }
        return $campo_novo;
    }

    static function reindexarArray($array)
    {
        $new_array = array();
        if ($array) {
            # code...
            foreach ($array as $key => $value) {
                $new_array[$value] = $value;
                unset($array[$key]);
            }
        }
        return $new_array;
    }

    static function nome_mes($mes)
    {
        switch ($mes) {
            case '01':
                return 'Janeiro';
            case '02':
                return 'Fevereiro';
            case '03':
                return 'Março';
            case '04':
                return 'Abril';
            case '05':
                return 'Maio';
            case '06':
                return 'Junho';
            case '07':
                return 'Julho';
            case '08':
                return 'Agosto';
            case '09':
                return 'Setembro';
            case '10':
                return 'Outubro';
            case '11':
                return 'Novembro';
            case '12':
                return 'Dezembro';
        }
    }

    static function keyToAlias($valor, $array)
    {

        foreach ($array as $key => $dado) {
            if ($key == $valor) {
                $dado = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $dado);
                return trim($dado);
            }
        }
    }

    static function recursive_unset(&$array, $unwanted_key)
    {
        unset($array[$unwanted_key]);
        foreach ($array as &$value) {
            if (is_array($value)) {
                self::recursive_unset($value, $unwanted_key);
            }
        }
    }

    static function objectToArray($object)
    {
        if (is_object($object)) {
            $object = get_object_vars($object);
        }

        if (is_array($object)) {
            return array_map(__FUNCTION__, $object);
        } else {
            return $object;
        }
    }

    static function arrayToObject($array)
    {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = self::removeIndex($value);
                $value = self::arrayToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    static function removeEspecialChars($string)
    {
        $map = array(
            'º' => ' ',
            'ª' => ' ',
            '*' => ' ',
            '/' => ' ',
            '-' => ' ',
            '_' => ' ',
            '@' => ' ',
            '!' => ' ',
            ',' => ' ',
            '\'' => ' ',
            '"' => ' ',
            '#' => ' ',
            '%' => ' ',
            '¨' => ' ',
            '¨' => ' ',
            'á' => 'a',
            'à' => 'a',
            'ã' => 'a',
            'â' => 'a',
            'é' => 'e',
            'ê' => 'e',
            'í' => 'i',
            'ó' => 'o',
            'ô' => 'o',
            'õ' => 'o',
            'ú' => 'u',
            'ü' => 'u',
            'ç' => 'c',
            'Á' => 'A',
            'À' => 'A',
            'Ã' => 'A',
            'Â' => 'A',
            'É' => 'E',
            'Ê' => 'E',
            'Í' => 'I',
            'Ó' => 'O',
            'Ô' => 'O',
            'Õ' => 'O',
            'Ú' => 'U',
            'Ü' => 'U',
            'Ç' => 'C'
        );
        $string = strtr($string, $map);
        return $string;
    }

    static function validaCPF($cpf)
    {
        $cpf = preg_replace('/[^0-9]/is', '', $cpf);

        if (strlen($cpf) != 11) {
            return false;
        }

        if (preg_match('/(\d)\1{10}/', $cpf)) {
            return false;
        }

        for ($t = 9; $t < 11; $t++) {
            for ($d = 0, $c = 0; $c < $t; $c++) {
                $d += $cpf[$c] * (($t + 1) - $c);
            }
            $d = ((10 * $d) % 11) % 10;
            if ($cpf[$c] != $d) {
                return false;
            }
        }
        return true;
    }

    static function removeValorVazio(&$array)
    {
        foreach ($array as $chave => &$valor) {
            if (is_array($valor)) {
                self::removeValorVazio($valor);
                if (empty($valor)) {
                    unset($array[$chave]);
                }
            } else {
                if ($valor == '') {
                    unset($array[$chave]);
                }
            }
        }
        return $array;
    }

    static function removerChavesVazias(&$dado)
    {
        if (is_array($dado)) {
            foreach ($dado as $chave => &$valor) {
                if (is_array($valor) || is_object($valor)) {
                    self::removerChavesVazias($valor);
                    if (empty($valor)) {
                        unset($dado[$chave]);
                    }
                } else {
                    if (
                        $valor === null || $valor === '' ||
                        $valor == null || $valor == 'null' ||
                        $valor == '' || $valor == '  ' ||
                        $valor === '  '
                    ) {
                        unset($dado[$chave]);
                    }
                }
            }
        }

        if (is_object($dado)) {
            foreach ($dado as $key => &$value) {
                if (is_array($value) || is_object($value)) {
                    self::removerChavesVazias($value);
                    if (empty($value)) {
                        unset($dado->$key);
                    }
                } else {
                    if ($value === null || $value === '' || $value == null || $value == 'null' || $value == '' || $value == '  ') {
                        unset($dado->$key);
                    }
                }
            }
        }

        return $dado;
    }

    static function removeAcentos($string)
    {
        if ($string) {
            return preg_replace(
                array(
                    "/(á|à|ã|â|ä)/", "/(Á|À|Ã|Â|Ä)/", "/(é|è|ê|ë)/", "/(É|È|Ê|Ë)/", "/(í|ì|î|ï)/", "/(Í|Ì|Î|Ï)/", "/(ó|ò|õ|ô|ö)/", "/(Ó|Ò|Õ|Ô|Ö)/", "/(ú|ù|û|ü)/", "/(Ú|Ù|Û|Ü)/", "/(ñ)/", "/(Ñ)/"
                ),
                explode(" ", "a A e E i I o O u U n N"),
                $string
            );
        }
    }

    static function iniciarBuffer()
    {
        if (ob_get_level() == 0) ob_start();
    }

    static function liberarBuffer()
    {
        // echo str_repeat(" ", 4096);
        if (ob_get_level() == 1) ob_flush();
        if (ob_get_level() == 1) flush();
        if (ob_get_level() == 1) ob_end_flush();
        usleep(200000);
    }

    static function testarBuffer()
    {
        set_time_limit(0);
        ob_implicit_flush(true);
        ob_end_flush();
        self::iniciarBuffer();
        for ($counter = 0; $counter < 10; $counter++) {
            sleep(1);
            $processed = ($counter + 1) * 10; //Progress
            $response = array('message' => $processed . '% complete. server time: ' . date("h:i:s", time()), 'progress' => $processed);
            echo json_encode($response);
            self::liberarBuffer();
        }
        self::iniciarBuffer();
        sleep(1);
        $response = array('message' => 'Complete', 'progress' => 100);
        echo json_encode($response);
        self::liberarBuffer();
    }


    static function arrayToDataTables($array, $key)
    {
        foreach ($array as $k => $v) {
            if (str_contains($k, '_data')) {
                $data[$key][$k] = Funcao::ConvertDateFromMysql($v);
            } else if (str_contains($k, '_valor')) {
                $data[$key][$k] = BRL($v);
            } else if (str_contains($k, '_status')) {
                if ($v == "Habilitado" || $v == "Liberado" || $v == "Ativo") {
                    $data[$key][$k] = "<div class='ui header blue'>$v</div>";
                } else {
                    $data[$key][$k] =  "<div class='ui header red'>$v</div>";
                }
            } else if (str_contains($k, '_anexo') || str_contains($k, '_car')) {
                if ($v) {
                    $data[$key][$k] = '<div class="text-center"><a target="_blank" href="' . __URLSITE__ . 'documento.php?id=' . $v . '"><button class="ui teal button"><i class="paperclip icon"></i> Anexo</button></a></div>';
                }
            } else if (str_contains($k, '_senha') || str_contains($k, '_pass')) {
                $data[$key][$k] = str_pad('#', 10, '#');
            } else if (str_contains($k, '_cpf')) {
                if ($v) {
                    $data[$key][$k] = self::mask($v, '###.###.###-##') ?? '';
                } else {
                    $data[$key][$k] = null;
                }
            } else if (str_contains($k, '_cnpj')) {
                if ($v) {
                    $data[$key][$k] = self::mask($v, '##.###.###/####-##');
                } else {
                    $data[$key][$k] = null;
                }
            } else {
                $data[$key][$k] = $v;
            }
        }
        return $data[$key];
    }

    static function isMd5($md5)
    {
        if (preg_match('/^[a-f0-9]{32}$/', $md5)) {
            return $md5;
        }
        return false;
    }
}
