<?php
// working_phonepe_test.php - Using official PhonePe test credentials
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');

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

// Official PhonePe Test Credentials (These are publicly available)
$MERCHANT_ID = 'PGTESTPAYUAT';
$SALT_KEY    = '099eb0cd-02cf-4e2a-8aca-3e6c6aff8719';
$SALT_INDEX  = '1';
$PHONEPE_ORDER_API = 'https://api-preprod.phonepe.com/apis/pg-sandbox/pg/v1/pay';

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) { 
    http_response_code(400); 
    echo json_encode(['success'=>false,'message'=>'Invalid JSON']); 
    exit; 
}

$amount = isset($input['amount']) ? intval($input['amount']) : 0;
$merchantTxnId = isset($input['merchantTxnId']) ? $input['merchantTxnId'] : 'TXN_'.time();

if ($amount <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid amount']);
    exit;
}

$payload = [
    'merchantId' => $MERCHANT_ID,
    'merchantTransactionId' => $merchantTxnId,
    'merchantUserId' => 'USER_'.time(),
    'amount' => $amount,
    'callbackUrl' => isset($input['redirectUrl']) ? $input['redirectUrl'] : 'https://webhook.site/redirect-url',
    'mobileNumber' => isset($input['mobileNumber']) ? $input['mobileNumber'] : '9999999999',
    'paymentInstrument' => ['type' => 'PAY_PAGE']
];

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

// Signature generation as per PhonePe docs
$stringToSign = $base64Payload . "/pg/v1/pay" . $SALT_KEY;
$signature = hash('sha256', $stringToSign);
$xVerify = $signature . "###" . $SALT_INDEX;

$postBody = json_encode(['request' => $base64Payload]);

$ch = curl_init($PHONEPE_ORDER_API);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-VERIFY: ' . $xVerify,
    'X-MERCHANT-ID: ' . $MERCHANT_ID
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);

if ($response === false) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'cURL error: ' . $curlErr]);
    exit;
}

// Decode PhonePe response
$phonepeResp = json_decode($response, true);

// Extract payment URL from PhonePe response
$paymentUrl = $phonepeResp['data']['instrumentResponse']['redirectInfo']['url'] ?? null;

// Return response to client
if ($paymentUrl) {
    echo json_encode([
        'success' => true,
        'http_code' => $httpCode,
        'paymentUrl' => $paymentUrl,
        'phonepe_response' => $phonepeResp,
        'request_payload' => $payload,
    ]);
} else {
    echo json_encode([
        'success' => false,
        'http_code' => $httpCode,
        'message' => 'Payment URL missing from PhonePe response',
        'phonepe_response' => $phonepeResp,
        'request_payload' => $payload,
    ]);
}
?>
