<?php

/**
 * Processor communcation handler
 * 
 * @category    Protocol
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

header('Content-type: application/json');

/**
 * The ATP IP Address
 */
define("HOST", "http://" . htmlentities($_SERVER["HTTP_HOST"] . ":8080"));

/**
 * Set timeout for ATP communication
 */
$ctx = stream_context_create(array(
    'http' => array(
        'protocol_version' => 1.1,
        'method' => 'GET',
        'header' => [
            'Accept: application/json',
            'Connection: close'
        ],
        'timeout' => 1
    ),
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false
    )
));

/**
 * Check if cURL is enabled
 * cURL is preferred over file_get_contents() if available
 */
$curl_enabled = in_array('curl', get_loaded_extensions());

/**
 * Turn all errors into exceptions so they can be caught in the try catch block
 */ 
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

/**
 * Handle Ajax requests
 */ 
try {

    if ( isset($_POST["action"]) ) {
        $action = htmlspecialchars($_POST["action"]);

        switch ($action) {

            case "queryProcessor":
            {
                $query = htmlentities($_POST["query"]);
                // At time of writing, processor does not correctly decode
                //$url = urlencode(HOST . "?" . $query);
                $url = HOST . "?" . str_replace(" ", "%20", $query);

                if ($curl_enabled)
                {
                    $ch = curl_init();

                    // Set cURL options
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    // Don't check peer certificate, we know it's us
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
                    // Response timeout
                    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Connection: close'));

                    $response = curl_exec($ch);
                    if (curl_errno($ch))
                    {
                        $error_msg = curl_error($ch);
                    }
                    curl_close($ch);

                    if (isset($error_msg))
                    {
                        throw new RuntimeException($error_msg, 1000);
                    }
                    else
                    {
                        echo json_encode(
                            array(
                                'status' => true,
                                'response' => $response
                            )
                        );
                    }
                }
                else
                {
                    $response = file_get_contents($url, false, $ctx);
                    if ($response)
                    {
                        echo json_encode(
                            array(
                                'status' => true,
                                'response' => $response
                            )
                        );
                    }
                    else
                    {
                        throw new Exception('file_get_contents() no response', 2002);
                    }
                }
                break;
            }

            default:
                throw new Exception('Invalid request', 2000);
                break;
        }
    }

} catch (Exception $e) {

    echo json_encode(
        array(
            'status' => false,
            'error' => $e->getMessage(),
            'error_code' => $e->getCode()
        )
    );

    exit;
}

restore_error_handler();

?>