<?php

require_once dirname(__DIR__).'/config.php';

$config['debug'] = false;
//$config['debug'] = true;
if (array_key_exists('debug', $_GET)) {
    $config['debug'] = true;
}

$curl = curl_init();

curl_setopt_array($curl, array(
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_HTTPHEADER => array("Content-Type: application/json"),
      CURLOPT_CUSTOMREQUEST => "POST"));


function api_call($path, $data)
{
    global $curl;
    global $config;

    if ($config['debug']) {
        echo '<pre>API-Call: '.$config['api_url'].$path."\n";
        print_r($data);
        echo '</pre>';
    }

    $data['authtoken'] = $config['api_token'];
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_URL, $config['api_url'].$path.($config['debug'] ? '?debug' : ''));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    $ret = @json_decode($response, true);
    if ($config['debug'] && $ret) {
        echo '<pre>API response';
        print_r($ret);
        echo '</pre>';
    }
    if ($config['debug'] && (!isset($ret['status']) || $ret['status'] == 'error')) {
        echo '<pre>API-Error-Response:';
        echo $response;
        echo '</pre>';
    }
    return $ret;
}