<?php
// card-response.php
define('DIRECTPAY_SECRET', 'aee0c8db6ab7b09e9b10c7b21fedd61bd4b0307dd79f0e766626de9483271083'); // <<-- set your secret here
$logFile = __DIR__ . "/incoming_data2.txt";

$timestamp = date("Y-m-d H:i:s");
$rawInput = file_get_contents("php://input");

$data = [
    "GET"  => $_GET,
    "POST" => $_POST,
    "RAW"  => $rawInput
];

// Basic log header
$entry  = "============================\n";
$entry .= $_GET['jobid'];
$entry .= "Date: $timestamp\n";
$entry .= "============================\n";
$entry .= "REQUEST DUMP:\n";
$entry .= print_r($data, true);
$entry .= "\n";

// Try to verify and decode DirectPay POST payload (if any)
$extracted = [
    'verified' => false,
    'reason' => '',
    'walletId' => null,
    'card' => null,
];

$authHeader = null;
// Grab Authorization header in a robust way
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
} elseif (function_exists('getallheaders')) {
    $headers = getallheaders();
    if (!empty($headers['Authorization'])) $authHeader = $headers['Authorization'];
    if (!empty($headers['authorization'])) $authHeader = $headers['authorization'];
}

if ($rawInput !== '') {
    if (!$authHeader) {
        $extracted['reason'] = 'No Authorization header present';
    } else {
        // Authorization expected format: "hmac <hash>"
        $parts = explode(' ', $authHeader, 2);
        if (count($parts) !== 2) {
            $extracted['reason'] = 'Malformed Authorization header';
        } else {
            $receivedHash = $parts[1];
            $generated = hash_hmac('sha256', $rawInput, DIRECTPAY_SECRET);
            if (!hash_equals($generated, $receivedHash)) {
                $extracted['reason'] = 'Signature mismatch';
            } else {
                // Verified — decode base64 body
                $decoded = base64_decode($rawInput, true);
                if ($decoded === false) {
                    $extracted['reason'] = 'Base64 decode failed';
                } else {
                    $payload = json_decode($decoded, true);
                    if ($payload === null) {
                        $extracted['reason'] = 'JSON decode failed';
                    } else {
                        // Mark verified and extract fields if present
                        $extracted['verified'] = true;
                        $extracted['reason'] = 'OK';
                        // Common fields from DirectPay doc:
                        $extracted['walletId'] = $payload['walletId'] ?? ($payload['wallet_id'] ?? null);
                        // Card may be inside 'card' key
                        $extracted['card'] = $payload['card'] ?? null;
                        // Some docs use card.id or card_id, try both
                        if (!$extracted['card'] && isset($payload['card_id'])) { 
                            $extracted['card'] = ['id' => $payload['card_id']]; 
                        }
                        
                        
                        $extracted['transaction'] = $_GET['jobid'] ?? null; 
                        
                        
                        // card process ok // pass to .net endpoint
                        
                        $endpoint = 'http://merchant.bnpl.hexdive.com/api/OnboardCard';
                        $jdata['walletId']= $payload['card']['walletId'];
                        $jdata['cardId']= $payload['card']['id'];
                        $jdata['CardNumber']= $payload['card']['number'];
                        $jdata['jobid']= $_GET['jobid'];
                        $jdata['brand']= $payload['card']['brand'];
                        $jdata['year']= $payload['card']['expiry']['year'];
                        $jdata['month']= $payload['card']['expiry']['month'];
                        $ar=array(
                            "payload"=>$jdata,
                            "functionName"=>"OnboardCard",
                            "reference"=>"card onboarding"
                        
                        
                        );
                        
                        $json = json_encode($ar);

                        // init
                        $ch = curl_init($endpoint);
                        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                            'Content-Type: application/json',
                            'Content-Length: ' . strlen($json),
                            // 'Authorization: Bearer YOUR_TOKEN_HERE' // uncomment if needed
                        ]);
                        
                        // execute
                        $response = curl_exec($ch);
                        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                        $curlErr = curl_error($ch);
                        curl_close($ch);
                        
                    }
                }
            }
        }
    }
} else {
    $extracted['reason'] = 'Empty raw body (no server-to-server POST)';
}

// Append extraction to log
$entry .= "DIRECTPAY PARSE:\n";
$entry .= print_r($json, true);
$entry .= "\n\n";

file_put_contents($logFile, $entry, FILE_APPEND | LOCK_EX);

// Optional: respond to DirectPay to acknowledge callback
// Keep response minimal. 200 OK is usually enough.
header('Content-Type: application/json');
echo json_encode(['ok' => true, 'received' => $extracted['verified'] ? 'verified' : 'no_payload', 'reason' => $extracted['reason']]);
