<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { 
    http_response_code(200); 
    exit(); 
}

$txnId = $_GET['merchantTransactionId'] ?? '';
if(!$txnId){ 
    http_response_code(400); 
    echo json_encode(['ok'=>false,'error'=>'merchantTransactionId required']); 
    exit; 
}

// X-VERIFY for status: sha256("/pg/v1/status/{merchantId}/{txnId}" + saltKey) + "###" + saltIndex
$path = '/pg/v1/status/' . PP_MERCHANT_ID . '/' . $txnId;
$checksum = hash('sha256', $path . PP_SALT_KEY);
$xVerify  = $checksum . '###' . PP_SALT_INDEX;

$ch = curl_init(PP_BASE_URL . $path);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER     => [
    'Content-Type: application/json',
    'X-VERIFY: ' . $xVerify,
    'X-MERCHANT-ID: ' . PP_MERCHANT_ID
  ],
  CURLOPT_TIMEOUT        => 20
]);
$res = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if($err){ 
    http_response_code(500); 
    echo json_encode(['ok'=>false,'error'=>$err]); 
    exit; 
}

$resp = json_decode($res, true);
// map PG response to a simple status
$status = $resp['data']['state'] ?? 'PENDING'; // e.g. SUCCESS, FAILED, PENDING
echo json_encode(['ok'=>true,'status'=>$status,'raw'=>$resp]);
?>
