<?php

namespace Teknisa\Libs\Util\Masks;

class Masks {

    /**
     * Remove mascara de campos de inscricao juridica e fisica.
     * @param $string String mascara.
     * @return string
     */
    public function removeMascaraInscricao($string)
    {
        $patterns[] = "/\//";
        $patterns[] = "/\-/";
        $patterns[] = "/\./";
        $patterns[] = "/\(/";
        $patterns[] = "/\)/";
        $patterns[] = "/\,/";

        return preg_replace($patterns,"","/".$string."/");
    }

    public function replaceCharsForParser($string)
    {
        $from = array(
            "<",
            ">",
            "&",
            "\"",
            "''"
        );

        $to = array(
            "&lt;",
            "&gt;",
            "&amp;",
            "&quot;",
            "&#39;"
        );

        return str_replace($from, $to, $string);
    }

    public function removeAcentos($string)
    {
        /**
         * A função "strtr" substitui os caracteres acentuados pelos não acentuados.
         */
        $acentos = array(
            'À','Á','Ã','Â', 'à','á','ã','â',
            'Ê', 'É',
            'Í', 'í',
            'Ó','Õ','Ô', 'ó', 'õ', 'ô',
            'Ú','Ü',
            'Ç', 'ç',
            'é','ê',
            'ú','ü',
            'Ñ','ñ'
        );
        $remove_acentos = array(
            'A', 'A', 'A', 'A', 'a', 'a', 'a', 'a',
            'E', 'E',
            'I', 'i',
            'O', 'O','O', 'o', 'o','o',
            'U', 'U',
            'C', 'c',
            'e', 'e',
            'u', 'u',
            'N','n'
        );

        return str_replace($acentos, $remove_acentos, $string);
    }

    public static function removeCharsFromString($string)
    {
        return preg_replace('/[^0-9]/', '', $string);
    }

    /**
     * Valida se string é igual a todos caracteres de 0..9 de tamanho = $length.
     * @param $string String a comparar.
     * @param $length Tamanho das strings 0..9.
     * @return boolean
     */
    public function validaInscricaoNumerosIguais($string, $length)
    {
        for($i = 0; $i <= 9; $i++) {
            $fake = str_pad("", $length, $i);
            if($string === $fake)
                return false;
        }

        return true;
    }

    public function picturePessoa($tipoPessoa)
    {
        switch($tipoPessoa) {
            case "F":
                return '###.###.###-##';
            case "J":
                return '##.###.###/####-##';
            case "O":
                return '#####';
            default:
                return '####################';
        }
    }

    /**
     * Valida CGC(CNPJ)
     * @param $cnpj String codigo.
     * @return boolean
     */
    public function validaCNPJ($cnpj)
    {
        $sum = null;
        $multiplier = null;
        $cnpj = trim($this->removeCharsFromString($cnpj));
        if(empty($cnpj) || strlen($cnpj) != 14) {
            return false;
        }else{
            if(!$this->validaInscricaoNumerosIguais($cnpj, 14)){
                return false;
            }else{
                $rev_cnpj = strrev(substr($cnpj, 0, 12));
                for($i = 0; $i <= 11; $i++) {
                    $i == 0 ? $multiplier = 2 : $multiplier;
                    $i == 8 ? $multiplier = 2 : $multiplier;
                    $multiply = ($rev_cnpj[$i] * $multiplier);
                    $sum = $sum + $multiply;
                    $multiplier++;
                }
                $rest = $sum % 11;
                if($rest == 0 || $rest == 1){
                    $dv1 = 0;
                }else{
                    $dv1 = 11 - $rest;
                }

                $sub_cnpj = substr($cnpj, 0, 12);
                $rev_cnpj = strrev($sub_cnpj.$dv1);
                $sum = null;
                for($i = 0; $i <= 12; $i++) {
                    $i == 0 ? $multiplier = 2 : $multiplier;
                    $i == 8 ? $multiplier = 2 : $multiplier;
                    $multiply = ($rev_cnpj[$i] * $multiplier);
                    $sum = $sum + $multiply;
                    $multiplier++;
                }
                $rest = $sum % 11;
                if($rest == 0 || $rest == 1) {
                    $dv2 = 0;
                }else{
                    $dv2 = 11 - $rest;
                }
                if($dv1 == $cnpj[12] && $dv2 == $cnpj[13]){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }

    /**
     * Valida CPF
     * @param $cpf String cpf.
     * @return boolean
     */
    public function validaCPF($cpf){
        $dv = null;
        $cpf = trim($this->removeCharsFromString($cpf));
        if(empty($cpf) || strlen($cpf) != 11) {
            return false;
        }else{
            if(!$this->validaInscricaoNumerosIguais($cpf, 11)) {
                return false;
            }else{
                $sub_cpf = substr($cpf, 0, 9);
                for($i = 0; $i <= 9; $i++) {
                    $dv += (substr($sub_cpf,$i,1) * (10-$i));
                }
                if($dv == 0) {
                    return false;
                }
                $dv = 11 - ($dv % 11);
                if($dv > 9){
                    $dv = 0;
                }
//                if($cpf[9] != $dv) {
//                    return false;
//                }
                if(substr($cpf,9,1) != $dv) {
                    return false;
                }
                $dv *= 2;
                for($i = 0; $i <= 9; $i++) {
                    $dv += (substr($sub_cpf,$i,1) * (11-$i));
                }
                $dv = 11 - ($dv % 11);
                if($dv > 9) {
                    $dv = 0;
                }
                if(substr($cpf,10,1) != $dv) {
                    return false;
                }
                return true;
            }
        }
    }

    /**
     * Remove a mascara de acordo com o @param $regex
     *
     * @param string $masked_value Valor com mascara.
     * @param string $regex        Expressão regular.
     *
     * @return mixed|NULL
     */
    public function removeMask($masked_value, $regex){
        $mask = $masked_value;
        if (isset($mask) === true) {
            $value = preg_replace($regex, '', $mask);
            return $value;
        } else {
            return null;
        }
    }

    /**
     * @param $val  mixed     - Valor a mascarar
     * @param $mask string    - Mascara
     *          # <Caractere a substituir>
     *          qualquer outro caractere diferente de # nas mascara sera tratado como tal.
     * @param $strict boolean - Se parametro for passado, entao tamanho da string devera condizer com o tamanho de # da mascara;
     * @return bool|string
     */
    public function mask($val, $mask, $strict = null)
    {
        if($strict && strlen($val) !== strlen(preg_replace("/[^\#]/","",$mask)))
            return false;
        $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;
    }
}