<?php
// Replace with your actual merchant public key and API password
$merchantPublicKey = "Merchant Public Key";
$apiPassword = "API Password";

// Set the API endpoint URL
$url = "https://api.merchant.geidea.net/payment-intent/api/v2/direct/session";

// Retrieve the JSON string from the request body
$data = file_get_contents("php://input");

// Decode the JSON string into a PHP associative array
$data = json_decode($data, true);

// Access the values of the array
$orderAmount = $data["amount"];
$orderCurrency = $data["currency"];
$callbackUrl = $data["callbackUrl"];
$orderMerchantReferenceId = $data["merchantReferenceId"];
$language = $data["language"];
$date=new DateTime();
$timestamp = date_format($date,"Y/m/d H:i:s");

$signature = generateSignature($merchantPublicKey, $orderAmount, $orderCurrency, $orderMerchantReferenceId, $apiPassword, $timestamp);



// Set the request data
$data = array(
    'amount' => $orderAmount,
    'currency' => $orderCurrency,
    'merchantReferenceId' => $orderMerchantReferenceId,
    'timestamp' => $timestamp,
	'signature' => $signature
);

// Set the cURL options
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Authorization: Basic " . base64_encode("$merchantPublicKey:$apiPassword")
    ),
    CURLOPT_RETURNTRANSFER => true
);

// Initialize cURL
$ch = curl_init();

// Set cURL options
curl_setopt_array($ch, $options);

// Execute the cURL request
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    curl_close($ch);
    die("cURL Error: $error_msg");
}

// Close the cURL session
curl_close($ch);

// Decode the JSON response
$response_data = json_decode($response, true);

// Check for errors in the response
if ($response_data["responseCode"] !== "000" || $response_data["detailedResponseCode"] !== "000") {
    die("Error: " . $response_data["detailedResponseMessage"]);
}

// Get the session ID from the response
$session_id = $response_data["session"]["id"];

// Output the session ID
echo $session_id;

function generateSignature($merchantPublicKey, $orderAmount, $orderCurrency, $orderMerchantReferenceId, $apiPassword, $timestamp)
{
    $amountStr = number_format($orderAmount, 2, '.', '');
    $data = "{$merchantPublicKey}{$amountStr}{$orderCurrency}{$orderMerchantReferenceId}{$timestamp}";
    $hash = hash_hmac('sha256', $data, $apiPassword, true);
    return base64_encode($hash);
}

?>