<?php
/**
 * BillDesk Payment Return Handler
 * Handles payment response and validates transaction
 * Manual JWE/JWS implementation for PHP 8.0 compatibility
 */

include 'db.php';
require 'vendor/autoload.php';

// Configuration (Must match index.php)
$useUAT = true;

if ($useUAT) {
    // UAT (Test) Environment
    define('CREATE_ORDER_URL', 'https://uat1.billdesk.com/u2/payments/ve1_2/orders/create');
    define('PAYMENT_FORM_URL', 'https://uat1.billdesk.com/u2/web/v1_2/embeddedsdk');
    $merchantId = 'BDUAT2K526';
    $clientId   = 'bduat2k526';
    $keyId      = 'apLkPDnO9NYf';
    $sharedKey  = 'xzYsZwfLeMDYzIweWT8i90QIWymCBXSn'; // 32-byte raw key for encryption
    $signingKey = 'RlKxmMPu6RB1BGaLKGxnnPXon8ynoSKh'; // 32-byte raw key for signing
} else {
    // Production Environment
    define('CREATE_ORDER_URL', 'https://api.billdesk.com/payments/ve1_2/orders/create');
    define('PAYMENT_FORM_URL', 'https://api.billdesk.com/web/v1_2/embeddedsdk');
    $merchantId = 'SHAKUNIYA';
    $clientId   = 'shakuniyasj';
    $keyId      = 'l6SVGjSf5Gun';
    $sharedKey  = '17mAMIqwOBvS9YIQEzeP7VStbgvXUuWK'; // 32-byte raw key for encryption
    $signingKey = 'z1XIAONLs2YecHz1CYiVlysiJzVzT6h8'; // 32-byte raw key for signing
}

// Helper functions
function base64url_decode($data) {
    $padded = $data . str_repeat('=', (4 - strlen($data) % 4) % 4);
    return base64_decode(strtr($padded, '-_', '+/'));
}

function verifyJWS(string $jws, string $key): string {
    $parts = explode('.', $jws);
    if (count($parts) !== 3) {
        throw new Exception('Invalid JWS format');
    }
    
    list($headerB64, $payloadB64, $signatureB64) = $parts;
    
    // Verify signature
    $signingInput = $headerB64 . '.' . $payloadB64;
    $signature = base64url_decode($signatureB64);
    $expectedSignature = hash_hmac('sha256', $signingInput, $key, true);
    
    if (!hash_equals($expectedSignature, $signature)) {
        throw new Exception('Invalid JWS signature');
    }
    
    return base64url_decode($payloadB64);
}

function decryptJWE(string $jwe, string $key): string {
    $parts = explode('.', $jwe);
    if (count($parts) !== 5) {
        throw new Exception('Invalid JWE format');
    }
    
    list($protectedHeader, $encryptedKeyB64, $ivB64, $ciphertextB64, $tagB64) = $parts;
    
    // Decode components
    $iv = base64url_decode($ivB64);
    $ciphertext = base64url_decode($ciphertextB64);
    $tag = base64url_decode($tagB64);
    
    // AAD is the protected header
    $aad = $protectedHeader;
    
    // Decrypt using AES-256-GCM
    $plaintext = openssl_decrypt(
        $ciphertext,
        'aes-256-gcm',
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag,
        $aad
    );
    
    if ($plaintext === false) {
        throw new Exception('JWE decryption failed: ' . openssl_error_string());
    }

    // Check for compression
    $headerJson = base64url_decode($protectedHeader);
    $header = json_decode($headerJson, true);
    
    if (isset($header['zip']) && $header['zip'] === 'DEF') {
        $plaintext = gzinflate($plaintext);
        if ($plaintext === false) {
            throw new Exception('Decompression failed');
        }
    }
    
    return $plaintext;
}

$orderid = $_GET['orderid'] ?? null;

// Check if orderid is provided in URL (status check)
if ($orderid) {
    // Just display status for existing order
    $stmt = $conn->prepare("SELECT status, product_id, name, email, amount FROM sales_orders WHERE orderid = ?");
    $stmt->bind_param('s', $orderid);
    $stmt->execute();
    $stmt->bind_result($status, $productId, $customerName, $email, $amount);
    
    if (!$stmt->fetch()) {
        echo '<h1>No record found for this order.</h1>';
        exit;
    }
    $stmt->close();
} else {
    // Process transaction response from BillDesk
    $encryptedResponse = $_POST['transaction_response'] ?? null;
    
    if (!$encryptedResponse) {
        die('No transaction response received');
    }
    
    try {
        // Step 1: Verify JWS signature
        $jweString = verifyJWS($encryptedResponse, $signingKey);
        
        // Step 2: Decrypt JWE payload
        $jsonPayload = decryptJWE($jweString, $sharedKey);
        
        // Get decrypted data
        $data = json_decode($jsonPayload, true);
        if (!$data) {
            throw new Exception('Invalid JSON payload');
        }
        
        $orderid = $data['orderid'] ?? null;
        if (!$orderid) {
             // Fallback if orderid is not in top level
             $orderid = $data['bdorderid'] ?? null;
        }
        
        // Log the response
        $encryptedResponseEscaped = mysqli_real_escape_string($conn, $encryptedResponse);
        mysqli_query($conn, "INSERT INTO billdesk_api_log (identifier, data, type) 
                             VALUES ('$orderid', '$encryptedResponseEscaped', 'payment_response_string')");
        
        // Determine transaction status
        $transactionStatus = 0; // Failed by default
        if (isset($data['transaction_error_code']) && $data['transaction_error_code'] === 'TRS0000') {
            $transactionStatus = 1; // Success
        } else if (isset($data['auth_status']) && $data['auth_status'] === '0300') {
             $transactionStatus = 1; // Success
        }
        
        // Update order status
        mysqli_query($conn, "UPDATE sales_orders SET status = $transactionStatus WHERE orderid = '$orderid'");
        
        // Get order details for display
        $stmt = $conn->prepare("SELECT status, product_id, name, email, amount FROM sales_orders WHERE orderid = ?");
        $stmt->bind_param('s', $orderid);
        $stmt->execute();
        $stmt->bind_result($status, $productId, $customerName, $email, $amount);
        $stmt->fetch();
        $stmt->close();
        
    } catch (Exception $e) {
        echo '<h1>Error Processing Payment Response</h1>';
        echo '<p>' . htmlspecialchars($e->getMessage()) . '</p>';
        exit;
    }
}

// Product catalog (example)
$products = [
    ['name' => 'Basic Plan', 'price_usd' => 100],
    ['name' => 'Premium Plan', 'price_usd' => 500],
    ['name' => 'Enterprise Plan', 'price_usd' => 1000],
];
$product = $products[$productId - 1] ?? $products[0];

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Status</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            width: 100%;
        }
        .receipt {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        .status-badge {
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            font-size: 1.5rem;
            font-weight: bold;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 2px solid #c3e6cb;
        }
        .failed {
            background: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
        }
        .pending {
            background: #fff3cd;
            color: #856404;
            border: 2px solid #ffeaa7;
        }
        .details {
            margin: 1.5rem 0;
        }
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #eee;
        }
        .detail-label {
            font-weight: 600;
            color: #555;
        }
        .detail-value {
            color: #333;
        }
        .total {
            font-size: 1.3rem;
            font-weight: bold;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 2px solid #333;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            margin-top: 1.5rem;
            text-align: center;
        }
        .btn:hover {
            background: #5568d3;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="receipt">
            <?php if ($status == 1): ?>
                <div class="status-badge success">
                    ✓ Payment Successful
                </div>
                <div class="details">
                    <div class="detail-row">
                        <span class="detail-label">Order ID:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($orderid); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Customer:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($customerName); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Email:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($email); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Product:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($product['name']); ?></span>
                    </div>
                    <div class="detail-row total">
                        <span class="detail-label">Amount Paid:</span>
                        <span class="detail-value">₹<?php echo htmlspecialchars($amount); ?></span>
                    </div>
                </div>
                <p style="text-align: center; color: #666;">
                    Thank you for your payment. A confirmation email has been sent to <?php echo htmlspecialchars($email); ?>.
                </p>
            <?php elseif ($status == 0): ?>
                <div class="status-badge failed">
                    ✗ Payment Failed
                </div>
                <div class="details">
                    <div class="detail-row">
                        <span class="detail-label">Order ID:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($orderid); ?></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Amount:</span>
                        <span class="detail-value">₹<?php echo htmlspecialchars($amount); ?></span>
                    </div>
                </div>
                <p style="text-align: center; color: #666;">
                    Your payment could not be processed. Please try again or contact support.
                </p>
                <div style="text-align: center;">
                    <a href="demo.php" class="btn">Try Again</a>
                </div>
            <?php else: ?>
                <div class="status-badge pending">
                    ⏳ Payment Pending
                </div>
                <div class="details">
                    <div class="detail-row">
                        <span class="detail-label">Order ID:</span>
                        <span class="detail-value"><?php echo htmlspecialchars($orderid); ?></span>
                    </div>
                </div>
                <p style="text-align: center; color: #666;">
                    Your payment is being processed. Please check back later.
                </p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
