<?php
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;

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

// Define the file where you want to store the webhook data
$logFile = 'billdesk_webhook_log.txt';
$rawPostData = file_get_contents('php://input');
//echo $rawPostData;
// Log the raw data for debugging purposes
file_put_contents($logFile, "Raw Data Received:\n".date("Y-m-d H:i:s") . $rawPostData . "\n\n", FILE_APPEND);

    $encryptedResponse = $rawPostData;
    $sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('".date("Y-m-d H:i:s")."','$encryptedResponse','webhook_encoded_string')");   

    // Setup keys and identifiers
    $clientId   = 'bduat2k526';
    $keyId      = 'apLkPDnO9NYf';
    $sharedKey  = 'xzYsZwfLeMDYzIweWT8i90QIWymCBXSn'; // 32-byte raw
    
    $signingKey = new JWK([
        'kty' => 'oct',
        'k'   => base64url_encode("RlKxmMPu6RB1BGaLKGxnnPXon8ynoSKh"),
        'kid' => $keyId,
    ]);
    
    // Step 2: Create JWE
    $encryptionKey = new JWK([
        'kty' => 'oct',
        'k'   => base64url_encode($sharedKey),
        'kid' => $keyId,
    ]);
    // 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');
    }
    
    $decryptedResponse = $jwe->getPayload();
    // decode as associative array
    $data = json_decode($decryptedResponse, true);

    $orderid = $data['orderid'];
    $sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('$orderid','$decryptedResponse','webhook_decoded_string')");   
    
    $apiUrl = 'https://billapi.shakuniya.in/payment/create/update_statuses.php?orderid=' . urlencode($orderid);
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log('Curl error: ' . curl_error($ch));
    }
    curl_close($ch);

?>