<?php
header('Content-Type: application/json');
session_start();

// Read input JSON
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['amount'], $input['payType'])) {
    echo json_encode(['error' => 'Invalid request']);
    http_response_code(400);
    exit;
}

$amount = (float)$input['amount']; // rupees
$payType = strtolower($input['payType']); // 'phonepe', 'paytm', 'bhim_upi'

// Fetch UPI IDs from files
$upi_file1 = 'admin/data/upi.txt';   // PhonePe
$upi_file2 = 'admin/data/upi2.txt';  // Paytm
$upi_file3 = 'admin/data/upi3.txt';  // BHIM / All

$upi1 = file_exists($upi_file1) ? trim(file_get_contents($upi_file1)) : 'Not Set';
$upi2 = file_exists($upi_file2) ? trim(file_get_contents($upi_file2)) : 'Not Set';
$upi3 = file_exists($upi_file3) ? trim(file_get_contents($upi_file3)) : 'Not Set';

// Assign correct UPI based on selected app
switch ($payType) {
    case 'phonepe':
        $upiAddress = $upi1;
        break;
    case 'paytm':
        $upiAddress = $upi2;
        break;
    case 'bhim_upi':
    default:
        $upiAddress = $upi3;
        break;
}

// Validate UPI and amount
if ($amount <= 0 || $upiAddress == 'Not Set') {
    echo json_encode(['error' => 'Invalid UPI or amount']);
    http_response_code(400);
    exit;
}

// Generate deep link based on selected app
switch ($payType) {
    case 'phonepe':
        // PhonePe expects amount in paisa
        $amountInPaisa = intval($amount * 100);

        $data = [
            "contact" => [
                "cbcName" => "",
                "nickName" => "",
                "vpa" => $upiAddress,
                "type" => "VPA"
            ],
            "p2pPaymentCheckoutParams" => [
                "note" => "Payment",
                "isByDefaultKnownContact" => true,
                "initialAmount" => $amountInPaisa,
                "currency" => "INR",
                "checkoutType" => "DEFAULT",
                "transactionContext" => "p2p"
            ]
        ];

        $jsonData = json_encode($data, JSON_UNESCAPED_SLASHES);
        $encoded = base64_encode($jsonData);
        $redirect_url = "phonepe://native?data={$encoded}&id=p2ppayment";
        break;

    case 'paytm':
        $tn = "s" . rand(100, 999); // random txn note
        // Exact format you provided
        $redirect_url = "paytmmp://cash_wallet?pa={$upiAddress}&am={$amount}&tn={$tn}&pn={$upiAddress}&cu=INR&mc=&cu=INR&url=&mode=&purpose=&orgid=&sign=&featuretype=money_transfer";
        break;

    case 'bhim_upi':
    default:
        // Universal UPI link for all apps
        $tr = 'cw' . rand(100000,999999);
        $redirect_url = "upi://pay?pa={$upiAddress}&pn=VPAY&tr={$tr}&am={$amount}&cu=INR&tn=Payment";
        break;
}

// Store payment in session (optional)
$payment_id = uniqid('pay_');
$_SESSION['payments'][$payment_id] = [
    'amount' => $amount,
    'payType' => $payType,
    'upi' => $upiAddress,
    'status' => 'pending'
];

// Return deep link
echo json_encode(['redirect_url' => $redirect_url]);
exit;
?>
