<?php
// payment_status.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), '+/', '-_'), '=');
}

// 1. Get parameters from GET request
$orderid  = isset($_POST['orderid'])  ? $_POST['orderid']  : null;

$inr_exchange_rate = 87;
$items = [
    ['name'=>'Live Streaming App', 'price_usd' => 1700, 'image'=>'https://www.shakuniya.in/products/live-streaming-apps/tiktok-clone-bg1.jpg'],
    ['name'=>'Audio Chat App', 'price_usd' => 750, 'image'=>'https://www.shakuniya.in/products/audio-streaming-app/mobile.ed99833.png'],
    ['name'=>'Social Media App', 'price_usd' => 560, 'image' => 'https://www.shakuniya.in/products/social-media-app/first.png'],
    ['name'=>'Shopping App', 'price_usd' => 300, 'image' => 'https://www.shakuniya.in/products/assets/ecommerce-images/ecommerce-banner.jpg'],
    ['name'=>'Gaming App', 'price_usd' => 1000, 'image' => 'https://images.pexels.com/photos/442576/pexels-photo-442576.jpeg?cs=srgb&dl=pexels-jeshootscom-442576.jpg&fm=jpg'],
];

if ($orderid) {
    // 2. Send API request to update statuses
    $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);
}
else {
    $encryptedResponse = $_POST['transaction_response'];

    // 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');
    }
    
    // decode as associative array
    $data = json_decode($jwe->getPayload(), true);
    
    $orderid = $data['orderid'];
    
    $sql=mysqli_query($conn,"INSERT INTO `billdesk_api_log`(`identifier`, `data`, `type`) VALUES ('$orderid','$encryptedResponse','payment_response_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);
}


// 3. Connect to database (update with your credentials)

// 4. Query sales_records for status, product_id, customer_name, email
$stmt = $conn->prepare(
    "SELECT status, product_id, name, email
     FROM sales_orders
     WHERE orderid = ?"
);
$stmt->bind_param('s', $orderid);
$stmt->execute();
$stmt->bind_result($status, $productId, $customerName, $email);

if (!$stmt->fetch()) {
    echo '<h1>No record found for this order.</h1>';
    exit;
}

$stmt->close();
$conn->close();

$item = $items[$productId-1];
$item['price_inr'] = floor($item['price_usd']*$inr_exchange_rate);
$item['price_tax'] = floor($item['price_inr']*0.18);

// 5. Display result based on status
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Payment Status</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 2em; }
        .container { max-width: 600px; margin: auto; text-align: center; }
        .success { color: green; }
        .failed  { color: red; }
        .pending { color: orange; }
        
    </style>
</head>
<body>
    <div class="container">
    <?php if ($status == 1): ?>
        <style>
  .receipt {
    max-width: 480px;
    margin: 2rem auto;
    padding: 2rem;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    font-family: -apple-system, BlinkMacSystemFont, “Segoe UI”, Roboto, Arial, sans-serif;
    color: #333;
    border-left: 4px solid #4CAF50;
  }

  .receipt .logo {
    display: block;
    margin: 0 auto 1.5rem;
    max-width: 120px;
  }

  .receipt h1.success {
    text-align: center;
    font-size: 1.75rem;
    margin-bottom: 1.5rem;
    color: #4CAF50;
  }

  .receipt h1.failure {
    text-align: center;
    font-size: 1.75rem;
    margin-bottom: 1.5rem;
    color: #f44336;
  }

  .receipt .details {
    display: grid;
    grid-template-columns: auto 1fr;
    row-gap: 0.75rem;
    column-gap: 1rem;
    margin-bottom: 1.5rem;
  }

  .receipt .details .label {
    font-weight: 600;
    text-align: justify;
  }

  .receipt .details .value {
    text-align: right;
    word-break: break-word;
  }

  .receipt .footer {
    text-align: center;
    font-size: 0. nine rem;
    color: #666;
    line-height: 1.4;
  }
</style>

<div class="receipt">
  <img src="https://shakuniya.in/abnweanewawe.png" alt="Your Logo" class="logo">
  <h1 class="success">Payment Successful!</h1>

  <div class="details">
    <div class="label">Payment Method:</div>
    <div class="value">Online</div>

    <div class="label">Order Id.:</div>
    <div class="value"><?= htmlspecialchars($data['orderid']); ?></div>

    <div class="label">Product:</div>
    <div class="value"><?php echo htmlspecialchars($item['name']); ?></div>

    <div class="label">Status:</div>
    <div class="value">Paid</div>

    <div class="label">Amount:</div>
    <div class="value"><?php echo number_format($item['price_inr'] + $item['price_tax'], 2); ?></div>

    <div class="label">Customer Name:</div>
    <div class="value"><?= htmlspecialchars($customerName); ?></div>

    <div class="label">Email:</div>
    <div class="value"><?= htmlspecialchars($email); ?></div>

    <div class="label">Transaction Time:</div>
    <div class="value"><?= htmlspecialchars($data['transaction_date']); ?></div>

    <div class="label">Reference No.:</div>
    <div class="value"><?= htmlspecialchars($data['transactionid']); ?></div>
  </div>

  <p class="footer">
    Thank you for shopping with us. Our team will get in touch with you soon for further processing.
  </p>
</div>
    <?php elseif ($status == 2): ?>
        <div class="receipt" style="border-left: 4px solid #f44336;">
  <img src="https://shakuniya.in/abnweanewawe.png" alt="Your Logo" class="logo">
  <h1 class="failure">Payment Failed!</h1>

  <div class="details">
    <div class="label">Payment Method:</div>
    <div class="value">Online</div>

    <div class="label">Product:</div>
    <div class="value"><?php echo htmlspecialchars($item['name']); ?></div>

    <div class="label">Status:</div>
    <div class="value"><?= htmlspecialchars($data['transaction_error_desc']); ?></div>

    <div class="label">Amount:</div>
    <div class="value"><?php echo number_format($item['price_inr'] + $item['price_tax'], 2); ?></div>

    <div class="label">Customer Name:</div>
    <div class="value"><?= htmlspecialchars($customerName); ?></div>

    <div class="label">Email:</div>
    <div class="value"><?= htmlspecialchars($email); ?></div>

    <div class="label">Transaction Time:</div>
    <div class="value"><?= htmlspecialchars($data['transaction_date']); ?></div>

    <div class="label">Reference No.:</div>
    <div class="value"><?= htmlspecialchars($data['transactionid']); ?></div>
  </div>

  <p class="footer">
    Unfortunately, your payment could not be processed. Please try again or contact our support team.
  </p>
</div>
    <?php else: ?>
        <h1 class="pending">Transaction Cancelled</h1>
        <p>Your transaction is cancelled. Please initiate a new transaction.</p>
    <?php endif; ?>
    </div>
</body>
</html>
