<?php
require 'acesso.php';
	$res = array();
	$uf  = $_POST['uf'];
	//$con = new PDO("mysql:dbname=$database; charset=utf8", $usuario , $senha);
	
	$query = "SELECT * FROM cep_brasil ";
	
	if (isset($_POST['contagem'])) {
		if ($uf == "") {
			$ret = $con->prepare("SELECT COUNT(*) AS contagem FROM cep_brasil");
		} else {
			$ret = $con->prepare("SELECT COUNT(*) AS contagem FROM cep_brasil WHERE uf='$uf'");
		}
	} else if (isset($_POST['linha'])) {
		$linha = $_POST['linha'];
		if ($uf == "") {
			$ret = $con->prepare($query . "order by endereco LIMIT $linha, 100");
		} else {
			$ret = $con->prepare($query . "WHERE uf='$uf' order by endereco LIMIT $linha, 100");
		}
	} else if (isset($_POST['pesquisar'])) {
	    $termo = $_POST['termo'];
	    $like_termos = "";
	    $like_array = explode(' ', $termo);
	    foreach($like_array as $palavra) {
	        $like_termos = $like_termos . "endereco LIKE '%$palavra%' AND ";
	    }
	    $like_termos = substr($like_termos, 0, -4);
	    
	    $ret = $con->prepare("SELECT * FROM cep_brasil WHERE cep LIKE '$termo%' or ($like_termos) order by endereco");
	} else {
		if ($uf == "") {
			$ret = $con->prepare($query . "order by endereco");
		} else {
			$ret = $con->prepare($query . "WHERE uf='$uf' order by endereco");
		}
	}
	$ret->execute();
	$mensagem = $ret->errorInfo();
	if ($ret->rowCount() > 0) {
	    $res["enderecos"] = array();
	    while ($row = $ret->fetch(PDO::FETCH_OBJ)) {
	    	array_push($res["enderecos"], $row);
	    }
	    $res["sucesso"] = 1;
		echo json_encode($res);
	} else {
	    $res["sucesso"] = 0;
	    $res["mensagem"] = $mensagem[2];
		echo json_encode($res);
	}
	
	$con = null;
?>

