<?php

use CodePunch\Base\Util as UTIL;

function get_dotdb_data($keyword, $apikey, $options = array()) {
    $callstatus = [
        'data' => [],
        'status' => '',
        'error' => '',
        'message' => ''
    ];

    $url = "https://api.dotdb.com/v2/search?keyword=" . urlencode($keyword);
    $headers = ['Authorization: Token ' . $apikey];

    $retv = UTIL::curl_get_url($url, 20, false, $headers);

    $callstatus['status'] = $retv['status'];

    if ($retv['status'] == 200) {
        $data = json_decode($retv['result'], true);
        if (is_array($data)) {
            $callstatus['data'] = $data;
        }
    } else {
        if (isset($retv['result'])) {
            $data = json_decode($retv['result'], true);
            if (isset($data['message'])) {
                $callstatus['message'] = $data['message'];
            }
        }
        $callstatus['error'] = $retv['error'] ?? $retv['status'];
    }

    return $callstatus;
}

function domain_name_only(string $domain): string {
    $domain = strtolower(trim($domain));
    $domain = preg_replace('#^[a-z]+://#i', '', $domain);
    $domain = preg_replace('#^www\.#i', '', $domain);
    $domain = explode('/', $domain, 2)[0];

    return explode('.', $domain, 2)[0];
}

function get_dotdb_counts($domain, $apikey, $prefix = "dotdb_") {
    $keyword = domain_name_only($domain);

    if (!$keyword) {
        return false;
    }

    $cv = get_dotdb_data($keyword, $apikey);

    if (!empty($cv['data']) && is_array($cv['data'])) {
        $d = $cv['data'];

        $out = [
            'domain'        => $domain,
            'keyword'       => $keyword,
            'total_suffix'  => $d['total_suffix'] ?? 0,
            'exact_matches' => $d['exact_match_total_suffix'] ?? 0,
            'total_name'    => $d['total_name'] ?? 0,
            'checked_at'    => date("Y-m-d H:i:s")
        ];

        if (!empty($prefix)) {
            $prefix = rtrim($prefix, '_') . '_';

            $prefixed = [
                'domain'  => $out['domain'],
                'keyword' => $out['keyword']
            ];

            foreach ($out as $k => $v) {
                if ($k === 'keyword' || $k === 'domain') {
                    continue;
                }
                $prefixed[$prefix . $k] = $v;
            }

            return $prefixed;
        }

        return $out;
    }

    return false;
}
