<?php

    include('/var/www/html/track/server/s_insert.php');
    include('/var/www/html/track/server/eventos.php');
    $data = json_decode(file_get_contents("php://input"), true);
    $loc = $data;
  

    $loc['overpass'] = 0;
   
    if (!isset($loc['imei'])) {
        mysqli_close($ms);
        die;
    }

    if ($loc['lat'] == 0 && $loc['lng'] == 0) {
        mysqli_close($ms);
        die;
    }

    $loc['dt_server'] = gmdate("Y-m-d H:i:s");
    if (!isset($loc['dt_tracker'])) {
        mysqli_close($ms);
        die;
    }

    $q_run_speed = 'SELECT run_speed, overpass FROM gs_objects WHERE imei = '.$loc['imei'].'';
    $r_run_speed = mysqli_query($ms, $q_run_speed) ;
    $row = mysqli_fetch_array($r_run_speed);

    $respeed =$row['run_speed'];
    $reoverpass =$row['overpass'];

    if ($reoverpass==1) {
        $url = 'http://35.208.70.195/api/interpreter?data=[out:json];way(around:5.0,'.$loc['lat'].','.$loc['lng'].');out;';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $jsondata = json_decode(curl_exec($ch), true);
        curl_close($ch);
        
        $result4 = 0;
        for($i = 0; $i < 16; $i++){
                if (isset($jsondata['elements'][$i]['tags']['maxspeed']))
                {
                    $result4 = $jsondata['elements'][$i]['tags']['maxspeed'];
                    break;
                }
        }

        $result2 = json_encode($result4);
        $result2 = str_replace('"','',$result2);
        $loc['overpass'] = intval($result2);
    }


    $variableJSON = json_encode($loc['params']);

    if ($loc["op"] == "loc") {

        if (strpos($variableJSON, '{"adc1"') !== false) { // Usamos !== false para evitar falsos positivos
            var_dump('cadena omitida');
            // error_log("Cadena omitida 1 : " . $variableJSON, 0);
        } else {
            if (strpos($variableJSON, '{"status"') !== false) {
                // error_log("Cadena omitida: " . $variableJSON, 0);
                var_dump('cadena omitida 2');
            } else {
                insert_db_loc($loc);
            }
        }
    }
            // elseif ($loc["op"] == "noloc") {
            //     insert_db_noloc($loc);
            // } elseif ($loc["op"] == "imgloc") {
            //     insert_db_imgloc($loc); 
            // }

    mysqli_close($ms);
    die;
