<?php
header('Content-Type: application/json;charset= utf-8');
require("dl.php");


$DB_HOST = "www.imsaninsp.com";
$DB_USER = "imsanins_daniel";
$DB_PASS = "Santana1966";
$DB_NAME = "imsanins_cat_conexiones";

$con_produccion = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if(!$con_produccion){
    echo("Finaliza ejecución. NO SE PUEDE CONECTAR SERVIDOR DE PRODUCCION!!!!" .  PHP_EOL);
    exit;}
mysqli_set_charset($con_produccion,"utf8");


$res = array();

$mensaje_array = array();

set_time_limit(5000000);

$colectores_alejados = 0;

$sql = "SELECT A.id AS ID , ASTEXT(B.SHAPE) AS GEOMCOLECTOR, ST_X(ST_ENDPOINT(A.SHAPE)) as LON, ST_Y(ST_ENDPOINT(A.SHAPE)) AS LAT ,";
$sql .= "ST_X(ST_STARTPOINT(A.SHAPE)) AS LON2, ST_Y(ST_STARTPOINT(A.SHAPE)) AS LAT2  ";
$sql .= "FROM conexiones_snap AS A INNER JOIN v_ss_tramo AS B  ";
$sql .= "ON A.colector = B.elemred  "; 
$sql .= "WHERE activo = 1";
$cont = 0;
$resultado = mysqli_query($con_produccion,$sql);
if ($resultado != FALSE){
	if (mysqli_num_rows($resultado) > 0){
		while($row = mysqli_fetch_assoc($resultado))
		{
            $cont++;
            if ($cont > 100000)
                 {     
                        $linestring = $row['GEOMCOLECTOR'];
                        $lat = $row['LAT'];
                        $lon = $row['LON'];
                        $res_pu_cercano = dl_geometria::dl_punto_cercano_linestring($lat,$lon,$linestring);
                        if ($res_pu_cercano['distancia'] <= 1 && $res_pu_cercano['distancia'] > 0.01)
                                {
                                    $id=$row['ID'];
                                    $lat2=$row['LAT2'];
                                    $lon2=$row['LON2'];                 
                                    $sql2 = "UPDATE conexiones_snap SET SHAPE = GEOMFROMTEXT('LINESTRING(" . $lon2 . " " . $lat2 . "," . $res_pu_cercano['lon'] . " " . $res_pu_cercano['lat'];
                                    $sql2 .= ")')  WHERE id = " . $id;
                                    $resultado2 = mysqli_query($con_produccion,$sql2);
                                    echo ($id . PHP_EOL);
                                    $colectores_alejados++;
                                }
                                else
                                {
                                echo ("este ya lo hizo" . PHP_EOL);
                                }
                 } 
         }       
  }
} 
echo ("se modificaron " . $colectores_alejados . " conexiones. Fin" . PHP_EOL);
?>