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

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 RETREIVE_ORDER_URL = 'https://uat1.billdesk.com/u2/payments/ve1_2/transactions/get';

// Setup keys and identifiers
$clientId   = 'bduat2k526';
$keyId      = 'apLkPDnO9NYf';
$sharedKey  = 'xzYsZwfLeMDYzIweWT8i90QIWymCBXSn'; // 32-byte raw

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


// 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() ])
);

if (isset($_GET['orderid'])) {
    $orders_in_pending = mysqli_query($conn,"SELECT * FROM sales_orders WHERE status = 0 and orderid = '".$_GET['orderid']."'");
}
else {
    $orders_in_pending = mysqli_query($conn,"SELECT * FROM sales_orders WHERE status = 0");
}
while ($row = mysqli_fetch_assoc($orders_in_pending)) {
    
    $orderId = $row['orderid'];
    
    echo $orderId;
    
    $payload = json_encode([
        'mercid'     => 'BDUAT2K526',
        'orderid'    => $orderId,
    ]);
    
    $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("RlKxmMPu6RB1BGaLKGxnnPXon8ynoSKh"),
        'kid' => $keyId,
    ]);
    
    $jws = $jwsBuilder
        ->create()
        ->withPayload($encryptedPayload)
        ->addSignature($signingKey,[
            'alg'      => 'HS256',
            'kid'      => $keyId,
            'clientid' => $clientId,
        ])
        ->build();
    
    $signedEncryptedToken = (new JWSCompactSerializer())->serialize($jws);
    
    
    $ch = curl_init(RETREIVE_ORDER_URL);
    $traceid   = bin2hex(random_bytes(16));
    $timestamp = time();
    $sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('BD-Traceid: $traceid, BD-Timestamp: $timestamp','$signedEncryptedToken','retreive_transaction_api_request_string')");   

    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);
    
    echo "</br>";
    echo "Encrypted response: ".$encryptedResponse;
    $sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('BD-Traceid: $traceid, BD-Timestamp: $timestamp','$encryptedResponse','retreive_transaction_api_response_string')");   

    // Response Decryption 
    
    // 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
    if (isset($data['auth_status'])) {
    $auth_status = $data['auth_status'];
    
    if (isset($auth_status)) {
        if ($auth_status == 300) {
            $orderstatus = 1;
        }
        else if ($auth_status == 2) {
            $orderstatus = 0;
        }
        else if ($orderstatus == 399) {
            $orderstatus = 2;
        }
    }
    if (isset($data['payment_category'])) {
        $orderstatus." and payment_cat = ".$data['payment_category'];
    }
    
    $sql=mysqli_query($conn,"UPDATE sales_orders SET status = $orderstatus WHERE orderid = '$orderId'");
    if($sql) {
    }
    else {
    }
    }
}
?>