<?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"];
//echo $map_file;
//exit;
/*$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"];                     
$total_hojas 	 	  = $_GET["total_hojas"];          //Nuevo



$hoja                 = 0;



$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."'";
}



$postgis_mapa = $_SESSION["postgis_mapa"];
//require_once (dirname(__FILE__)."/../i3geo/ms_configura.php");
require_once (dirname(__FILE__)."/config/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__)."/../i3geo/classesphp/carrega_ext.php");
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');
	    echo 'es en WINDOWS';
    }
	else
	{
    	dl('php_mapscript.so');
    	echo 'es en linux';
    }
}
else
{
    //dl('php_mapscript.so');
    echo 'Error';
}
*/

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 



//echo 'Verificandoo'.$nomes;

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

//$link_bd = pg_connect("host=45.10.163.71 port=5432 dbname=expropiacion user=sge password=2l2f1nt22022i");

//$link_bd = pg_connect("user=sge password=2l2f1nt22022i dbname=expropiacion host=45.10.163.71 port=5432");

//echo 'Conectado';

$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
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------

		$map_file = "/var/www/html/sgeReport/map_files/mopc_gl_a3_tramo_afectacion2.map";
		$map = ms_newMapObj($map_file);
		$temp = str_replace(".map",$nomes.".map",$map_file);
		$map->save($temp);
		$map = ms_newMapObj($temp);
		restauraCon($temp,$postgis_mapa);

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


		$capas = $map->getalllayernames();
		foreach ($capas as $capa)
		{
			$layer = $map->getlayerbyname($capa);
        	$v_name = $layer->name;				
            //echo $v_name;  
			//if (($layer->data != "") && (strtolower($layer->getmetadata("escondido")) != "sim") && (strtolower($layer->getmetadata("tema")) != "nao"))
        	if (($layer->data != ""))
			{
         
				$existedato = "NO";
				//if (($layer->getmetadata("tema")=="tramos_plano"))
            	if (($v_name=="tramos_plano"))
				{
					$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->getmetadata("tema")=="plano_terrenos_ci"))
            	if (($v_name=="plano_terrenos_ci"))
				{

					$sq='select st_setsrid(the_geom,4326) as the_geom,id_exp,id_proyec,codigo,des_codigo_unico,des_codigo_proyecto,des_proyecto,tipo,tramo,subtramo,obs,nombre,sup_sig_m2,sup_sig_ha,sup_legal,id_tramo,fc,fd,id_estado_agrupado_gerencial,estado_agrupado_gerencial,clasificacion,gid from ide.v_terrenos_ci_si_i3geo 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', 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");
					}
				}
			}*/
            
		}

		//echo 'casi llegamos';


		$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();

        //echo 'casi llegamos: '.$numresults;
        
		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;
		}
		$par_escala=1;

	$hoja=0;
	

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

		if ($total_hojas > 8)
		{
			$total_hojas=8;
		}

    		//echo 'antes de while';
    		//exit;

	//while ($hoja != $total_hojas ) {
		$hoja = $hoja + 1;	
		$sq = "
		select
		cast(round(cast((j.b_x1-((j.b_x2-j.b_x1)/20)/"."1".") as decimal),13) as text) as ext1, 
		cast(round(cast((j.b_y1-((j.b_y2-j.b_y1)/20)/"."1".") as decimal),13) as text) as ext2, 
		cast(round(cast((j.b_x2+((j.b_x2-j.b_x1)/20)/"."1".") as decimal),13) as text) as ext3, 
		cast(round(cast((j.b_y2+((j.b_y2-j.b_y1)/20)/"."1".") as decimal),13) as text) as ext4 
		from 
		(select 
		round(cast((x.x1+((x.x2-x.x1)/".$total_hojas.")*".($hoja-1).") as decimal),13) as b_x1, 
		round(cast(x.y1 as decimal),13) as b_y1, 
		round(cast((x.x1+((x.x2-x.x1)/".$total_hojas.")*".$hoja.") as decimal),13) as b_x2, 
		round(cast(x.y2 as decimal),13) as b_y2,
		x.x1,
		x.y1,
		x.x2,
		x.y2  
		from 
		(select 
		cast((regexp_split_to_array(bb, E','))[1] as decimal) as x1, 
		cast((regexp_split_to_array(bb, E','))[2] as decimal) as y1, 
		cast((regexp_split_to_array(bb, E','))[3] as decimal) as x2, 
		cast((regexp_split_to_array(bb, E','))[4] as decimal) as y2 
		from 
		(select 
		replace(replace(substr(cast(a.bb as varchar),5),' ',',') ,')','') as bb  
		from 
		(select ST_Extent(the_geom) bb from 
		(select 1 objectid, st_union(st_snaptogrid(the_geom,0.00000000000001)) the_geom 
		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." ))
		) e 
		) as a) as t1) as x) j;
		";

		//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 ();

        //echo $sq;
        //echo $ext1.' '.$ext2.' '.$ext3.' '.$ext4;

		$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> " . 'escala:'.$escala. " </p>";
		pg_free_result ($result_escala);
		pg_close ();

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

		//echo ' Escala '.$escala;
		
		$o->set("imagemode",MS_IMAGEMODE_RGB);
		$o->set("transparent","false");
		

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

	
    	//echo "buscando error";


    	//echo "debugueando";
        /*    	
        $map_path = '/var/www/html/sgeReport/tmp/';
        $imgo = $map->draw();
        $nomer = ($imgo->imagepath)."mapa".$nomes.".png";
        $nombre = ($imgo->imagepath)."mapa".$nomes.".png";
        //$nomer = $map_path."mapa".$nomes.".png";
        //$nombre = $map_path."mapa".$nomes.".png";
        //echo $nomer;
        //if($nombre == "")        
        if($imgo->imagepath == "")
        {echo "Erro IMAGEPATH vazio";exit;}
        $nombre_imagen = $imgo->imagepath."imagen_".$nombre.".png";
        //echo "antes de guardar imagen";
        $imgo->saveImage($nombre_imagen);
        */
        
        
        
        //Obtenemos la imagen
        $nombre = ($imgo->imagepath)."mapa".$nomes.".png";
        $imgo = $map->draw();
        if($imgo->imagepath == "")
        {echo "Error IMAGEPATH vacia";exit;}
        $nombre_imagen = $imgo->imagepath."imagen_".$nombre.".png";
        $imgo->saveImage($nombre_imagen);
        // carga map file 
        //$map = ms_newMapObj($map_file);
        $w = $map->width;
        $h = $map->height;

        
        
        
        echo "debugueando";

    		//exit;
    		
    	/*
		if ($hoja == 1) {       
        	//echo 'un paso mas 1';
        	$imgo = $map->draw();
			if($imgo->imagepath == "")
			  {echo "Erro IMAGEPATH vazio h1";exit;}
		    $nomer = ($imgo->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo->saveImage($nomer);        
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomer);
			//CONFIGURACION DE LA LEYENDA
		    //echo 'un paso mas 1';
        	$imgo = $map->drawlegend();
			$nomerl = ($imgo->imagepath)."leg".$nomes.$hoja.".png";
			$imgo->saveImage($nomerl);
			$pathlegenda = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomerl);	 
        	//echo 'un paso mas 2';
        
		} elseif ($hoja == 2) {
			$imgo2 = $map->draw();
			if($imgo2->imagepath == "")
			{echo "Erro IMAGEPATH vazio h2";exit;}
		    $nomer2 = ($imgo2->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo2->saveImage($nomer2);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa2 = $dir_tmp."/".basename($imgo2->imageurl)."/".basename($nomer2);
			//CONFIGURACION DE LA LEYENDA
			$imgo2 = $map->drawlegend();
			$nomerl2 = ($imgo2->imagepath)."leg".$nomes.$hoja.".png";
			$imgo2->saveImage($nomerl2);
			$pathlegenda2 = $dir_tmp."/".basename($imgo2->imageurl)."/".basename($nomerl2);   
		} elseif ($hoja == 3) {
			$imgo3 = $map->draw();
			if($imgo3->imagepath == "")
			{echo "Erro IMAGEPATH vazio h3";exit;}
		    $nomer3 = ($imgo3->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo3->saveImage($nomer3);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa3 = $dir_tmp."/".basename($imgo3->imageurl)."/".basename($nomer3);
			//CONFIGURACION DE LA LEYENDA
			$imgo3 = $map->drawlegend();
			$nomerl3 = ($imgo3->imagepath)."leg".$nomes.$hoja.".png";
			$imgo3->saveImage($nomerl3);
			$pathlegenda3 = $dir_tmp."/".basename($imgo3->imageurl)."/".basename($nomerl3);
		} elseif ($hoja == 4) {
			$imgo4 = $map->draw();
			if($imgo4->imagepath == "")
			{echo "Erro IMAGEPATH vazio h4";exit;}			
		    $nomer4 = ($imgo4->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo4->saveImage($nomer4);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa4 = $dir_tmp."/".basename($imgo4->imageurl)."/".basename($nomer4);
			//CONFIGURACION DE LA LEYENDA
			$imgo4 = $map->drawlegend();
			$nomerl4 = ($imgo4->imagepath)."leg".$nomes.$hoja.".png";
			$imgo4->saveImage($nomerl4);
			$pathlegenda4 = $dir_tmp."/".basename($imgo4->imageurl)."/".basename($nomerl4);
		} elseif ($hoja == 5) {
			$imgo5 = $map->draw();
			if($imgo5->imagepath == "")
			{echo "Erro IMAGEPATH vazio h5";exit;}			
		    $nomer5 = ($imgo5->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo5->saveImage($nomer5);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa5 = $dir_tmp."/".basename($imgo5->imageurl)."/".basename($nomer5);
			//CONFIGURACION DE LA LEYENDA
			$imgo5 = $map->drawlegend();
			$nomerl5 = ($imgo5->imagepath)."leg".$nomes.$hoja.".png";
			$imgo5->saveImage($nomerl5);
			$pathlegenda5 = $dir_tmp."/".basename($imgo5->imageurl)."/".basename($nomerl5);
		} elseif ($hoja == 6) {
			$imgo6 = $map->draw();
			if($imgo6->imagepath == "")
			{echo "Erro IMAGEPATH vazio h6";exit;}			
		    $nomer6 = ($imgo6->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo6->saveImage($nomer6);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa6 = $dir_tmp."/".basename($imgo6->imageurl)."/".basename($nomer6);
			//CONFIGURACION DE LA LEYENDA
			$imgo6 = $map->drawlegend();
			$nomerl6 = ($imgo6->imagepath)."leg".$nomes.$hoja.".png";
			$imgo6->saveImage($nomerl6);
			$pathlegenda6 = $dir_tmp."/".basename($imgo6->imageurl)."/".basename($nomerl6);
		} elseif ($hoja == 7) {
			$imgo7 = $map->draw();
			if($imgo7->imagepath == "")
			{echo "Erro IMAGEPATH vazio h7";exit;}			
		    $nomer7 = ($imgo7->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo7->saveImage($nomer7);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa7 = $dir_tmp."/".basename($imgo7->imageurl)."/".basename($nomer7);
			//CONFIGURACION DE LA LEYENDA
			$imgo7 = $map->drawlegend();
			$nomerl7 = ($imgo7->imagepath)."leg".$nomes.$hoja.".png";
			$imgo4->saveImage($nomerl7);
			$pathlegenda7 = $dir_tmp."/".basename($imgo7->imageurl)."/".basename($nomerl7);
		} elseif ($hoja == 8) {
			$imgo8 = $map->draw();
			if($imgo8->imagepath == "")
			{echo "Erro IMAGEPATH vazio h8";exit;}			
		    $nomer8 = ($imgo8->imagepath)."mapa".$nomes.$hoja.".png";
			$imgo8->saveImage($nomer8);
			$protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);
			$pathMapa8 = $dir_tmp."/".basename($imgo8->imageurl)."/".basename($nomer8);
			//CONFIGURACION DE LA LEYENDA
			$imgo8 = $map->drawlegend();
			$nomerl8 = ($imgo8->imagepath)."leg".$nomes.$hoja.".png";
			$imgo8->saveImage($nomerl8);
			$pathlegenda8 = $dir_tmp."/".basename($imgo8->imageurl)."/".basename($nomerl8);
		} else {
          	$imgo = $map->draw();
			if($imgo->imagepath == "")
			  {echo "Erro IMAGEPATH vazio h0";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
		    //echo 'un paso mas 1';
        	$imgo = $map->drawlegend();
			$nomerl = ($imgo->imagepath)."leg".$nomes.".png";
			$imgo->saveImage($nomerl);
			$pathlegenda = $dir_tmp."/".basename($imgo->imageurl)."/".basename($nomerl);	 
        	//echo 'un paso mas 2';
		}
		*/
		
		
        /*		
		$nomer = ($imgo->imagepath)."mapa".$nomes.$hoja.".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.$hoja.".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
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
		//----------------------------------------------------------------------------------
	//}
	
	
echo 'pasamos la generacion de imagenes';

//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//------- 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');
require(dirname(__FILE__).'/pacotes/fpdf/rpdf.php');
#$pdf = new FPDF("L","mm",array(297,420));
#$pdf = new RPDF("L","mm",array(297,210));
#$pdf = new FPDF("L","mm","A3");
$pdf = new RPDF("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);


$total_hojas=1;
$hoja = 0;

while ($hoja != $total_hojas ) {


	$hoja = $hoja + 1;

    //echo "generando hoja   ".$hoja;

	$tramo_text = $dato[nombre];
	$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


		if ($hoja == 1) {
        	//echo "generando hoja   1".$hoja;
        	//echo "path ".$pathMapa;
			$mapasize = getimagesize($pathMapa);
		} elseif ($hoja == 2) {
			$mapasize = getimagesize($pathMapa2);
			$pathMapa = $pathMapa2;
			$pathlegenda = $pathlegenda2;
		} elseif ($hoja == 3) {
			$mapasize = getimagesize($pathMapa3);
			$pathMapa = $pathMapa3;
			$pathlegenda = $pathlegenda3;
		} elseif ($hoja == 4) {
			$mapasize = getimagesize($pathMapa4);
			$pathMapa = $pathMapa4;
			$pathlegenda = $pathlegenda4;
		} elseif ($hoja == 5) {
			$mapasize = getimagesize($pathMapa5);
			$pathMapa = $pathMapa5;
			$pathlegenda = $pathlegenda5;
		} elseif ($hoja == 6) {
			$mapasize = getimagesize($pathMapa6);
			$pathMapa = $pathMapa6;
			$pathlegenda = $pathlegenda6;
		} elseif ($hoja == 7) {
			$mapasize = getimagesize($pathMapa7);
			$pathMapa = $pathMapa7;
			$pathlegenda = $pathlegenda7;
		} elseif ($hoja == 8) {
			$mapasize = getimagesize($pathMapa8);
			$pathMapa = $pathMapa8;
			$pathlegenda = $pathlegenda8;
		}

	//$mapasize = getimagesize($pathMapa);
	$wMapa = $mapasize[0];
	$hMapa = $mapasize[1];




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


//echo $wMapa.' '.$hMapa.' '.$nW.' '.$nH;

$pdf->Text(312,27,$wMapa);
$pdf->Text(312,37,$hMapa);




	//Ancho y alto para el recuadro del mapa

	//Medidas de un A3: 420x297 mm // 11,693 x 16,535 pulgadas // 29,7 x 42 cm.

	$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
	//echo($pathMapa);
	$pdf->Image($pathMapa, 10, 10, 295, 262);//imagen principal del mapa
	$pdf->Rect(10, 10, $anchomap-20, $altomap-20, 'D');//Mapa CONTORNO DE LA HOJA

//echo "genero imagen";

	//$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, 295, 262, 'D');// recuadro2del 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);

//echo "genero imagen";

	$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;
//echo "genero recuadros";
	//-------------------------------------------------------------------------------
	//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);


//echo "genero logos";



	//                                               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);

	$sq = "
	select
	round((st_x(st_centroid(u.geom))-((10)::numeric*u.escala)/100)) cuadricula_x1_2, 
	round((st_x(st_centroid(u.geom)))) cuadricula_x2_2, 
	round((st_x(st_centroid(u.geom))+((10)::numeric*u.escala)/100)) cuadricula_x3_2, 
	round((st_y(st_centroid(u.geom))+(u.e_y2_utm-u.e_y1_utm)*81/262)) cuadricula_y1_2, 
	round((st_y(st_centroid(u.geom))-(u.e_y2_utm-u.e_y1_utm)*181/262)) cuadricula_y2_2, 
	(u.e_y1_utm+(u.e_y2_utm-u.e_y1_utm)*81/262) cuadricula_y1,
	(u.e_y1_utm+(u.e_y2_utm-u.e_y1_utm)*181/262) cuadricula_y2,
	st_x(st_centroid(u.geom)) centroide_real_utm_x,
	st_y(st_centroid(u.geom)) centroide_real_utm_y, 
	(u.e_x1_utm+(u.e_x2_utm-u.e_x1_utm)/2) centroide_utm_x,
	(u.e_y1_utm+(u.e_y2_utm-u.e_y1_utm)/2) centroide_utm_y,
	((u.e_y2_utm-u.e_y1_utm)*81/262) distancia_utm_cuadricula_y1, 
	(u.e_x2_utm-u.e_x1_utm) distancia_utm_x_obj,
	(u.e_y2_utm-u.e_y1_utm) distancia_utm_y,
	u.distancia_d,
	u.distancia_x,
	u.distancia_y,
	u.distancia_y_3857,
	u.distancia_y_s2,
	u.distancia_y_s,
	(u.distancia_y/29.5)*100 escala2,
	u.escala,
	u.e_x1_utm,
	u.e_y1_utm,
	u.e_x2_utm,
	u.e_y2_utm,
	u.e_x1,
	u.e_y1,
	u.e_x2,
	u.e_y2,
	u.geom
	from 
	(select   
	ST_Distance(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 32721),
	ST_Transform('SRID=4326;POINT('||t.e_x2||' '||t.e_y2||')', 32721)) distancia_d, 
	ST_Distance(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 32721),
	ST_Transform('SRID=4326;POINT('||t.e_x2||' '||t.e_y1||')', 32721)) distancia_x,
	ST_Distance(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 3857),
	ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y2||')', 3857)) distancia_y_3857,
	ST_Distance(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 32721),
	ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y2||')', 32721)) distancia_y,
	ST_Distance(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 4326),
	ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y2||')', 4326),true) distancia_y_s2,
	ST_Distance(st_geomfromtext('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')'),
	st_geomfromtext('SRID=4326;POINT('||t.e_x1||' '||t.e_y2||')'),true) distancia_y_s,
	ide.calcular_escala_real_dec(t.e_x1::numeric,t.e_y1::numeric,t.e_x1::numeric,t.e_y2::numeric,29.5) escala,
	st_x(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 32721)) e_x1_utm,
	st_y(ST_Transform('SRID=4326;POINT('||t.e_x1||' '||t.e_y1||')', 32721)) e_y1_utm,
	st_x(ST_Transform('SRID=4326;POINT('||t.e_x2||' '||t.e_y2||')', 32721)) e_x2_utm, 
	st_y(ST_Transform('SRID=4326;POINT('||t.e_x2||' '||t.e_y2||')', 32721)) e_y2_utm,
	t.e_x1,
	t.e_y1,
	t.e_x2,
	t.e_y2,
	ST_Transform(st_setsrid(t.geom,4326),32721) geom
	from  
	(select 
	cast(round(cast((puntos.x1-(puntos.x2-puntos.x1)/40) as decimal),13) as text) as e_x1, 
	cast(round(cast((puntos.y1-(puntos.y2-puntos.y1)/40) as decimal),13) as text) as e_y1, 
	cast(round(cast((puntos.x2+(puntos.x2-puntos.x1)/40) as decimal),13) as text) as e_x2, 
	cast(round(cast((puntos.y2+(puntos.y2-puntos.y1)/40) as decimal),13) as text) as e_y2, 
	puntos.x1,
	puntos.y1,
	puntos.x2,
	puntos.y2,
	puntos.geom 
	from 
	(select 
	cast((regexp_split_to_array(e.bb, E','))[1] as decimal) as x1, 
	cast((regexp_split_to_array(e.bb, E','))[2] as decimal) as y1, 
	cast((regexp_split_to_array(e.bb, E','))[3] as decimal) as x2, 
	cast((regexp_split_to_array(e.bb, E','))[4] as decimal) as y2,
	e.geom 
	from 
	(select 
	cast(b.bb as varchar) c1,
	substr(cast(b.bb as varchar),5) c2,
	replace(substr(cast(b.bb as varchar),5),' ',',') c3,
	replace(replace(substr(cast(b.bb as varchar),5),' ',',') ,')','') as bb,  
	b.geom
	from 
	(select ST_Extent(l.the_geom) bb,st_union(l.the_geom) geom  
	from i3geo.tramos l 
	where l.id_tramo = ".$objectid." 
	or l.id_tramo in (select i.id_tramo from public.tramos i where i.tramo_padre=".$objectid." )
	) b 
	) e
	) puntos
	) t
	) u 

	";
	//echo $sq;
	$result10 = pg_query ($link_bd,$sq);
	if ($r_calculo4 = pg_fetch_array($result10))
	{
		$utm_y_1=(double)$r_calculo4["cuadricula_y1_2"];
	    $utm_y_2=(double)$r_calculo4["cuadricula_y2_2"];
	    $utm_x_1=(double)$r_calculo4["cuadricula_x1_2"];
	    $utm_x_2=(double)$r_calculo4["cuadricula_x2_2"];
	    $utm_x_3=(double)$r_calculo4["cuadricula_x3_2"];
	}
		
	//$pdf->Image($pathMapa, 11, 36, $nW, $nH);
    //echo $utm_y_1;
	//exit;
    
	$pdf->SetLineWidth(0.4);
	//$pdf->SetDash(5,5); //5mm on, 5mm off

	//8,1	13,1	18,1		
	//4,75	14,75	24,75
	//$pdf->Image($pathMapa, 10, 10, 295, 262);//imagen principal del mapa

	//CUARICULA SUPERIOR
	$pdf->Line( 57.5, 10, 57.5, 11);
	$pdf->Line(157.5, 10,157.5, 11);
	$pdf->Line(257.5, 10,257.5, 11);
	//CUARICULA INFERIOR
	$pdf->Line( 57.5,271, 57.5,272);
	$pdf->Line(157.5,271,157.5,272);
	$pdf->Line(257.5,271,257.5,272);
	//CUARICULA VERTICAL IZQUIERDA
	$pdf->Line(10, 91,11, 91);
	$pdf->Line(10,191,11,191);
	//CUARICULA VERTICAL DERECHA
	$pdf->Line(304,	91,305,	91);
	$pdf->Line(304,191,305,191);

	// cambiar FONT PARA cuadricula
	$pdf->SetFont('Arial','B',6.0);
	$pdf->SetFillColor(255,0,0);
	
	//CUADRICULA VERTICAL IZQUIERDA
	$pdf->TextWithDirection(  9.0, 91+4,$utm_y_1,'U');
	$pdf->TextWithDirection(  9.0,191+4,$utm_y_2,'U');
	//CUADRICULA VERTICAL DERECHA
	$pdf->TextWithDirection(307.5, 91+4,$utm_y_1,'U');
	$pdf->TextWithDirection(307.5,191+4,$utm_y_2,'U');
	//CUADRICULA HORIZONTAL IZQUIERDA
	$pdf->Text( 57.5-3.5, 9,$utm_x_1,'U');
	$pdf->Text(157.5-3.5, 9,$utm_x_2,'U');
	$pdf->Text(257.5-3.5, 9,$utm_x_3,'U');
	//CUADRICULA HORIZONTAL DERECHA
	$pdf->Text( 57.5-3.5,275,$utm_x_1,'U');
	$pdf->Text(157.5-3.5,275,$utm_x_2,'U');
	$pdf->Text(257.5-3.5,275,$utm_x_3,'U');

}
//echo 'fin';
$pdf->Close();
$nombre_archivo = "mapa_hoja".$hoja.".pdf";
$pdf->Output($nombre_archivo,"I", true);
?>
