<?php
include '../../../config.php';

if (!isset($payping_token) || empty($payping_token)) { die("توکن پی‌پینگ تنظیم نشده است."); }

$user_id = $_GET['id'] ?? null;
$amount_toman = (int)($_GET['amount'] ?? 0);


if (!$user_id || $amount_toman < 100) { die("مبلغ نامعتبر است (حداقل ۱۰۰ تومان)."); }

$callback_url = "$web/etc/pay/payping/back.php?amount=$amount_toman&id=$user_id";

$data = array(
    'amount' => $amount_toman,
    'returnUrl' => $callback_url,
    'description' => "شارژ حساب کاربر $user_id",
    'clientRefId' => (string)$user_id
);

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.payping.ir/v2/pay",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($data),
  CURLOPT_HTTPHEADER => array(
    "Accept: application/json",
    "Authorization: Bearer " . $payping_token,
    "Content-Type: application/json"
  ),
));

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

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  $result = json_decode($response, true);
  if (isset($result['code'])) {
      header("Location: https://api.payping.ir/v2/pay/gotoip/" . $result['code']);
  } else {

      echo "خطا در ایجاد تراکنش پی‌پینگ: <br>";
      print_r($result);
  }
}
?>