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

if (!isset($zibal_merchant) || empty($zibal_merchant)) { die("مرچنت کد زیبال تنظیم نشده است."); }

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

if (!$user_id || $amount_toman < 1000) { die("مبلغ نامعتبر است."); }

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

$parameters = array(
    "merchant" => $zibal_merchant,
    "amount" => $amount_rial,
    "callbackUrl" => $callback_url,
    "description" => "شارژ حساب کاربری $user_id",
    "mobile" => "09123456789"
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://gateway.zibal.ir/v1/request");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if (isset($result['result']) && $result['result'] == 100) {
    $trackId = $result['trackId'];
    header("Location: https://gateway.zibal.ir/start/$trackId");
} else {
    echo "خطا در اتصال به زیبال: " . ($result['message'] ?? 'ناشناخته');
}
?>