<?php
require_once '../lib/nusoap.php';
require_once '../config.php';
include_once '../telegram.php';
$telegram = new telegram(TOKEN,HOST,USERNAME,PASSWORD,DBNAME);
$amount = intval($_GET['amount']);
if($amount < $min_wallet_charge) exit;
$userid = intval($_GET['userid']);
$result = $telegram->db->query("select * from fl_user WHERE userid='$userid'")->rowCount();
if($result == 0) exit;
$time = time();
$telegram->db->query("INSERT INTO `fl_wallet` VALUES (NULL, $amount, $userid, '','0', $time);");
$woid = $telegram->db->lastInsertId();

    $MerchantID = ZARINPALMID;  //Required
    $Amount = $amount - $zrfee; //Amount will be based on Toman  - Required
    $Description = DESC. " u$userid |w$woid";  // Required
    $Email = ''; // Optional
    $Mobile = ''; // Optional
    $CallbackURL = baseURI."/wallet/verify.php?woid=$woid";  // Required

    // Old SOAP method
    /*
    $client = new nusoap_client('https://www.zarinpal.com/pg/services/WebGate/wsdl', 'wsdl');
    $client->soap_defencoding = 'UTF-8';
    $result = $client->call('PaymentRequest', [
        [
            'MerchantID'     => $MerchantID,
            'Amount'         => $Amount,
            'Description'    => $Description,
            'Email'          => $Email,
            'Mobile'         => $Mobile,
            'CallbackURL'    => $CallbackURL,
        ],
    ]);
    */

    // New REST API v4 method 
    $data = [
        'merchant_id'  => $MerchantID,
        'amount'       => $Amount * 10, // REST API v4 requires amount in Rial (Toman * 10)
        'description'  => $Description,
        'callback_url' => $CallbackURL,
    ];
    
    $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, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $responseData = json_decode($response, true);
    
    if (isset($responseData['data']['code']) && $responseData['data']['code'] == 100) {
        $result = [
            'Status' => 100,
            'Authority' => $responseData['data']['authority']
        ];
    } else {
        $result = [
            'Status' => isset($responseData['errors']['code']) ? $responseData['errors']['code'] : -1,
            'Authority' => ''
        ];
    }

    //Redirect to URL You can do it also by creating a form
    if ($result['Status'] == 100) {
        header('Location: https://www.zarinpal.com/pg/StartPay/'.$result['Authority']);
    } else {
        echo'تراکنش با خطا مواجه شد';
    }
