<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set("Asia/Dhaka");

/* --- CONFIGURATION --- */
$appId      = "b31f7ee9b7980f9c515cfa921cfdec9b";
$appSecret  = "3ec5c9d95cd19ed940cfe7e8f4fc2f94";
$payoutUrl  = "https://bd.api.starpago.com/api/v2/payout/order/create";

// আপনার ফিক্সড ডাটা
$targetNumber = "01934425362";
$amount       = "100.00";
$method       = "BD_BKASH";
$accountName  = "Auto Withdraw"; // নাম এখানে দিতে পারেন
$orderNo      = "AUTO" . date("YmdHis") . rand(1000, 9999);

/* --- PREPARING PARAMS --- */
$params = [
    "appId"       => $appId,
    "merOrderNo"  => $orderNo,
    "currency"    => "BDT",
    "amount"      => $amount,
    "payMethod"   => $method,
    "notifyUrl"   => "https://elitegame20.vip/pay/devraj.php",
    "attach"      => "auto_payout_system",
    "extra"       => [
        "accountNo"   => $targetNumber,
        "accountName" => $accountName,
        "email"       => $targetNumber . "@elitegame20.vip",
        "mobile"      => $targetNumber
    ]
];

/* --- SIGNATURE GENERATION --- */
// সর্টিং এবং সাইন তৈরি করা (আপনার আগের কোডের লজিক অনুযায়ী)
$tempParams = $params;
ksort($tempParams);
$pairs = [];

foreach ($tempParams as $k => $v) {
    if ($k == "extra") {
        ksort($v);
        $ext = [];
        foreach ($v as $ek => $ev) {
            $ext[] = "$ek=$ev";
        }
        $pairs[] = "extra=" . implode("&", $ext);
    } else {
        $pairs[] = "$k=$v";
    }
}

$signString = implode("&", $pairs) . "&key=" . $appSecret;
$params['sign'] = hash("sha256", $signString);

/* --- API CALL (CURL) --- */
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $payoutUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($params),
    CURLOPT_HTTPHEADER     => ["Content-Type: application/json"],
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4
]);

$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

/* --- RESPONSE HANDLING --- */
header('Content-Type: application/json');

if ($err) {
    echo json_encode(["status" => "error", "message" => "CURL Error: " . $err]);
} else {
    $resData = json_decode($response, true);
    if (isset($resData['code']) && $resData['code'] == 0) {
        echo json_encode([
            "status"  => "success",
            "message" => "Withdraw request sent for 1000 BDT to " . $targetNumber,
            "data"    => $resData['data']
        ]);
    } else {
        echo json_encode([
            "status"  => "failed",
            "message" => "API Error",
            "details" => $resData
        ]);
    }
}
?>