$query = "select a.id_rota, a.tipo_acesso, a.ramal,b.modelo from pbx_rotas_saida_ramais a inner join pbx_rotas_saida_modelos b on a.id_rota = b.id_rota
where ramal = '$ramal'
and '$destino' ~ case when (substring(modelo from '.$') <> '.') then replace('^'||replace(replace(modelo||'$','X','[0-9]'),'Z','[1-9]'),'N','[2-9]')
when (substring(modelo from '.$') = '.') then replace('^'||replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]') end
case when (substring(modelo from '.$') <> '.') then length(replace(replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]'))
when (substring(modelo from '.$') = '.') then length(replace(replace(replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]'),'.',REPEAT('[0-9]', 100))) end as prioridade
from pbx_rotas_saida_ramais a inner join pbx_rotas_saida_modelos b on a.id_rota = b.id_rota
inner join pbx_rotas_saida c on a.id_rota = c.id
where ramal = '$ramal'
and '$destino' ~ case when (substring(modelo from '.$') <> '.') then replace('^'||replace(replace(modelo||'$','X','[0-9]'),'Z','[1-9]'),'N','[2-9]')
when (substring(modelo from '.$') = '.') then replace('^'||replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]') end
and tipo_acesso <> '0'
order by prioridade limit 1";
$result = pg_query($conexao, $query);
$row = pg_fetch_array($result);
$id_rota = $row['id_rota'];
$tipo_acesso = $row['tipo_acesso'];
$ramal = $row['ramal'];
$modelo = $row['modelo'];
$recorte = $row['recorte'];
$acrescenta = $row['acrescenta'];
if (!$tipo_acesso) {
$tipo_acesso = 0;
}
//Libera ligacao caso tenha agente logado no ramal
else if ($tipo_acesso == '3') {
$query = "select count(*) from pbx_supervisor_agentes where ramal = '$ramal'";