<?php
ini_set('display_errors', 1);
require_once "config.php";
session_start();

if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == true){

$username = $_SESSION["username"];


//$HouseStreetInfo = $_SESSION["HouseStreetInfo"];
$ZipCode = $_SESSION["ZipCode"];
$City = $_SESSION["City"];
$State = $_SESSION["State"];
$Country = $_SESSION["Country"];

$arrcsc 	= array('mysqli'=>$mysqli, 'country' => $Country, 'state' => $State, 'city' => $City);
$getCTCdata = getCountryStateCity($arrcsc);

$Country= $getCTCdata['country_name'];
$State 	= $getCTCdata['state_name'];
$City 	= $getCTCdata['city_name'];
$Homeaddresswithspaces = $City." ".$State." ".$Country;
$Homeaddress = str_replace(" ","%20",$Homeaddresswithspaces);
$c_name = str_replace(" ","%20",$Country);


// $curl = curl_init("https://us1.locationiq.com/v1/search.php?key=pk.a3a9d5650529b95fdc1eda8e4625b40e&q={$Homeaddress}&accept-language=&countrycodes=United%20States&dedupe=0&normalizeaddress=1&postaladdress=1&format=json");

$curl = curl_init("https://us1.locationiq.com/v1/search.php?key=pk.a3a9d5650529b95fdc1eda8e4625b40e&q={$Homeaddress}&accept-language=&countrycodes={$c_name}&dedupe=0&normalizeaddress=1&postaladdress=1&format=json");
// print_r($curl);
// exit;
curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER    =>  true,
  CURLOPT_FOLLOWLOCATION    =>  true,
  CURLOPT_MAXREDIRS         =>  10,
  CURLOPT_TIMEOUT           =>  30,
  CURLOPT_CUSTOMREQUEST     =>  'GET',
));

$Homeresponse = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo 'cURL Error #:' . $err;
} else {

}

//isolating the latitude
$getlatlong = json_decode($Homeresponse)[0];

$Homelat =$getlatlong->lat;
$Homelon =$getlatlong->lon;

  $sql = "UPDATE users SET homelon=$Homelon, homelat=$Homelat WHERE username='$username'";
  $stmt = $mysqli->prepare($sql);
  $stmt->execute();
}

header("Location:".$baseurl);
?>