<?php
# Required File Includes
include '../../../init.php';
include '../../../includes/functions.php';
include '../../../includes/gatewayfunctions.php';
include '../../../includes/invoicefunctions.php';
require_once '../litepay/lib/MerchantClient/MerchantClient.php';

$gatewaymodule = "litepay";
$GATEWAY = getGatewayVariables($gatewaymodule);
$secretID = $GATEWAY['secretID'];
$vendorID = $GATEWAY['vendorID'];
$merchantApiUrl = 'https://litepay.ch/p/';

if (!$GATEWAY["type"]) {
	logTransaction($GATEWAY["name"], $_POST, 'Not activated');
	error_log('LitePay module not activated');
	exit("LitePay module not activated");
}

function convertToBTCFromSatoshi($value) {
    $BTC = $value / 100000000;
    return $BTC;
}
function convertToSatoshiFromBTC($value) {
    $BTC = $value * 100000000;
    return $BTC;
}
function formatBTC($value) {
    $value = sprintf('%.8f', $value);
    $value = rtrim($value, '0');
    return $value;
}

$request = $_REQUEST;

$client = new MerchantClient($merchantApiUrl, $secretID, $vendorID);
$callback = $client->parseCreateOrderCallback($request);

if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
	if ($callback != null){
		
		if (!isset($_GET['invoice_id'])) {
			error_log('Error. invoice_id is not provided');
			exit('Error. invoice_id is not provided');
		}

                $invoiceId = intval($_GET['invoice_id']);
                
                $get_invoice = localAPI('GetInvoice',['invoiceid' => $invoiceId]);
                $price = $get_invoice['total'];
                
		
                    if ($callback->secretID() == $secretID && $get_invoice['status'] != "Paid") {
                        $transId = $vendorID."-".$invoiceId;
                        checkCbTransID($transId);
                        $note = "Received payment of ". formatBTC(convertToBTCFromSatoshi($callback->value())) ." ".$callback->coin()." trough address ". $callback->input_address() ." to ". $callback->destination_address() . " TxID: ". $callback->transaction_hash() ." , current confirmations: ". $callback->confirmations() ." for invoiceID: ".$callback->invoiceID();
                        localAPI('UpdateInvoice', ['invoiceid' => $callback->invoiceID(), 'notes' => 'Invoice Paid through LitePay.ch PayGate']);
                        addInvoicePayment($invoiceId, $transId, $price, '0', $gatewaymodule);
                        logActivity($note);
                        echo '*ok*';	
                    } elseif ($callback->secretID() == $secretID && $get_invoice['status'] == "Paid") {
                        echo '*ok*';
                    }
		

	} else {
		error_log('Error. Invalid callback');
		exit('Error. Invalid callback');
	}
} else {
	header('Location: /');
}
