<?php

namespace HwapX\Api\Controller;

use HwapX\Core\Library\DB\SQL\Mapper;

use HwapX\Api\Controller\AdminAuth;

class AdminApi extends AdminAuth {
    public function geoip($f3) {
        $ip   = $f3->get('PARAMS.ip');
        $hash = md5($ip);
        $key  = "api.geoip.$hash";

        if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
            die();//$this->json(null, 'IP inválido');

        $data = '';
        if(!$f3->exists($key, $data) || !$data) {
            $data = file_get_contents("https://www.maxmind.com/geoip/v2.1/city/$ip?use-downloadable-db=1&demo=1");

            if($json = @json_decode($data, true)) {
                $json['location']['latitude'] = str_replace(',', '.', $json['location']['latitude']);
                $json['location']['longitude'] = str_replace(',', '.', $json['location']['longitude']);
                $data = "Latitude: {$json['location']['latitude']}\nLongitude: {$json['location']['longitude']}";
            } else {
                $ch = curl_init("http://api.hackertarget.com/geoip/?q=$ip");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $data = curl_exec($ch);
                curl_close($ch);
            }

            $f3->set($key, $data, 60*60*24);
        }

        echo $data;
    }
}
