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

function out($arr, $code=200){ http_response_code($code); echo json_encode($arr); exit; }

try {
  $in = json_decode(file_get_contents('php://input'), true) ?: [];
  $amountRupees = (float)($in['amount'] ?? 0);
  $mobile       = trim((string)($in['mobile'] ?? ''));
  $userId       = trim((string)($in['userId'] ?? 'guest'));

  if ($amountRupees <= 0) out(['ok'=>false,'message'=>'amount required'], 400);

  $amountPaise   = (int)round($amountRupees * 100);
  $merchantTxnId = 'TXN' . (string)round(microtime(true) * 1000);

  // Build callback with txn id (both deep link and web fallback)
  $deepLinkCb = APP_DEEPLINK_BASE . '?mtid=' . urlencode($merchantTxnId);
  $webCb      = APP_WEB_CALLBACK   . '?mtid=' . urlencode($merchantTxnId);

  $payload = [
    'merchantId'            => PP_MERCHANT_ID,
    'merchantTransactionId' => $merchantTxnId,
    'merchantUserId'        => ($userId !== '' ? $userId : 'guest'),
    'amount'                => $amountPaise,
    // Prefer deep link. PhonePe sometimes prefers HTTPS URLs;
    // keep a fallback web callback in case.
    'callbackUrl'           => $deepLinkCb,
    'mobileNumber'          => $mobile,
    'paymentInstrument'     => ['type' => 'PAY_PAGE'],
    // (Optional) pass redirectMode if enabled on your account
    // 'redirectMode'          => 'POST',  // or 'REDIRECT'
    // 'redirectUrl'           => $webCb,
  ];

  $payloadJson   = json_encode($payload, JSON_UNESCAPED_SLASHES);
  $payloadBase64 = base64_encode($payloadJson);

  $path     = '/pg/v1/pay';
  $checksum = hash('sha256', $payloadBase64 . $path . PP_SALT_KEY);
  $xVerify  = $checksum . '###' . PP_SALT_INDEX;

  $ch = curl_init(PP_BASE_URL . $path);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
      'Content-Type: application/json',
      'X-VERIFY: ' . $xVerify,
      'X-MERCHANT-ID: ' . PP_MERCHANT_ID,
    ],
    CURLOPT_POSTFIELDS     => json_encode(['request' => $payloadBase64]),
    CURLOPT_TIMEOUT        => 30,
  ]);
  $res  = curl_exec($ch);
  $err  = curl_error($ch);
  $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);

  if ($err) out(['ok'=>false,'http_code'=>$code,'message'=>'curl error','error'=>$err], 500);

  $pp = json_decode($res, true);
  if (!is_array($pp) || ($pp['success'] ?? false) !== true) {
    out([
      'ok'=>false,
      'http_code'=>$code,
      'message'=>$pp['message'] ?? 'PhonePe API failed',
      'gateway_response'=>$pp,
      'request_payload'=>$payload
    ], 400);
  }

  $instrument  = $pp['data']['instrumentResponse'] ?? [];
  $intentUrl   = $instrument['intentUrl'] ?? null;
  $redirectUrl = $instrument['redirectInfo']['url'] ?? null;

  if (!$intentUrl && !$redirectUrl) {
    out(['ok'=>false,'http_code'=>$code,'message'=>'Payment URL missing','gateway_response'=>$pp], 400);
  }

  out([
    'ok' => true,
    'merchantTransactionId' => $merchantTxnId,
    'amount' => $amountPaise,
    'intentUrl' => $intentUrl,
    'redirectUrl' => $redirectUrl ?? $webCb,
  ], 200);

} catch (Throwable $e) {
  out(['ok'=>false,'message'=>$e->getMessage()], 500);
}
?>
