<?php 
//------------------------------------------
//escrito por Luis Henrique Weirich de Matos
//------------------------------------------

include_once (dirname(__FILE__)."/../../classesphp/sani_request.php");
$_GET = array_merge($_GET,$_POST);
//$mapexten = $_GET["mapexten"];
error_reporting(0);
session_name("i3GeoPHP");
if (isset($_GET["g_sid"]))
{session_id($_GET["g_sid"]);}
session_start();


//obtención de variables enviados por URL
$map_file 	= $_GET["mapfile"];
/*$objectid 	= $_GET["objectid"];
$gid        = $_GET["objectid"];
$dpto 		= $_GET["dpto"];
$distrito 	= $_GET["distrito"];
$colonia 	= $_GET["colonia"];
$mz_agr 	= $_GET["mz_agr"];
$lote_agr 	= $_GET["lote_agr"];
$id_usuario	= $_GET["usr"];
$hoja	    = $_GET["hoja"];
$par_escala = $_GET["par_escala"];
$genera_per = $_GET["genera_per"];
*/


$id_proyecto 	      = $_GET["id_proyecto"];          //Nuevo
$id_tramo 	          = $_GET["id_tramo"];             //Nuevo
$id_subtramo 	      = $_GET["id_subtramo"];          //Nuevo
$id_tipo_afectacion   = $_GET["id_tipo_afectacion"];   //Nuevo
$id_condicion_dominio = $_GET["id_condicion_dominio"]; //Nuevo
$franja_dominio       = $_GET["franja_dominio"];       //Nuevo
$id_departamento      = $_GET["id_departamento"];      //Nuevo
$id_distrito 	      = $_GET["id_distrito"];          //Nuevo
$desafectado 	      = $_GET["desafectado"];          //Nuevo
$entrada_maquina 	  = $_GET["entrada_maquina"];      //Nuevo
$progresiva_inicial   = $_GET["progresiva_inicial"];   //Nuevo
$progresiva_final 	  = $_GET["progresiva_final"];     //Nuevo
$urgente 	 		  = $_GET["urgente"];              //Nuevo
$usr 	              = $_GET["usr"];                     






$w=0;
$sq = "select * from ide.v_expedientes_listado_g ";


if (isset($id_proyecto) and ($id_proyecto > 0))	{	   
	if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;
	$sq = $sq." id_proyecto=".$id_proyecto;
}
if (isset($id_tramo) and ($id_tramo > 0))	{
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	   
	$sq = $sq." id_tramo=".$id_tramo;
}
if (isset($id_subtramo) and ($id_subtramo > 0)) { 
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;   
	$sq = $sq." id_subtramo=".$id_subtramo;
}
if (isset($id_tipo_afectacion) and ($id_tipo_afectacion > 0))	{	
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;     
	$sq = $sq." id_tipo_afectacion=".$id_tipo_afectacion;
}
if (isset($id_condicion_dominio) and ($id_condicion_dominio > 0)) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." id_condicion_dominio=".$id_condicion_dominio;
}

if (isset($franja_dominio) AND ($franja_dominio <> 'FT')) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." franja_dominio='".$franja_dominio."'";
}
if (isset($id_departamento) and !empty($id_departamento)) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." id_departamento='".$id_departamento."'";
}
if (isset($id_distrito)  and ! empty($id_departamento)) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." id_distrito='".$id_distrito."'";
}
if (isset($desafectado) AND ($desafectado <> 'TO')) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." desafectado='".$desafectado."'";
}
if (isset($entrada_maquina) AND ($entrada_maquina <> 'TO')) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." entrada_maquina='".$entrada_maquina."'";
}

$sq = $sq." order by clasificacion, codigo ";

if (isset($urgente) AND ($urgente <> 'TO')) {	   
    if ($w==0) {	
		$sq = $sq." WHERE ";     
	} else {
		$sq = $sq." AND ";    
	}
	$w=1;	
	$sq = $sq." urgente='".$urgente."'";
}



$hoja_plano = $hoja - 1;



$postgis_mapa = $_SESSION["postgis_mapa"];
require_once (dirname(__FILE__)."/../../ms_configura.php");
//
//se as extens&otilde;es j&aacute; estiverem carregadas no PHP, vc pode comentar essa linha para que o processamento fique mais r&aacute;pido
//


include_once (dirname(__FILE__)."/../../classesphp/carrega_ext.php");
//
//carrega o phpmapscript
//
$exts = get_loaded_extensions();
//$exts = $_GET["mapexten"];

if (array_search( "MapScript", $exts) != TRUE)	
{
	if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
	{
		if(!@dl('php_mapscript_48.dll'))
		dl('php_mapscript.dll');
	}
	else
	{dl('php_mapscript.so');}
}


require(dirname(__FILE__)."/../../classesphp/funcoes_gerais.php");
$nomes = nomeRandomico();
//
//substitui a string de conex&atilde;o com o banco em cada layer se for necess&aacute;rio
//
// carga map file 
$map = ms_newMapObj($map_file);
$temp = str_replace(".map","xxx.map",$map_file);
$map->save($temp);
$map = ms_newMapObj($temp);
restauraCon($temp,$postgis_mapa);

$w = $map->width;
$h = $map->height;




$link_bd=pg_connect("host=45.10.163.71 port=5432 dbname=expropiacion user=sge password=2l2f1nt22022i connect_timeout=5 options='--client_encoding=utf8'");

$formato_lado = 'N';
$colonia_titulada = ' ';
$formato_hrumbo	= ' ';
$dpto_cod = ' ';
$dpto_desc = ' ';
$dist_cod =' ';
$dist_desc =' ';
$col_cod = 0 ;
$col_desc = ' ';
$dpdsc = ' ';
$dtodsc = ' ';
$coldsc = ' ';




if (isset($id_subtramo) and ($id_subtramo > 0)) { 
	$objectid = $id_subtramo;
} else {
	if (isset($id_tramo) and ($id_tramo > 0)) {
		$objectid = $id_tramo;
	}
}




//echo $sq;
$sq='select t.nombre nombre_tramo, t.pro_inicio pro_inicio, t.pro_fin, pro_fin, d.* 
from ide.tramos t,
ide.distritos d  
where (t.id_tramo=' .$objectid.  
' or t.id_tramo in  
(select i.id_tramo from public.tramos i where i.tramo_padre='.$objectid.' )) 
and st_intersects(t.geom,d.geom)';

//echo $sq;

$result = pg_query ($link_bd,$sq);

//echo $result;

while ($datos = pg_fetch_array($result)) {		
	$dpto_cod = $datos[dpto];
    $dpto_desc = $datos[dpto_desc];
    $dist_cod = $datos[distrito];
	$dist_desc = $datos[dist_desc];
	$nombre_tramo=$datos[nombre_tramo];
	$pro_inicio=$datos[pro_inicio];
	$pro_fin=$datos[pro_fin];
}
pg_free_result ($result);
pg_close ();





//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//---- INICIO DE LA CONFIGURACION DE LA IMAGEN PRINCIPAL DEL PLANO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------


$capas = $map->getalllayernames();
foreach ($capas as $capa)
{
	$layer = $map->getlayerbyname($capa);
	if (($layer->data != "") && (strtolower($layer->getmetadata("escondido")) != "sim") && (strtolower($layer->getmetadata("tema")) != "nao"))
	{
		//echo $layer->getmetadata("tema");
		$existedato = "NO";
		if (($layer->getmetadata("tema")=="tramos_plano"))
		{
			////echo "<p> " . 'antes de select' . ":</p>";
			/*
			$sq ="select st_setsrid(the_geom,4326) as the_geom,id_proyec,nombre,codigo,id_tramo,tipo,pro_inicio,pro_fin,gid from i3geo.tramos where id_tramo = ".$objectid;
			*/

$sq='select st_setsrid(the_geom,4326) as the_geom,id_proyec,nombre,codigo,id_tramo,tipo,pro_inicio,pro_fin,gid  
from i3geo.tramos t
where (t.id_tramo=' .$objectid.  
' or t.id_tramo in  
(select i.id_tramo from public.tramos i where i.tramo_padre='.$objectid.' ))';

			//echo "<p> " . $sq . "</p>";
	
			$result = pg_query ($link_bd,$sq);

			while ($r_fila = pg_fetch_array($result))
			{
				//echo "<p> " . 'Ingreso SI' . ":</p>";		
				$existedato = "SI";				
			}
			pg_free_result ($result);
			pg_close ();
			if ($existedato  == "NO")
			{
				////echo "<p> " . 'Existe NO' . ":</p>";		
				$layer->set('opacity', 20); 				
			}	
			else
			{
	            $data="the_geom from (".$sq." /*FW*//*FW*/) as foo using unique gid using srid=4326";
				$layer->set("data",$data);            
				//$layer->set('opacity', 100); 	
				$layer->set('opacity', 50); 		
			}	
		}


		
		if ($layer->numclasses > 0)
		{
			$classe = $layer->getclass(0);
			if (($classe->name == "") || ($classe->name == " "))
			{$classe->set("name",$layer->getmetadata("tema"));}		    
		}	
			

	}
	if ($layer->getmetadata("classe") == "NAO")
	{
		$nclasses = $layer->numclasses;
		if ($nclasses > 0)
		{
			for($i=0;$i<$nclasses;$i++)
			{
				$classe = $layer->getclass($i);
				$classe->set("name","classeNula");
			}
		}
	}
}

$map->save($temp);
removeLinha("classeNula",$temp);
$map = ms_newMapObj($temp);
$layer = $map->getlayerbyname("tramos");
$layer->querybyattributes("tramos","id_tramo"."=".$objectid,1);
$layer->set('status', MS_ON);
$numresults = $layer->getNumResults();

if ($numresults < 1) {
  $error = true;
} else {
  ////echo "<p> " . 'mayor igual a 1' . ":</p>";
  $result = $layer->getResult(0);
  $shapeObj = $layer->getShape($result);

  $minx = $shapeObj->bounds->minx;
  $miny = $shapeObj->bounds->miny;
  $maxx = $shapeObj->bounds->maxx;
  $maxy = $shapeObj->bounds->maxy;
}

substituiCon($temp,$postgis_mapa);
$o = $map->outputformat;

if ($par_escala <= 0)
{
	$par_escala=1;
}

if ($par_escala > 9)
{
	$par_escala=9;
}

$sq = "select ";
$sq = $sq."cast(round(cast((x.campo1-(x.campo3-x.campo1)/10) as decimal),13) as text) as ext1, ";
$sq = $sq."cast(round(cast((x.campo2-(x.campo4-x.campo2)/10) as decimal),13) as text) as ext2, ";
$sq = $sq."cast(round(cast((x.campo3+(x.campo3-x.campo1)/10) as decimal),13) as text) as ext3, ";
$sq = $sq."cast(round(cast((x.campo4+(x.campo4-x.campo2)/10) as decimal),13) as text) as ext4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."cast((regexp_split_to_array(bb, E','))[1] as decimal) as campo1, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[2] as decimal) as campo2, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[3] as decimal) as campo3, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[4] as decimal) as campo4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."replace(replace(substr(cast(a.bb as varchar),5),' ',',') ,')','') as bb  ";
$sq = $sq."from ";
$sq = $sq."(select ST_Extent(the_geom) bb from ";
$sq = $sq."(select 1 objectid, st_union(st_snaptogrid(the_geom,0.00000000000001)) the_geom ";
$sq = $sq." from i3geo.tramos t ";
$sq = $sq." where (t.id_tramo =".$objectid;

$sq = $sq." or t.id_tramo in ";
$sq = $sq." (select i.id_tramo from public.tramos i where i.tramo_padre=".$objectid." ))";

$sq = $sq.") e ";
$sq = $sq.") as a) as t1) as x;";


//echo $sq;

$ext1='                                          ';
$ext2='                                          ';
$ext3='                                          ';
$ext4='                                          ';



$result = pg_query ($link_bd,$sq);
if ($r_parcela = pg_fetch_array($result))
{

	$ext1=$r_parcela["ext1"];
	$ext2=$r_parcela["ext2"];
	$ext3=$r_parcela["ext3"];
	$ext4=$r_parcela["ext4"];
	
		//echo $ext1;
		//echo $ext2;
		//echo $ext3;
		//echo $ext4;
	
}
pg_free_result ($result);
pg_close ();

$escala=0;

$result_escala = pg_query ($link_bd,"select ide.calcular_escala_real(".$ext1.",".$ext4.",".$ext3.",".$ext4.",19) as escala;");
if ($r_escala = pg_fetch_array($result_escala))
{

	$escala=$r_escala["escala"];
	//echo "<p> " . '$escala:'.$escala. " </p>";
}
//echo "<p> " . '$ext1:'.$escala. " </p>";
pg_free_result ($result_escala);
pg_close ();



$extatual = $map->extent;
$extatual->setExtent( $ext1, $ext2, $ext3, $ext4 );

//echo $dpto.'  '.$distrito;

$map->setExtent( $ext1, $ext2, $ext3, $ext4 );


$o->set("imagemode",MS_IMAGEMODE_RGB);
$o->set("transparent","false");


$imgo = $map->draw();
if($imgo->imagepath == "")
{echo "Erro IMAGEPATH vazio";exit;}
$nomer = ($imgo->imagepath)."mapa".$nomes.".png";

$imgo->saveImage($nomer);


$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
$pathMapa = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomer);

//CONFIGURACION DE LA LEYENDA

$imgo = $map->drawlegend();
$nomer = ($imgo->imagepath)."leg".$nomes.".PNG";
$imgo->saveImage($nomer);
$pathlegenda = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomer);

//substituiCon($map_file,$postgis_mapa);

//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------- FINAL DE LA CONFIGURACION DE LA IMAGEN PRINCIPAL DEL PLANO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------

//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//---- INICIO DE LA CONFIGURACION DE LA IMAGEN DE REFERENCIA DEL DEPARTAMENTO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------

$ref_map_file = "C:/ms4w/Apache/htdocs/i3geo/aplicmap/mopc_gl_a3_tramo_afectacion_dpto.map";
$ref_map = ms_newMapObj($ref_map_file);
$ref_temp = str_replace(".map","xxx_ref.map",$ref_map_file);

//echo "<p> " . 'Ingreso ref'. ":</p>";
//substitui a string de conex&atilde;o com o banco em cada layer se for necess&aacute;rio
$ref_map->save($ref_temp);
$ref_map = ms_newMapObj($ref_temp);

$capas = $ref_map->getalllayernames();
foreach ($capas as $capa)
{
	$layer = $ref_map->getlayerbyname($capa);
	if (($layer->data != "") && (strtolower($layer->getmetadata("escondido")) != "sim") && (strtolower($layer->getmetadata("tema")) != "nao"))
	{
		
		$existedato = "NO";

		if (($layer->getmetadata("tema")=="dpto_plano"))
		{
			////echo "<p> " . 'antes de select' . ":</p>";
			$sq = "select st_setsrid(the_geom,4326) as the_geom,dpto,dpto_desc,gid,objectid ";
			$sq = $sq."from i3geo.dpto ";
			$sq = $sq."where dpto = '".$dpto_cod."'" ;
	
			$result = pg_query ($link_bd,$sq);

			while ($r_fila = pg_fetch_array($result))
			{
				//echo "<p> " . 'Ingreso SI' . ":</p>";		
				$existedato = "SI";				
			}
			pg_free_result ($result);
			pg_close ();
			if ($existedato  == "NO")
			{
				////echo "<p> " . 'Existe NO' . ":</p>";		
				$layer->set('opacity', 20); 				
			}	
			else
			{
	            //echo "<p> " . $sq . "</p>";	
	            $data="the_geom from (".$sq." /*FW*//*FW*/) as foo using unique gid using srid=4326";
				$layer->set("data",$data);            
 	
				$layer->set('opacity', 100); 		
			}	
		}
		if ($layer->numclasses > 0)
		{
			$classe = $layer->getclass(0);
			if (($classe->name == "") || ($classe->name == " "))
			{$classe->set("name",$layer->getmetadata("tema"));}		    
		}	
	}
	if ($layer->getmetadata("classe") == "NAO")
	{
		$nclasses = $layer->numclasses;
		if ($nclasses > 0)
		{
			for($i=0;$i<$nclasses;$i++)
			{
				$classe = $layer->getclass($i);
				$classe->set("name","classeNula");
			}
		}
	}
}

$ref_map->save($ref_temp);
removeLinha("classeNula",$ref_temp);
$ref_map = ms_newMapObj($ref_temp);
$layer = $ref_map->getlayerbyname("dpto");
$layer->querybyattributes("dpto","dpto"."=".$dpto_cod,1);
$layer->set('status', MS_ON);
$numresults = $layer->getNumResults();

if ($numresults < 1) {
  $error = true;
} else {
  ////echo "<p> " . 'mayor igual a 1' . ":</p>";
  $result = $layer->getResult(0);
  $shapeObj = $layer->getShape($result);

  $minx = $shapeObj->bounds->minx;
  $miny = $shapeObj->bounds->miny;
  $maxx = $shapeObj->bounds->maxx;
  $maxy = $shapeObj->bounds->maxy;
}

substituiCon($ref_temp,$postgis_mapa);
$o = $ref_map->outputformat;

if ($par_escala <= 0)
{
	$par_escala=1;
}

if ($par_escala > 9)
{
	$par_escala=9;
}

$sq = "select ";
$sq = $sq."cast(round(cast((x.campo1+x.campo1*(0.0000".$par_escala.")) as decimal),13) as text) as ext1, ";
$sq = $sq."cast(round(cast((x.campo2+x.campo2*(0.0000".$par_escala.")) as decimal),13) as text) as ext2, ";
$sq = $sq."cast(round(cast((x.campo3-x.campo3*(0.0000".$par_escala.")) as decimal),13) as text) as ext3, ";
$sq = $sq."cast(round(cast((x.campo4-x.campo4*(0.0000".$par_escala.")) as decimal),13) as text) as ext4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."cast((regexp_split_to_array(bb, E','))[1] as decimal) as campo1, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[2] as decimal) as campo2, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[3] as decimal) as campo3, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[4] as decimal) as campo4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."replace(replace(substr(cast(a.bb as varchar),5),' ',',') ,')','') as bb  ";
$sq = $sq."from ";
$sq = $sq."(select ST_Extent(the_geom) bb from ";
$sq = $sq."(select 1 objectid, st_union(st_snaptogrid(the_geom,0.00000000000001)) the_geom ";
$sq = $sq."from i3geo.dpto t ";
$sq = $sq."where t.dpto='".$dpto_cod."' ) e ";
$sq = $sq.") as a) as t1) as x;  ";

$ext1='                                          ';
$ext2='                                          ';
$ext3='                                          ';
$ext4='                                          ';

$result = pg_query ($link_bd,$sq);
if ($r_parcela = pg_fetch_array($result))
{

	$ext1='-63';
	$ext2='-27';
	$ext3='-54';
	$ext4='-20';
	/*
		echo $ext1;
		echo $ext2;
		echo $ext3;
		echo $ext4;
	*/
}
	$ext1='-63';
	$ext2='-27';
	$ext3='-54';
	$ext4='-20';

$result = pg_query ($link_bd,"select indert.calcular_escala(".$ext1.",".$ext4.",".$ext3.",".$ext4.",19) as escala;");
if ($r_parcela = pg_fetch_array($result))
{

	$escala=$r_parcela["escala"];
}

//echo "<p> " . '$ext1:'.$ext1. " </p>";

pg_free_result ($reqcat);
pg_close ();

$extatual = $ref_map->extent;
$extatual->setExtent( $ext1, $ext2, $ext3, $ext4 );

$ref_map->setExtent( $ext1, $ext2, $ext3, $ext4 );

$o->set("imagemode",MS_IMAGEMODE_RGB);
$o->set("transparent","false");

$imgo = $ref_map->draw();
if($imgo->imagepath == "")
{echo "Erro IMAGEPATH vazio1";exit;}
$nomer_ref = ($imgo->imagepath)."mapa".$nomes."_ref.png";  //CORREGIR JAIME

$imgo->saveImage($nomer_ref);
 
$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
$pathMapa_ref = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomer_ref);
$nomeImagem = nomeRandomico();
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------- FINAL DE LA CONFIGURACION DE LA IMAGEN DE REFERENCIA POR DEPARTAMENTO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------




//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//---- INICIO DE LA CONFIGURACION DE LA IMAGEN DE REFERENCIA DEL DISTRITO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------

$ref_map_file = "C:/ms4w/Apache/htdocs/i3geo/aplicmap/mopc_gl_a3_tramo_afectacion_distrito.map";
$ref_map = ms_newMapObj($ref_map_file);
$ref_temp = str_replace(".map","xxx_ref.map",$ref_map_file);

//echo "<p> " . 'Ingreso ref'. ":</p>";
//substitui a string de conex&atilde;o com o banco em cada layer se for necess&aacute;rio
$ref_map->save($ref_temp);
$ref_map = ms_newMapObj($ref_temp);

$capas = $ref_map->getalllayernames();
foreach ($capas as $capa)
{
	$layer = $ref_map->getlayerbyname($capa);
	if (($layer->data != "") && (strtolower($layer->getmetadata("escondido")) != "sim") && (strtolower($layer->getmetadata("tema")) != "nao"))
	{
		
		$existedato = "NO";
		

		if (($layer->getmetadata("tema")=="distritos_plano"))
		{
			////echo "<p> " . 'antes de select' . ":</p>";
			$sq = "select st_setsrid(the_geom,4326) as the_geom,dpto,distrito,cod,dpto_desc,dist_desc,gid ";
			$sq = $sq."from i3geo.distritos ";
			$sq = $sq."where dpto = '".$dpto_cod."'" ;
			$sq = $sq." and distrito = '".$dist_cod."'" ;
	

			$result = pg_query ($link_bd,$sq);

			while ($r_fila = pg_fetch_array($result))
			{
				//echo "<p> " . 'Ingreso SI' . ":</p>";		

				$existedato = "SI";				
			}
			pg_free_result ($result);
			pg_close ();
			if ($existedato  == "NO")
			{
				////echo "<p> " . 'Existe NO' . ":</p>";		
				$layer->set('opacity', 20); 				
			}	
			else
			{
	            //echo "<p> " . $sq . "</p>";	
	            //echo "<p> " . $sq . ":</p>";
	            $data="the_geom from (".$sq." /*FW*//*FW*/) as foo using unique gid using srid=4326";
				$layer->set("data",$data);            
 	
				$layer->set('opacity', 100); 		
			}	
		}
		$existedato = "NO";
		
			
		if ($layer->numclasses > 0)
		{
			$classe = $layer->getclass(0);
			if (($classe->name == "") || ($classe->name == " "))
			{$classe->set("name",$layer->getmetadata("tema"));}		    
		}
	}
	if ($layer->getmetadata("classe") == "NAO")
	{
		$nclasses = $layer->numclasses;
		if ($nclasses > 0)
		{
			for($i=0;$i<$nclasses;$i++)
			{
				$classe = $layer->getclass($i);
				$classe->set("name","classeNula");
			}
		}
	}
}

$ref_map->save($ref_temp);
removeLinha("classeNula",$ref_temp);
$ref_map = ms_newMapObj($ref_temp);
$layer = $ref_map->getlayerbyname("distritos");
$layer->querybyattributes("distritos","distrito"."=".$dist_cod,1);
$layer->set('status', MS_ON);
$numresults = $layer->getNumResults();

if ($numresults < 1) {
  $error = true;
} else {
  ////echo "<p> " . 'mayor igual a 1' . ":</p>";
  $result = $layer->getResult(0);
  $shapeObj = $layer->getShape($result);

  $minx = $shapeObj->bounds->minx;
  $miny = $shapeObj->bounds->miny;
  $maxx = $shapeObj->bounds->maxx;
  $maxy = $shapeObj->bounds->maxy;
}

substituiCon($ref_temp,$postgis_mapa);
$o = $ref_map->outputformat;

if ($par_escala <= 0)
{
	$par_escala=1;
}

if ($par_escala > 9)
{
	$par_escala=9;
}


$par_escala=1;
$sq = "select ";
$sq = $sq."cast(round(cast((x.campo1+x.campo1*(0.00".$par_escala.")) as decimal),13) as text) as ext1, ";
$sq = $sq."cast(round(cast((x.campo2+x.campo2*(0.00".$par_escala.")) as decimal),13) as text) as ext2, ";
$sq = $sq."cast(round(cast((x.campo3-x.campo3*(0.00".$par_escala.")) as decimal),13) as text) as ext3, ";
$sq = $sq."cast(round(cast((x.campo4-x.campo4*(0.00".$par_escala.")) as decimal),13) as text) as ext4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."cast((regexp_split_to_array(bb, E','))[1] as decimal) as campo1, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[2] as decimal) as campo2, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[3] as decimal) as campo3, ";
$sq = $sq."cast((regexp_split_to_array(bb, E','))[4] as decimal) as campo4 ";
$sq = $sq."from ";
$sq = $sq."(select "; 
$sq = $sq."replace(replace(substr(cast(a.bb as varchar),5),' ',',') ,')','') as bb  ";
$sq = $sq."from ";
$sq = $sq."(select ST_Extent(the_geom) bb from ";
$sq = $sq."(select 1 objectid, st_union(st_snaptogrid(the_geom,0.00000000000001)) the_geom ";
$sq = $sq."from i3geo.distritos t ";
$sq = $sq."where t.dpto='".$dpto_cod."' and t.distrito='".$dist_cod."') e ";
$sq = $sq.") as a) as t1) as x;  ";

$ext1='                                          ';
$ext2='                                          ';
$ext3='                                          ';
$ext4='                                          ';

$result = pg_query ($link_bd,$sq);
if ($r_parcela = pg_fetch_array($result))
{

	$ext1=$r_parcela["ext1"];
	$ext2=$r_parcela["ext2"];
	$ext3=$r_parcela["ext3"];
	$ext4=$r_parcela["ext4"];
	/*
		echo $ext1;
		echo $ext2;
		echo $ext3;
		echo $ext4;
	*/
}

$result = pg_query ($link_bd,"select indert.calcular_escala(".$ext1.",".$ext4.",".$ext3.",".$ext4.",19) as escala;");
if ($r_parcela = pg_fetch_array($result))
{

	$escala=$r_parcela["escala"];
}

//echo "<p> " . '$ext1:'.$ext1. " </p>";

pg_free_result ($reqcat);
pg_close ();

$extatual = $ref_map->extent;
$extatual->setExtent( $ext1, $ext2, $ext3, $ext4 );

$ref_map->setExtent( $ext1, $ext2, $ext3, $ext4 );

$o->set("imagemode",MS_IMAGEMODE_RGB);
$o->set("transparent","false");

$imgo = $ref_map->draw();
if($imgo->imagepath == "")
{echo "Erro IMAGEPATH vazio1";exit;}
$nomer_ref2 = ($imgo->imagepath)."mapa".$nomes."_ref2.png";  //CORREGIR JAIME

$imgo->saveImage($nomer_ref2);
 
$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
$pathMapa_ref2 = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomer_ref2);
$nomeImagem = nomeRandomico();
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------- FINAL DE LA CONFIGURACION DE LA IMAGEN DE REFERENCIA POR DISTRITO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------




//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------- INICIO DE LA CONFIGURACION, INSERCION DE RECUADROS, LINEAS, IMAGENES
//------- Y TEXTOS EN EL ARCHIVO PDF DEL PLANO
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//-----------CONFIGURACION Y CREACION DEL ARCHIVO PDF
//----------------------------------------------------------------------------------
require(dirname(__FILE__).'/../../pacotes/fpdf/fpdf.php');
#$pdf = new FPDF("L","mm",array(297,420));
$pdf = new FPDF("L","mm","A3");
//$pdf = new FPDF("P","mm","A4");
$pdf->SetAutoPageBreak(false);
//$pdf->SetDisplayMode( 70 , "single");
$pdf->SetDisplayMode( 70 , "single");
$pdf->SetMargins(0, 0, 0);
$pdf->AddPage("L");
$pdf->SetLineWidth(0.1);
//$wMapaMax = 222;
//$hMapaMax = 171;

//$hMapaMax = 230;
//$wMapaMax = 190;
//----------------------------------------------------------------------------------------------
//--------------------INSERCION O IMPRESION DE RECUADROS LINEAS E IMAGENES DEL PLANO
//----------------------------------------------------------------------------------------------
//--------------------INSERCION DE LA IMAGEN PRINCIPAL DEL PLANO
//--------------------INSERCION DE LAS IMAGENES DE REFERENCIA DEL PLANO DEPARTAMENTAL Y DISTRITAL
//--------------------INSERCION DE LA IMAGEN DE LEYENDA Y ESCALA SI EXISTIESE
$mapasize = getimagesize($pathMapa);
$wMapa = $mapasize[0];
$hMapa = $mapasize[1];

$nW  = $wMapa/10;
$nH  = $hMapa/10;

//Ancho y alto para el recuadro del mapa
$anchomap = 420;
$altomap  = 297;
//echo "ancho: ". $nW. " 	alto: " . $nH;
//$pdf->Rect(10, 10, $anchomap-20, $altomap-20, 'D');//Mapa CONTORNO DE LA HOJA
//$pdf->Rect(10, 10, $nW+893, $nH+831, 'D');//Mapa
//Ancho y alto para el recuadro de los datos
$xdatos  = 10; //valor para x del recuadro de datos
$ydatos  = $altomap;  
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
//----------INSERCION 0 IMPRESION DE IMAGENES Y RECUADROS----------------------------
//$pdf->Image($pathMapa, 10, 10, $nW, $nH);//imagen principal del mapa
$pdf->Image($pathMapa, 10, 10, 300, 267);//imagen principal del mapa
$pdf->Rect(10, 10, $anchomap-20, $altomap-20, 'D');//Mapa CONTORNO DE LA HOJA

//$pdf->Rect(310, 10, 100, 277, 'D');//recuadro de dato alfanumerico 
//$pdf->Rect(10, 10, $nW, $nH, 'D');// recuadro del contorno de la imagen
$pdf->Rect(10, 10, 300, 267, 'D');// recuadro del contorno de la imagen


$pdf->SetFont('Arial','',9);


//$pdf->Rect(37-6, 26-6, 212+10, 172+8, 'D');//recuadro superior de la imagen

//$pdf->Image($pathMapa, 37, 26, $nW, $nH); //CORREGIDO POR JAIME
$pdf->Image($pathMapa_ref, 312, 180, 48, 48);//IMAGEN DEL MAPA DEPARTAMENTAL
$pdf->Image($pathMapa_ref2, 360, 180, 48, 48);//IMAGEN DEL MAPA DISTRITAL
$pdf->Image($pathlegenda, 312, 240 , 35);

$pdf->Rect(312, 180, 48, 48, 'D');// recuadro del contorno de la imagen del mapa dep
$pdf->Rect(360, 180, 48, 48, 'D');// recuadro del contorno de la imagen del mapa dist
$pdf->Rect(312, 238, 48, 48, 'D');// recuadro del contorno de la imagen de la leyenda

$pdf->SetFont('Arial','',9);

//************************************
//************************************
//************************************

$nWG = $nW;
$nHG = $nH;

$linea = 30; //Linea inicial
$separador = 15;
$ancho = 350;

//-------------------------------------------------------------------------------
//IMPRESION DE IMAGENES DE LOGOS 
//-------------------------------------------------------------------------------
//


//$pdf->Image("../../imagens/norte.jpg", 11, 9, 12,13);
//$pdf->Image("../../imagens/pie_pagina.jpg" , 375,247,25,15.907,'','',1);
/*
*/
//$pdf->Image("../../imagens/puntos-cardinales.jpg", 11, 11, 16,17);
$pdf->Image("../../imagens/Norte.jpg", 11, 11, 14,18);
$pdf->Image("../../imagens/mopc.jpg" , $xtabla+311,$ydatos1+11, 34,13,'','',1);
$pdf->Image("../../imagens/paraguay-de-la-gente.jpg" , $xtabla+380,$ydatos1+11, 25,12,'','',1);
//                                               HORIZONRAL      VERTICAL       ANCHO  ALTO    
//                                            IZQUIERDA-DERECHA  ARRIBA-ABAJO 
//                                                    X             Y
 //$xMsg = $anchomap/2 - $pdf->GetStringWidth($textMsg)/2; 


//-------------------------------------------------------------------------------
//OBTENCION DE DATOS A TRAVEZ DE SQL O CONSULTAS A LA BASE DE DATOS
//-------------------------------------------------------------------------------
// Consulta en postgres

	$resolucion_hab = ' ';
	$fecha_hab 		= ' ';
	$fecha_deslinde	= ' ';
	$dist_matriz	= 0;


$nro_titulo = ' ';
$expediente = ' ';



$hora = pg_query($link_bd, "SELECT to_char(now(), 'HH24:mi') hora");
while ($dato = pg_fetch_array($hora)) {
	$hora = $dato[hora];
}
$fecha = pg_query($link_bd, "SELECT to_char(now(), 'DD/MM/YYYY') fecha");
while ($dato = pg_fetch_array($fecha)) {
	$fecha = $dato[fecha];
}
$sq="SELECT first_name, last_name from users where id = " . $id_usuario;
//echo $sq;
$usuario = pg_query($link_bd, $sq);
while ($usr = pg_fetch_array($usuario)) {
	$nombreapellidousr = $usr[first_name] . " " . $usr[last_name];
}
$tramo= pg_query($link_bd, "select t.nombre nombre from ide.tramos t where t.id_tramo=".$objectid);
while ($dato = pg_fetch_array($tramo)) {
	$tramo_text = $dato[nombre];
}


	
//--------------------------------------------------------------------------------------------
//------ INSERCION O IMPRESION DE TITULOS Y DATOS ALFANUMERICOS  OBTENIDOS DE LAS CONSULTAS SQL
//--------------------------------------------------------------------------------------------

$anchotitulo=78;
$separador = 4;

$pdf->SetFillColor(251,187,0);

$pdf->Rect(312, 23, 96, 26, 'F');


$pdf->SetFont('Arial','B',12);


$ancho = 96;


$textMsg = utf8_decode("REPÚBLICA DEL PARAGUAY");
$x_centreado = $ancho/2 - $pdf->GetStringWidth($textMsg)/2;//EJEMPLO CENTREADO

$pdf->Text(312+$x_centreado,27,$textMsg);

$pdf->SetFont('Arial','B',10);

$textMsg = utf8_decode("MINISTERIO DE OBRAS PÚBLICAS Y COMUNICACIONES");
$x_centreado = $ancho/2 - $pdf->GetStringWidth($textMsg)/2;//EJEMPLO CENTREADO
$pdf->Text(312+$x_centreado,32,$textMsg);

$pdf->SetFont('Arial','B',9);

$textMsg = utf8_decode("VICEMINISTERIO DE OBRAS PUBLICAS Y COMUNICACIONES");
$x_centreado = $ancho/2 - $pdf->GetStringWidth($textMsg)/2;//EJEMPLO CENTREADO
$pdf->Text(312+$x_centreado,37,$textMsg);

$pdf->SetFont('Arial','B',10);
$textMsg = utf8_decode("DIRECCIÓN DE BIENES INMOBILIARIOS");
$x_centreado = $ancho/2 - $pdf->GetStringWidth($textMsg)/2;//EJEMPLO CENTREADO
$pdf->Text(312+$x_centreado,42,$textMsg);

//$pdf->SetFont('Arial','B',9);
$textMsg = utf8_decode("MAPA DE AFECTADOS - TRAMO ").$tramo_text;
$x_centreado = $ancho/2 - $pdf->GetStringWidth($textMsg)/2;//EJEMPLO CENTREADO
$pdf->Text(312+$x_centreado,47,$textMsg);


//$textMsg = "INFORMACION";
//$pdf->Text(320+22,39,$textMsg);
$pdf->SetFont('Arial','B',10);
$textMsg = utf8_decode("TRAMO: ");   
$pdf->Text(312,65,$textMsg);
$pdf->Text(312+50,65,$tramo_text);

$coloniadesc = "(".$col_cod.") ".$col_desc;
$dptodesc = "(".$dpto_cod.") ".$dpto_desc;
$distritodesc = "(".$dist_cod.") ".$dist_desc;

$textMsg = "DEPARTAMENTO: ";   
$pdf->Text(312,70,$textMsg);
$pdf->Text(312+50,70,$dptodesc);

$textMsg = "DISTRITO: ";   
$pdf->Text(312,75,$textMsg);
$pdf->Text(312+50,75,$distritodesc);

$textMsg = "PROGRESIVA INICIO: ";
$pdf->Text(312,80,$textMsg);
$pdf->Text(312+50,80,$pro_inicio);

$sup_legal=(double)0;

$textMsg = "PROGRESIVA FIN: ";   
$pdf->Text(312,85,$textMsg);
$pdf->Text(312+50,85,$pro_fin);


//$pdf->SetFillColor(251,187,0);
//$pdf->Rect(312, 90, 96, 65, 'F');//RECUADRO DEL INFORME

//DATOS DEL INFORME
$linea=95;//renglon
$separador=5;//intro
$pdf->SetFont('Arial','B',10);
$textMsg = utf8_decode("Afectacción");
$linea = ($linea + $separador) ;
$pdf->Text(313,$linea,$textMsg);//30c,28p,13s,34p,

$textMsg = "Cantidad";
$pdf->Text(313+50,$linea,$textMsg);

$textMsg = "%";
$pdf->Text(313+73,$linea,$textMsg);


$pdf->Line(313,$linea+2,405,$linea+2);

$pdf->SetFont('Arial','',12);

$textMsg = utf8_decode("Franja Construcción");
$pdf->Text(313,$linea+8,$textMsg);

$textMsg = "Franja Dominio";
$pdf->Text(313,$linea+16,$textMsg);

$textMsg = utf8_decode("Entrada de Máquina");
$pdf->Text(313,$linea+24,$textMsg);

$textMsg = "Sin Clasificar";
$pdf->Text(313,$linea+32,$textMsg);




//$result = pg_query ($link_bd,"select mapear, sum(st_area(geom)) superficie, count(*) cantidad, round((sum(st_area(geom))*100 / a.sup_tot)::numeric,2) porcentaje from indert.in_temp, (select sum(st_area(geom)) sup_tot from indert.in_temp where dpto = '".$dpto."' and distrito = '".$distrito."' and colonia = ".$colonia.") a where dpto = '".$dpto."' and distrito = '".$distrito."' and colonia = ".$colonia." group by mapear, a.sup_tot");
$result = pg_query ($link_bd,
							"select clasificacion, 
							count(*) cantidad,
							count(*)*100::decimal / b.cant_tot::decimal porc_cant,
							sum(st_area(geom)) superficie, 
							round((sum(st_area(geom))*100 / a.sup_tot)::numeric,2) porc_sup
							from ide.v_terrenos_ci_si, 
							(select sum(st_area(geom)) sup_tot from ide.v_terrenos_ci_si where id_tramo =".$objectid.") a,
							(select count(*) cant_tot from ide.v_terrenos_ci_si where id_tramo =".$objectid.") b 
							where id_tramo =".$objectid." 
							group by clasificacion, a.sup_tot, b.cant_tot;");

while ($r_parcela = pg_fetch_array($result))
{
	$clasificacion  = $r_parcela[clasificacion];
	$cantidad  = $r_parcela[cantidad];
	$porc_cant  = $r_parcela[porc_cant];
    $superficie  = round($r_parcela[superficie],2);
    $porc_sup  = $r_parcela[porc_sup];
	
	$separador = 6;
	$pdf->SetFont('Arial','',12);
	
	switch ($clasificacion) {
		case '1': //Entrada de Máquina
			$textMsg = $cantidad;
			$pdf->Text(313+55,$linea+8,$textMsg);

			$textMsg = round($porc_cant,2);
			$pdf->Text(313+70,$linea+8,$textMsg);

			/*$textMsg = $superficie;
			$pdf->Text(365,$linea+8,$textMsg);

			$textMsg = $porc_sup;
			$pdf->Text(395,$linea+8,$textMsg);*/
			break;
		case '2':
			$textMsg = $cantidad;//Franja Construccion
			$pdf->Text(313+55,$linea+16,$textMsg);

			$textMsg = round($porc_cant,2);
			$pdf->Text(313+70,$linea+16,$textMsg);

			/*$textMsg = $superficie;
			$pdf->Text(365,$linea+16,$textMsg);

			$textMsg = $porc_sup;
			$pdf->Text(395,$linea+16,$textMsg);*/
			break;
		case '3':
			$textMsg = $cantidad;//Franja Dominio
			$pdf->Text(313+55,$linea+24,$textMsg);

			$textMsg = round($porc_cant,2);
			$pdf->Text(313+70,$linea+24,$textMsg);

			/*$textMsg = $superficie;
			$pdf->Text(365,$linea+24,$textMsg);

			$textMsg = $porc_sup;
			$pdf->Text(395,$linea+24,$textMsg);*/
			break;
		case '4'://Sin Clasificar
			$textMsg = $cantidad;
			$pdf->Text(313+55,$linea+32,$textMsg);

			$textMsg = round($porc_cant,2);
			$pdf->Text(313+70,$linea+32,$textMsg);

			/*$textMsg = $superficie;
			$pdf->Text(365,$linea+32,$textMsg);

			$textMsg = $porc_sup;
			$pdf->Text(395,$linea+32,$textMsg);*/
			break;
	}
	$tot_cant 		= $tot_cant + $cantidad;
	$tot_porcentaje	= $tot_porcentaje + $porc_cant;
	/*
	$textMsg = "mapear: ".$mapear;
	$linea = ($linea + $separador + 6);
    $pdf->Text(292,$linea,$textMsg);

    $textMsg = "superfice: ".$superficie;
    $linea = ($linea + $separador) ;
    $pdf->Text(292,$linea,$textMsg);
	*/
}
	$pdf->SetFont('Arial','B',12);

	$pdf->Line(313,$linea+35,405,$linea+35);

	$textMsg = $tot_cant;
	$pdf->Text(313+55,$linea+40,$textMsg);

	$textMsg = $tot_porcentaje;
	$pdf->Text(313+70,$linea+40,$textMsg);

pg_free_result ($reqcat);
pg_close ();





$pdf->SetFillColor(255, 255, 255);
$pdf->SetFont('Arial','B',7.0);

$textMsg = "DEPARTAMENTAL";   
$pdf->Text(312,178,$textMsg);


$textMsg = "DISTRITAL";   
$pdf->Text(360,178,$textMsg);
$textMsg = "LEYENDA DEL MAPA";   
$pdf->Text(312,236,$textMsg);



$pdf->SetFont('Arial','B',5.0);
$textMsg = "IMPRESO POR: ".$nombreapellidousr;  
$pdf->Text(150,280,$textMsg);

$textMsg = "Fecha: ".$fecha." Hora: ".$hora;   
$pdf->Text(150,283,$textMsg);

$pdf->Close();
$nombre_archivo = "mapa_hoja".$hoja.".pdf";
$pdf->Output($nombre_archivo,"I", true);
?>
