<?php

class Cep
{
    const CEP_DB_NAME     = 'cep';
    const CEP_DB_USERNAME = 'cep';
    const CEP_DB_PASSWORD = 'Fut!13@CeP@13Orc';

    public function getCep($cep)
    {
        $address = $this->query('select * from ceps where cep = ' . $cep);
        return $address ? current($address) : false;
    }

    public function getCepEndereco($chave)
    {
        $chaves = explode(",",$chave);
        $inc    = 0;
        $sql    = ' ';
        $filtro = ' Where ';
        foreach ($chaves as $value) {
            $value = '"'.trim($value).'"';
            if ($inc == 0) $sql .= "( (position(concat('|',{$value},'|')  in a.CHAVE_CONSULTA)) +
                      (position(concat({$value},'|')  in a.CHAVE_CONSULTA)) +
                      (position({$value}  in a.CHAVE_CONSULTA))"; else
                $sql .= "+ (position(concat('|',{$value},'|')  in a.CHAVE_CONSULTA)) +
                      (position(concat({$value},'|')   in a.CHAVE_CONSULTA)) +
                      (position({$value} in a.CHAVE_CONSULTA))";

            if ($inc == 0) $filtro .= "( a.CHAVE_CONSULTA  like concat('%', " . $value . ", '%'))";
            else           $filtro .= "and ( a.CHAVE_CONSULTA  like concat('%'," . $value . ", '%'))";

            $inc++;
        }

        if ($inc>0)
            $sql.=") ordenacao,";

        $ceps = $this->query("
            select ".$sql."
                a.uf, a.cidade, a.bairro, a.tipo_logradouro, a.logradouro, a.logradouro_completo, a.cep, a.complemento,
                a.nome, a.chave_consulta, a.codigo_municipio
            from ceps a ".$filtro."
            order by 1, a.logradouro, a.cidade
            limit 100");

        return $ceps ? $ceps : false;
    }

    public function query($sql)
    {
        $result = false;

        $link = mysqli_connect(DB_HOSTNAME, self::CEP_DB_USERNAME, self::CEP_DB_PASSWORD);
        $db_selected = mysqli_select_db($link, self::CEP_DB_NAME);
        if ($db_selected){
            $query = $link->query($sql);
            if ($query){
                $result = $query->fetch_all(MYSQLI_ASSOC);
            }
        }
        $link->close();
        return $result;
    }

}
