<?php

// API thread handler
function api($target, $data, &$json) {
	$data['SERVER_NAME'] = $_SERVER['SERVER_NAME'];
    // TODO: Need to encrypt the data and the thread to avoid MITM-attack (man in the middle attack)
    $data_string = json_encode($data);
    $api = curl_init();

    // Create a connection to the API server, and will transmit the POST data thereto, as the API server handles everything related to the user (e.g. user registration & credit card gateway)
    $options = [
        CURLOPT_URL => API_URL ."/". $target,
        CURLOPT_USERPWD => API_AUTH_USERNAME .":". API_AUTH_PASSWORD,
        CURLOPT_HTTPHEADER => ['Content-Type:application/json', 'Content-Length: ' . strlen($data_string)],
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HEADER => true,
        CURLOPT_RETURNTRANSFER => true,
    ];

    curl_setopt_array($api, $options);

    $content = explode("\r\n\r\n", curl_exec($api));
	
//	var_dump(curl_error ( $api ));
	
	//var_dump($content);
    $json = json_decode(end($content), true);
    $httpCode = curl_getinfo($api, CURLINFO_HTTP_CODE);

    curl_close($api);

    return $httpCode == API_ACCEPT;
}

function getValue($name, $default = false)
{
    if (isset($_POST[$name])) {
        return $_POST[$name];
    }

    if ($default && isset($default[$name])) {
        return $default[$name];
    }

    return "";
}

function printMessages($name)
{
    printSuccess($name);
    printError($name);
}

function printError($name)
{
    global $error;

    if (count($error[$name]['form'])) {
        foreach ($error[$name]['form'] as $error_messages) {
            if (count($error_messages)) {
                echo "<div class=\"alert alert-danger\">".implode("<br>", $error_messages)."</div>";
            }
        }
    }
}

function printSuccess($name)
{
    global $success;

    if (count($success[$name])) {
        echo "<div class=\"alert alert-success\">".implode("<br>", $success[$name])."</div>";
    }
}
