<?php

include_once("server/lib/mod_dbm/package.dbm.php");
/*
 * ROMAN DIGITAL - Autor: Américo Patetta
 */

/**
 * Description of Location
 *
 * @author pc
 */
class Location {

    private $lat;
    private $lng;
    private $road;
    private $hNum;
    private $city;
    private $state;
    private $country;
    private $postCode;
    private $dao;
    private $locationId=null;
    // CURL
    private $templateUrl = "https://nominatim.openstreetmap.org/reverse?format=json&lat=%s&lon=%s&zoom=%d&addressdetails=%d";

    function __construct($id = null) {
        $this->dao = new dbObject();
        if ($id != null) {
            $this->retrieve($id);
        }
    }

    // Misc
    function create($lat, $lng, $zoom = 24, $details = 1) {
        
        $this->lat = $lat;
        $this->lng = $lng;
        
        $geoCodingResponse = $this->getContent(sprintf($this->templateUrl, $lat, $lng, $zoom, $details));
        $decodedResponse = json_decode($geoCodingResponse, true, 512, JSON_OBJECT_AS_ARRAY);
        
        $this->hNum = (isset($decodedResponse['address']['house_number'])) ? $decodedResponse['address']['house_number'] : null;
        $this->road = (isset($decodedResponse['address']['road'])) ? $decodedResponse['address']['road'] : null;
        $this->city = (isset($decodedResponse['address']))?$this->determineCity($decodedResponse['address']):null;
        $this->state = (isset($decodedResponse['address']['state'])) ? $decodedResponse['address']['state'] : null;
        $this->country = (isset($decodedResponse['address']['country'])) ? $decodedResponse['address']['country'] : null;
        $this->postCode = (isset($decodedResponse['address']['postcode'])) ? $decodedResponse['address']['postcode'] : null;
    }
    function determineCity($address) {
        
        if (isset($address['city'])) {
            $city = $address['city'];
        } elseif (isset($address['town'])) {
            $city = $address['town'];
        } elseif (isset($address['village'])) {
            $city = $address['village'];
        } elseif (isset($address['hamlet'])) {
            $city = $address['hamlet'];
        } else {
            $city = null;
        }
        return $city;
        
    }
    function getContent($url) {
        $options = array(
            CURLOPT_RETURNTRANSFER => true, // return web page
            CURLOPT_HEADER => false, // don't return headers
            CURLOPT_FOLLOWLOCATION => true, // follow redirects
            CURLOPT_ENCODING => "", // handle all encodings
            CURLOPT_USERAGENT => "spider", // who am i
            CURLOPT_AUTOREFERER => true, // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
            CURLOPT_TIMEOUT => 120, // timeout on response
            CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
            CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
        );

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $content = curl_exec($ch);
        $err = curl_errno($ch);
        $errmsg = curl_error($ch);
        $header = curl_getinfo($ch);
        curl_close($ch);
        //print_r($content);
        $header['errno'] = $err;
        $header['errmsg'] = $errmsg;
        $header['content'] = $content;
        return $content;
    }
    function persist() {
        if ($this->locationId) {
            $this->updateLocation();
        } else {
            $this->insertLocation();
        }
        return $this->locationId;
    }
    function insertLocation() {
        $q = sprintf("INSERT INTO locations (lat, lng, road, num_casa, city, state, country, postcode) VALUES (%s,%s,'%s','%s','%s','%s','%s','%s')", $this->lat, $this->lng, $this->road, $this->hNum, $this->city, $this->state, $this->country, $this->postCode);
        $this->dao->execute($q);
        $this->locationId = $this->dao->getAutoInc();
        return $this->locationId;
    }
    function updateLocation() {
        $q = sprintf("UPDATE locations SET lat=%s, lng=%s, road=%s, num_casa=%s, city=%s, state=%s, country=%s, postcode=%s WHERE location_id = %d", $this->lat, $this->lng, $this->road, $this->hNum, $this->city, $this->state, $this->country, $this->postCode, $this->location_id);
    }
    function retrieve($id) {
        $q = sprintf("SELECT * FROM locations WHERE location_id = %d", $id);
        $location = $this->dao->fetchQuery($q);
        if (is_array($location) && count($location)) {
            $this->lat = $location[0]['lat'];
            $this->lng = $location[0]['lng'];
            $this->road = $location[0]['road'];
            $this->hNum = $location[0]['num_casa'];
            $this->city = $location[0]['city'];
            $this->state = $location[0]['state'];
            $this->country = $location[0]['country'];
            $this->postCode = $location[0]['postcode'];
            $this->locationId = $location[0]['location_id'];
        } else {
            $this->lat = null;
            $this->lng = null;
            $this->road = null;
            $this->hNum = null;
            $this->city = null;
            $this->state = null;
            $this->country = null;
            $this->postCode = null;
            $this->locationId = null;
        }
    }

    // Getters
    public function getLat() {
        return $this->lat;
    }
    public function getLng() {
        return $this->lng;
    }
    public function getRoad() {
        return $this->road;
    }
    public function getHNum() {
        return $this->hNum;
    }
    public function getCity() {
        return $this->city;
    }
    public function getState() {
        return $this->state;
    }
    public function getCountry() {
        return $this->country;
    }
    public function getPostCode() {
        return $this->postCode;
    }
    
    // Setters
    public function setLat($lat): void {
        $this->lat = $lat;
    }
    public function setLng($lng): void {
        $this->lng = $lng;
    }
    public function setRoad($road): void {
        $this->road = $road;
    }
    public function setHNum($hNum): void {
        $this->hNum = $hNum;
    }
    public function setCity($city): void {
        $this->city = $city;
    }
    public function setState($state): void {
        $this->state = $state;
    }
    public function setCountry($country): void {
        $this->country = $country;
    }
    public function setPostCode($postCode): void {
        $this->postCode = $postCode;
    }

    public function getLocationId() {
        return $this->locationId;
    }


}
