<?php

use Exception;

class GermanMinerAPI
{

    private static $apiKey = '<API-Key>';

    
    /*
     * Utility-Functions
     */
    
    private static function validateUuid($uuid, $parameterName) {
        if (strlen(str_replace('-', '', $uuid)) != 32) {
            throw new Exception('API returned error: Ungültiger Parameter: ' . $parameterName);
        }
    }
    
    private static function validateGmlinkCode($code, $parameterName) {
        $split = explode('-', $code);
        if (strlen($code) != 11 || count($split) != 3 || !is_numeric($split[0]) ||  !is_numeric($split[1]) || !is_numeric($split[2]) || $split[0] != (($split[1] + $split[2]) % 1000)) {
            throw new Exception('API returned error: Ungültiger Parameter: ' . $parameterName . ' (Der GMLink-Code ist ungültig)');
        }
    }
    
    private static function validateAccountNumber($accountNumber, $parameterName) {
        if (strlen($accountNumber) != 11 || substr(strtoupper($accountNumber), 0, 3) !== 'DEF') {
            throw new Exception('API returned error: Ungültiger Parameter: uuid' . $parameterName);
        }
    }
    
    private static function fetchJson($path, $parameters = null)
    {
        $output = static::fetch($path, $parameters);

        if (!empty($output)) {
            $json = static::parseJson($output);
            if (is_array($json) && isset($json['success'])) {

                if (!$json['success']) {
                    throw new Exception('API returned error: ' . $json['error']);
                }

                return isset($json['data']) ? $json['data'] : true;
            } else {
                throw new Exception('API returned invalid JSON.');
            }
        }

        throw new Exception('API returned nothing.');
    }

    private static function parseJson(string $json)
    {
        $data = json_decode($json, true);
        return empty($data) ? false : $data;
    }

    private static function fetch($path, $parameters = null) {
        return self::getData('https://api.germanminer.de/v2/' . $path . '?key=' . self::$apiKey . '&' .  ($parameters == null ? '' : http_build_query($parameters)));
    }

    private static function getData($url) {
        if (function_exists('curl_init') and extension_loaded('curl')) {
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

            $output = curl_exec($ch);
            curl_close($ch);

            return $output;
        } else {
            return @file_get_contents($url);
        }
    }
}