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

if (!isset($merichentzarin) || empty($merichentzarin)) { die("پیکربندی درگاه پرداخت (مرچنت کد) یافت نشد."); }

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

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

$user_res = $connect->query("SELECT id FROM user WHERE id = '$user_id' LIMIT 1");
if ($user_res->num_rows == 0) { die("کاربر یافت نشد."); }

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

$data = array(
  "merchant_id" => $merichentzarin,
  "amount" => $amount_rial,
  "callback_url" => $callback_url,
  "description" => "شارژ حساب کاربری - ID: $user_id",
  "metadata" => ["user_id" => (string)$user_id]
);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($jsonData)));

$result = curl_exec($ch);
$err = curl_error($ch);
$result = json_decode($result, true);
curl_close($ch);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  if (empty($result['errors'])) {
    if ($result['data']['code'] == 100) {
      header('Location: https://www.zarinpal.com/pg/StartPay/' . $result['data']["authority"]);
    }
  } else {
    echo 'Error Code: ' . $result['errors']['code'];
    echo 'Message: ' . $result['errors']['message'];
  }
}
?>