<?php
// create_payment.php

// Basic CORS - adjust for production: replace * with your exact domain
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);
if (!$input) {
    http_response_code(400);
    echo json_encode(['error'=>'invalid_json']);
    exit;
}

$amount = isset($input['amount']) ? trim($input['amount']) : null;
$payType = isset($input['payType']) ? trim($input['payType']) : null;
$upi = isset($input['upi']) ? trim($input['upi']) : null;
$min_amount = isset($input['min_amount']) ? trim($input['min_amount']) : null;
$max_amount = isset($input['max_amount']) ? trim($input['max_amount']) : null;

// Basic validation
if (!$amount || !$payType || !$upi) {
    http_response_code(400);
    echo json_encode(['error'=>'missing_parameters']);
    exit;
}

// Normalize numeric amounts
function to_float($v) {
    if ($v === null) return null;
    $v = preg_replace('/[^\d\.]/','',$v);
    if ($v === '') return null;
    return floatval($v);
}

$amtF = to_float($amount);
$minF = to_float($min_amount);
$maxF = to_float($max_amount);

// If min/max provided, enforce/clamp
if ($minF !== null && $amtF < $minF) {
    $amtF = $minF;
}
if ($maxF !== null && $amtF > $maxF) {
    $amtF = $maxF;
}
// Format back to string (no decimals if integer)
$amtStr = (floor($amtF) == $amtF) ? strval((int)$amtF) : number_format($amtF, 2, '.', '');

// helper functions
function genTid() {
    return 'cw' . round(microtime(true) * 1000) . bin2hex(random_bytes(5));
}
function genTransactionNote($payType) {
    if ($payType === 'paytm' || $payType === 'phonepe') {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $c = $chars[random_int(0, strlen($chars)-1)];
        return $c . random_int(100,999);
    }
    return '1' . bin2hex(random_bytes(2));
}

function buildRedirectUrl($payType, $upi, $amt, $tid, $tn) {
    if ($payType === 'gpay') {
        return "tez://upi/pay?pa=" . rawurlencode($upi) .
               "&pn=VPAY&mc=3526&tr={$tid}&am={$amt}&cu=INR&tn=" . rawurlencode($tn) .
               "&url=&mode=02&purpose=00&orgid=951";
    }

    if ($payType === 'phonepe') {
        $amountInPaise = (int) round(floatval($amt) * 100);
        $payload = [
            'contact' => ['cbsName' => '', 'nickName' => '', 'vpa' => $upi, 'type' => 'VPA'],
            'p2pPaymentCheckoutParams' => [
                'note' => $tn,
                'isByDefaultKnownContact' => true,
                'initialAmount' => $amountInPaise,
                'currency' => 'INR',
                'checkoutType' => 'DEFAULT',
                'transactionContext' => 'p2p'
            ]
        ];
        $encoded = base64_encode(json_encode($payload));
        // For safety use rawurlencode on the encoded chunk
        return "phonepe://native?data=" . rawurlencode($encoded) . "&id=p2ppayment";
    }

    if ($payType === 'paytm') {
        // paytm expects amount in rupees as string
        return "paytmmp://cash_wallet?pa=" . rawurlencode($upi) .
               "&am={$amt}&tn=" . rawurlencode($tn) . "&pn=" . rawurlencode($upi) .
               "&mc=&cu=INR&url=&mode=&purpose=&orgid=&sign=&featuretype=money_transfer";
    }

    // fallback generic UPI
    return "upi://pay?pa=" . rawurlencode($upi) .
           "&pn=VPAY&tr={$tid}&am={$amt}&cu=INR&tn=" . rawurlencode($tn);
}

// generate values
$tid = genTid();
$tn = genTransactionNote($payType);
$redirect = buildRedirectUrl($payType, $upi, $amtStr, $tid, $tn);

// sign payload as optional tamper-evidence (set HMAC_SECRET in env in production)
$hmac_secret = getenv('HMAC_SECRET') ?: 'replace_this_with_env_secret';
$expires = time() + 60; // seconds TTL
$payload_obj = ['redirect'=>$redirect,'tid'=>$tid,'exp'=>$expires];
$payload = base64_encode(json_encode($payload_obj));
$sig = hash_hmac('sha256', $payload, $hmac_secret);

// Optionally store $tid in DB with status 'created' to validate later

echo json_encode([
    'redirect_url' => $redirect,
    'payload' => $payload,
    'sig' => $sig,
    'expires' => $expires,
    'tid' => $tid,
    'amount' => $amtStr
]);
exit;
