<?php
$server   = "localhost";
$username = "systemso_usuario";
$password = "Rivera2020*";
$database = "systemso_sis-track";


$mysqli = new mysqli($server, $username, $password, $database);

if ($mysqli->connect_error) {
    die('error'.$mysqli->connect_error);
}

$metodo=$_SERVER['REQUEST_METHOD'];

if($metodo=='GET'){
    $user = $_GET['user'];
    if($user=='ALL'){
        $query = mysqli_query($mysqli, "SELECT * FROM ubicacion");
        if(!$query){
            die('Error en la consulta'. mysqli_error($mysqli));
        }
        //$json[] = array();
        while($data = mysqli_fetch_array($query)){
            $json[] = array(
                'lat' => $data['lat'],
                'lng' => $data['lng'],
                'user' => $data['usuario']
            );
        }
        
        $jsonstring = json_encode($json);
        echo $jsonstring;  
    }else{
        $query = mysqli_query($mysqli, "SELECT * FROM ubicacion WHERE usuario='$user'");
        if(!$query){
            die('Error en la consulta'. mysqli_error($mysqli));
        }
        //$json[] = array();
        while($data = mysqli_fetch_array($query)){
            $json[] = array(
                'lat' => $data['lat'],
                'lng' => $data['lng'],
                'user' => $data['usuario']
            );
        }
        
        $jsonstring = json_encode($json[0]);
        echo $jsonstring; 
    }
    
}

if($metodo=='POST'){
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];
    $u = $_POST['u'];
    $fecha = date("Y-m-d H:i:s");
    
    $query = mysqli_query($mysqli, "UPDATE ubicacion SET lat='$lat', lng='$lng', fecha='$fecha' WHERE usuario='$u'");
    if(!$query){
        die('Error en la consulta'. mysqli_error($mysqli));
    }
    echo "Registro actualizado";   
}

?>