<?php
// Make sure this runs before Base64UrlSafe is ever loaded:
include 'db.php';

require '/home/shakuniya/billapi.shakuniya.in/vendor/autoload.php';

use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\Util\StringUtil;
use Jose\Component\Encryption\Algorithm\ContentEncryption\A256GCM;
// ← Replace the interface import:
use Jose\Component\Encryption\Algorithm\KeyEncryption\Dir;
use Jose\Component\Encryption\Compression\CompressionMethodManager;
use Jose\Component\Encryption\Compression\Deflate;
use Jose\Component\Encryption\JWEBuilder;
use Jose\Component\Encryption\JWEDecrypter;
use Jose\Component\Encryption\Serializer\CompactSerializer as JWECompactSerializer;
use Jose\Component\Signature\Algorithm\HS256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\JWSVerifier;
use Jose\Component\Signature\Serializer\CompactSerializer as JWSCompactSerializer;

const CREATE_ORDER_URL = 'https://uat1.billdesk.com/u2/payments/ve1_2/orders/create';

$amount = isset($_GET['tramt']) ? $_GET['tramt'] : (isset($_POST['tramt']) ? $_POST['tramt'] : 0);
$name = isset($_GET['csname']) ? $_GET['csname'] : (isset($_POST['csname']) ? $_POST['csname'] : "");
$email = isset($_GET['csemail']) ? $_GET['csemail'] : (isset($_POST['csemail']) ? $_POST['csemail'] : "");
$number = isset($_GET['csnumber']) ? $_GET['csnumber'] : (isset($_POST['csnumber']) ? $_POST['csnumber'] : "");
$address = isset($_GET['csaddress']) ? $_GET['csaddress'] : (isset($_POST['csaddress']) ? $_POST['csaddress'] : "");
$productid = isset($_GET['prodid']) ? $_GET['prodid'] : (isset($_POST['prodid']) ? $_POST['prodid'] : 0);

// Setup keys and identifiers
$clientId   = 'shakuniyasj';
$keyId      = 'l6SVGjSf5Gun';
$sharedKey  = '17mAMIqwOBvS9YIQEzeP7VStbgvXUuWK'; // 32-byte raw

function base64url_encode(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$orderId = 'ORD' . time();
$traceid   = bin2hex(random_bytes(16));
$timestamp = time();


$sql=mysqli_query($conn,"insert into sales_orders(name,email,number,address,product_id,orderid)values('$name','$email','$number','$address','$productid','$orderId')");   
//print_r($sql);exit;
if($sql)
{
    echo "done";
}
else
{
}

$payload = json_encode([
    'mercid'     => 'SHAKUNIYASJ',
    'orderid'    => $orderId,
    'amount'     => $amount.'.00',
    'order_date' => date('Y-m-d\TH:i:sP'),
    'currency'   => '356',
    'ru'         => 'https://billapi.shakuniya.in/payment/create/return.php',
    'itemcode'   => 'DIRECT',
    'additional_info' => [
        'additional_info1' => $name,
        'additional_info1' => $email,
        'additional_info1' => $productid,
    ],
    'device'     => [
        'init_channel'             => 'internet',
        'ip'                       => $_SERVER['REMOTE_ADDR'] ?? '',
        'user_agent'               => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'accept_header'            => $_SERVER['HTTP_ACCEPT'] ?? '',
    ],
]);

// Step 2: Create JWE
$encryptionKey = new JWK([
    'kty' => 'oct',
    'k'   => base64url_encode($sharedKey),
    'kid' => $keyId,
]);

$jweBuilder = new JWEBuilder(
    new AlgorithmManager([ new Dir() ]),     // ← use Dir, not DirectEncryption :contentReference[oaicite:0]{index=0}
    new AlgorithmManager([ new A256GCM() ]),
    new CompressionMethodManager([ new Deflate() ])
);

$jwe = $jweBuilder
    ->create()
    ->withPayload($payload)
    ->withSharedProtectedHeader([
        'alg'      => 'dir',
        'enc'      => 'A256GCM',
        'kid'      => $keyId,
        'clientid' => $clientId,
    ])
    ->addRecipient($encryptionKey)
    ->build();

$encryptedPayload = (new JWECompactSerializer())->serialize($jwe);

// Step 3: Sign the Encrypted Payload
$jwsBuilder = new JWSBuilder(
    new AlgorithmManager([ new HS256() ])
);

$signingKey = new JWK([
    'kty' => 'oct',
    'k'   => base64url_encode("z1XIAONLs2YecHz1CYiVlysiJzVzT6h8"),
    'kid' => $keyId,
]);

$jws = $jwsBuilder
    ->create()
    ->withPayload($encryptedPayload)
    ->addSignature($signingKey,[
        'alg'      => 'HS256',
        'kid'      => $keyId,
        'clientid' => $clientId,
    ])
    ->build();

$signedEncryptedToken = (new JWSCompactSerializer())->serialize($jws);

$sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('BD-Traceid: $traceid, BD-Timestamp: $timestamp','$signedEncryptedToken','create_api_request_string')");   


$ch = curl_init(CREATE_ORDER_URL);

echo "</br>";
echo "BD-Traceid: $traceid";
echo "</br>";
echo "BD-Timestamp: $timestamp";
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $signedEncryptedToken,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/jose',
        'Accept: application/jose',
        "BD-Traceid: $traceid",
        "BD-Timestamp: $timestamp"
    ],
]);

$encryptedResponse = curl_exec($ch);
if (curl_errno($ch)) {
    die('cURL Error: ' . curl_error($ch));
}
curl_close($ch);


// Response Decryption 
$sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('BD-Traceid: $traceid, BD-Timestamp: $timestamp','$encryptedResponse','create_api_response_string')");   

// Step 1: Verify JWS signature
$jwsSerializer = new JWSCompactSerializer();
$jws = $jwsSerializer->unserialize($encryptedResponse);

$verifier = new JWSVerifier(new AlgorithmManager([new HS256()]));

if (!$verifier->verifyWithKey($jws, $signingKey, 0)) {
    throw new \Exception('Invalid JWS signature');
}

$jweString = $jws->getPayload();

// Step 2: Decrypt JWE payload
$jweSerializer = new JWECompactSerializer();
$jwe = $jweSerializer->unserialize($jweString);

$jweDecrypter = new JWEDecrypter(
    new AlgorithmManager([new Dir()]),
    new AlgorithmManager([new A256GCM()]),
    new CompressionMethodManager([new Deflate()])
);

if (!$jweDecrypter->decryptUsingKey($jwe, $encryptionKey, 0)) {
    throw new \Exception('Unable to decrypt JWE');
}

// decode as associative array
$data = json_decode($jwe->getPayload(), true);

// directly grab the 2nd link’s rdata
$rdata = $data['links'][1]['parameters']['rdata'];
$bdorderid = $data['links'][1]['parameters']['bdorderid'];

$sql=mysqli_query($conn,"UPDATE sales_orders SET bdorderid = '$bdorderid', rdata = '$rdata' WHERE orderid = '$orderId'");
if($sql) {
}
?>
</head>
<body>
<form name="sdklaunch" id="sdklaunch"
action="https://uat1.billdesk.com/u2/web/v1_2/embeddedsdk" method="POST">
<input type="hidden" id="bdorderid" name="bdorderid" value="<?php echo $bdorderid; ?>">
<input type="hidden" id="merchantid" name="merchantid" value="BDUAT2K526">
<input type="hidden" id="rdata" name="rdata" value="<?php echo $rdata; ?>">
<input name='submitBtn' type='submit' value='Complete your Payment' />
</form>
<script>
     document.getElementById('sdklaunch').submit();


</script>
</body>
</html>