Files
dev-chiefworks f76abffdcd first commit
2022-05-31 16:21:53 -04:00

91 lines
3.3 KiB
PHP

<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('geofence_area_city_model');
}
public function geocodeReverse($latitude, $longitude)
{
//$this->output(['city' => "Wrocław"]);
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
// Call geocoding service
$url = "http://oauth2.service/api/v1/reverse/?lat=" . $latitude . '&lng=' . $longitude;
$opts = array(
'http' => array(
'method' => "GET",
'timeout' => 60, /* 1 minute */
'header' =>
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/json\r\n" .
"Authorization: Server-Token ${httpAuthToken}\r\n",
),
);
$context = stream_context_create($opts);
$body = file_get_contents($url, false, $context);
$geocoded = json_decode($body, true);
if (is_array($geocoded) && is_array($geocoded["data"]) && !isset($geocoded["error"])) {
return $geocoded["data"]['city'];
}
return null;
}
public function updatecity($id, $latitude, $longitude)
{
$error = 1;
$city = $this->geocodeReverse($latitude, $longitude);
if (!empty($city)) {
$inputData = [
'city' => $city,
];
if ($this->geofence_area_city_model->update($id, $inputData) > 0) {
$error = 0;
$this->output(['error' => $error, 'msg' => 'Updated geofence area city successfully.','city'=>$city]);
} else {
$this->output(['error' => $error, 'msg' => 'Updated failed.','city'=>$city]);
}
}
$this->output(['error' => $error, 'msg' => 'Invalid input.','city'=>$city]);
}
public function cleanupCities(){
$duplicateds=$this->geofence_area_city_model->getDuplicatedCities();
$error=0;
foreach($duplicateds as $city){
$city_name =$city->city;
$country =$city->country;
$condition="LOWER(city) ILIKE '" . strtolower(pg_escape_string($city_name)) . "' AND country='" . $country . "'";
$city_ids = $this->geofence_area_city_model->getCities($condition);
$num = count($city_ids);
if ($num > 0) {
$ids=[];
foreach ($city_ids as $info) {
$ids[]=$info->id;
}
if(count($ids)>0){
$city_id = $ids[0];
$data_update = [
'city_id' => $city_id,
];
$condition = "country='" . $country . "' AND city_id IN (" . implode(",", $ids) . ")";
$updated = $this->geofence_area_city_model->updateAddresses($condition, $data_update);
}
}
}
$this->geofence_area_city_model->deleteUnusedCities();
$this->output(['error' => $error, 'msg' => 'Clean up successfully']);
}
private function output($output)
{
echo json_encode($output);exit;
}
}