<?php
header('Content-Type: application/json');
require_once 'production_config.php';

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

$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);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

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

$pp = json_decode($res, true) ?: [];
$status = $pp['data']['state'] ?? 'PENDING'; // SUCCESS, FAILED, PENDING

echo json_encode([
  'ok'=>true,
  'status'=>$status,
  'gateway_response'=>$pp,
  'merchantTransactionId'=>$txnId
], JSON_UNESCAPED_SLASHES);
?>
