<?php

$settings = HSettings::getBasicSettings();

class WhoisService
{
    private $site;
    private $apiResponse;
    private $settings;

    private $whoisData = [
        'created_date'              => 0,
        'updated_date'              => 0,
        'expired_date'              => 0,
        'registrar_name'            => '',
        'isp_name'                  => '',
        'server_ip_address'         => '',
        'server_country_name'       => '',
        'server_country_short_name' => '',
        'server_region'             => '',
        'server_city'               => '',
        'server_country_latitude'   => '',
        'server_country_longitude'  => '',
        'server_ns_records'         => []
    ];

    public function __construct($site)
    {
        $this->site = $site;

        $this->settings = LSetting::getSettings();
    }

    public function get()
    {
        if ($this->apiRequest()) {
            $this->fillData();
        }

        if ($this->whoisData['server_country_name'] == ''){
            $this->whoisData['server_country_name'] = 'Other';
        }

        if ($this->whoisData['server_country_short_name'] == ''){
            $this->whoisData['server_country_short_name'] = 'ot';
        }

        return $this->whoisData;
    }

    private function apiRequest()
    {

        $response = Unirest\Request::get("https://jsonwhois.com/api/v1/whois",

            array(
                "Accept" => "application/json",
                "Authorization" => "Token token=" . $this->settings->api_whois_key
            ),
            array(
                "domain" => $this->site
            )
        );

        if(isset($response->body)){
            $this->apiResponse = $response->body;
            return true;
        }
        return false;
    }

    private function ipLookup($ip)
    {
        $jsonData = file_get_contents('http://ip-api.com/json/' . $ip);

        if (!$jsonData) {
            return false;
        }

        $data = json_decode($jsonData, true);

        if (!$data) {
            return false;
        }

        if($data['status'] == 'success'){
            return $data;
        }

        return false;
    }

    private function fillData()
    {
        if (isset($this->apiResponse->created_on) && $this->apiResponse->created_on != '') {
            $this->whoisData['created_date'] = strtotime(str_replace('.', '-', $this->apiResponse->created_on));
        }
        if (isset($this->apiResponse->updated_on) && $this->apiResponse->updated_on != '') {
            $this->whoisData['updated_date'] = strtotime(str_replace('.', '-', $this->apiResponse->updated_on));
        }
        if (isset($this->apiResponse->expires_on) && $this->apiResponse->expires_on != '') {
            $this->whoisData['expired_date'] = strtotime(str_replace('.', '-', $this->apiResponse->expires_on));
        }

        if (isset($this->apiResponse->registrar->name) && $this->apiResponse->registrar->name != '') {
            $this->whoisData['registrar_name'] = $this->apiResponse->registrar->name;
        }

        $ip = gethostbyname($this->site);

        if (filter_var($ip, FILTER_VALIDATE_IP)) {
            $this->whoisData['server_ip_address'] = $ip;
            $ipData = $this->ipLookup($ip);

            if($ipData['isp'] != ''){
                $this->whoisData['isp_name'] = $ipData['isp'];
            }

            if($ipData['countryCode'] != ''){
                $this->whoisData['server_country_short_name'] = strtolower($ipData['countryCode']);
            }

            if($ipData['country'] != ''){
                $this->whoisData['server_country_name'] = $ipData['country'];
            }

            if($ipData['regionName'] != ''){
                $this->whoisData['server_region'] = $ipData['regionName'];
            }

            if($ipData['city'] != ''){
                $this->whoisData['server_city'] = $ipData['city'];
            }

            if($ipData['lat'] != ''){
                $this->whoisData['server_country_latitude'] = $ipData['lat'];
            }

            if($ipData['lon'] != ''){
                $this->whoisData['server_country_longitude'] = $ipData['lon'];
            }
        }

        if (isset($this->apiResponse->nameservers) && count($this->apiResponse->nameservers) > 0) {

            if(is_array($this->apiResponse->nameservers)){
                $nameservers = $this->apiResponse->nameservers;
            }else{
                $nameservers = [$this->apiResponse->nameservers];
            }

            foreach ($nameservers as $record) {
                if(! $this->isValidNameServer(trim($record->name)))
                    continue;

                $newNS = [
                    'ns'                 => trim(Str::lower($record->name)),
                    'ip_address'         => '',
                    'country'            => '',
                    'country_short_name' => ''
                ];

                if($record->ipv4 != ''){
                    $ip = $record->ipv4;
                }else{
                    $ip = trim(Str::lower($record->name));
                }

                if (filter_var($ip, FILTER_VALIDATE_IP)) {

                    $newNS['ip_address'] = $ip;

                    $ipData = $this->ipLookup($ip);

                    if($ipData['countryCode'] != ''){
                        $newNS['country_short_name'] = strtolower($ipData['countryCode']);
                    }

                    if($ipData['country'] != ''){
                        $newNS['country'] = $ipData['country'];
                    }
                }

                else if ($this->isValidNameServer($ip)){

                    $ipData = $this->ipLookup($ip);

                    if ($ipData['query'] != '' && filter_var($ipData['query'], FILTER_VALIDATE_IP)) {
                        $newNS['ip_address'] = $ipData['query'];
                    }

                    if($ipData['countryCode'] != ''){
                        $newNS['country_short_name'] = strtolower($ipData['countryCode']);
                    }

                    if($ipData['country'] != ''){
                        $newNS['country'] = $ipData['country'];
                    }
                }

                $this->whoisData['server_ns_records'][] = $newNS;
            }
        }
    }

    private function isValidNameServer($ns)
    {
        preg_match("/[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-]+\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})?/", $ns, $matched);
        if($matched)
            return true;
        return false;
    }



}