<?php
// Input values
function generateRandom15DigitNumber() {
    return str_pad(mt_rand(1, 9) . mt_rand(0, 99999999999999), 15, '0', STR_PAD_RIGHT);
}

if(isset($_POST['submit'])) {



$merchantId = generateRandom15DigitNumber();

$data = [
    'addlParam1' => $_POST['address'],
    'addlParam2' => $_POST['city']." ".$_POST['state'],
    'amount' => $_POST['amount'],
    'currencyCode' => '356',
    'customerEmailID' => $_POST['email'],
    'customerMobileNo' => $_POST['mobile'],
    'customerName' => $_POST['name'],
    'merchantId' => 'T_03342',
    'merchantTxnNo' => $merchantId,
    'payType' => '0',
    'returnURL' => 'https://qa.phicommerce.com/pg/api/merchant',
    'transactionType' => 'SALE',
    'txnDate' => '202505171520'
];

// Secret key for hash generation
$secretKey = 'abc';

// Prepare secure hash string
 $hashInput = 
 $data['addlParam1'] .
  $data['addlParam2'] .
    $data['amount'] .
    $data['currencyCode'] .
    $data['customerEmailID'] .
    $data['customerMobileNo'] .
    $data['customerName'] .
    $data['merchantId'] .
    $data['merchantTxnNo'] .
    $data['payType'] .
    $data['returnURL'] .
    $data['transactionType'] .
    $data['txnDate'];

// Generate secure hash
function hmacDigest($hashInput, $keyString) {
    return hash_hmac('sha256', $hashInput, $keyString);
}

$data['secureHash'] = hmacDigest($hashInput, $secretKey);

// Encode data to JSON
$jsonData = json_encode($data);

// API endpoint
$url = 'https://qa.phicommerce.com/pg/api/v2/initiateSale';

// Initialize cURL
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

//print_r($response);
//die;
// Error handling
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
} else {
   // echo "HTTP Status: $httpCode\n";
    echo "Response:\n$response";
    $result = json_decode($response);
     $redirectURI = $result->redirectURI;
     $tranCtx = $result->tranCtx;
   
}


 $finalurl = $redirectURI."?tranCtx=".$tranCtx;
header("Location: $finalurl");
exit; // Important to stop script execution after redirection

// Close cURL
curl_close($ch);

}

?>
