<?php
require_once 'Config.php';
require_once 'Crypt/RSA.php';
require_once 'RequestObject.php';
require_once 'ResponseObject.php';
require_once 'BizLayer.php';

//Get a hold of all configuration variables.
$config = new Config();

//Encrypted post data should be contained in $_POST['req']
/**
 * @return decrypted request. 
 */
function DecryptRequest($rawRequest)
{
    global $config;
    
    if($config->IsConnectionEncryptionEnabled())
    {
        $rsa = new Crypt_RSA();

        ////Use the following lines to create a new key pair and write it to a file.
        //extract($rsa->createKey());
        //$filename = "keys_newpair.txt";
        //$filehandle = fopen($filename, "w+b");
        //fwrite($filehandle, $privatekey."|||||".$publickey);
        //fclose($filehandle);
        /* 
         * Use config::receive_privateKey to decrypt data received from client
         * Use config::send_publicKey to encrypt data before sending it to client.
         */
    //    if(!$rsa->loadKey($config->GetRequestPublicKey()))
    //        echo "<p>Loading pub key failed.</p>";
    //    $plaintext = "Che chak zuv myon";
    //    $encryptedText = $rsa->encrypt($plaintext);
    //    echo "<p><strong>Encrypted text:</strong><br/>$encryptedText</p>";

        //decrypted text
        if(!$rsa->loadKey($config->GetRequestPrivateKey()))
        {
            //send a json encoded error message if loading client's pub key failed.
            $e =  new ErrorObject($responseData, E_VROOM_LOAD_RECV_PRI_KEY_FAILED);
            exit();//no need to continue processing once the error has been sent.
        }
        $decryptedText = $rsa->decrypt($rawRequest);
    }
    else
        $decryptedText = $rawRequest;
    //json decoding
    $request_array = json_decode($decryptedText, true);
    //Store the request
    $request = new RequestObject(
                                 $request_array['requestHash'], 
                                 $request_array['call'], 
                                 $request_array['paramArray']
                                );
    return $request;
}


/*send it back to requester.*/
function SendResponse($responseData)
{
    global $config;
    //json_encode will encode only public variables of the class.
    $responseJson = json_encode($responseData);
    
    if(!$config->IsConnectionEncryptionEnabled())
    {
        echo $responseJson;
        return;
    }
    
    $rsa = new Crypt_RSA();
    //encrypt response
    if(!$rsa->loadKey($config->GetResponsePublicKey()))
    {
        //send a json encoded error message if loading client's pub key failed.
        $e =  new ErrorObject($responseData, E_VROOM_LOAD_SEND_PUB_KEY_FAILED);
        exit();//no need to continue processing once the error has been sent.
    }
    
    echo $rsa->encrypt($responseJson);
}

function GetResponse($requestData)
{
    $biz = new BizLayer($requestData);
    return $biz->CallFunction();
}

$rawRequest = file_get_contents("php://input");
if($rawRequest == null)
        return;
if($config->IsLoggingRequestsEnabled())
{
    $filename = "requests.txt";
    $filehandle = fopen($filename, "a+b");
    fwrite($filehandle, date('d F Y h:i:s A', time()). chr(13).$rawRequest.chr(13).'-------------'.chr(13).chr(13));
    fclose($filehandle);
}
SendResponse(GetResponse(DecryptRequest($rawRequest)));

?>