<?php
require_once 'lib/nusoap.php';
require_once 'config.php';
require_once 'telegram.php';
$telegram = new telegram(TOKEN,HOST,USERNAME,PASSWORD,DBNAME);

$TokenCode = NOVINOPAY;

if(!isset($_GET['action'],$_GET['type'])) exit;


$action = $_GET['action'];
$type = $_GET['type'];
$callback_url = baseURI."/nvpayment.php?type=$type&action=verify";
$time = time();
if($type == 'renew'){
    if($action == 'pay'){
        $token = base64_decode($_GET['token']);
        $input = explode('#',$token); 
        $userid = intval($input[0]);
        $fid = intval($input[1]);
        $oid = intval($input[2]);
        $order = $telegram->db->query("select * from fl_order where id=$oid")->fetch(2);
        //$fid = $order['fileid'];
        $remark = $order['remark'];
        $server_id = $order['server_id'];
        $inbound_id = $order['inbound_id'];
        $respd = $telegram->db->query("select * from fl_file WHERE id='$fid' and active=1")->fetch(2);
        $name = $respd['title'];
        $days = $respd['days'];
        $volume = $respd['volume'];
        $price = $respd['price'];
        novino_payment($price, $TokenCode, base64_encode($token), $callback_url);
    }elseif($action == 'verify'){
        $token = base64_decode($_GET['InvoiceID']);
        if(!$token) exit;
        
        $input = explode('#',$token);
        $userid = intval($input[0]);
        $fid = intval($input[1]);
        $oid = intval($input[2]);
        $order = $telegram->db->query("select * from fl_order where id=$oid")->fetch(2);
        //$fid = $order['fileid'];
        $remark = $order['remark'];
        $server_id = $order['server_id'];
        $inbound_id = $order['inbound_id'];
        $expire_date = $order['expire_date'];
        $expire_date = ($expire_date > $time) ? $expire_date : $time;
        $respd = $telegram->db->query("select * from fl_file WHERE id='$fid' and active=1")->fetch(2);
        $name = $respd['title'];
        $days = $respd['days'];
        $volume = $respd['volume'];
        $price = $respd['price'];
        $time = time();

        $pay_result = novino_verify($price, $TokenCode); 
        if($pay_result == 'success'){

            require_once('vray.php');
            if($inbound_id > 0)
                $response = renew_client($server_id, $inbound_id, $remark, $volume, $days);
            else
                $response = renew_inbound($server_id, $remark, $volume, $days);
            if($response->success){
                $telegram->db->query("update fl_order set expire_date= $expire_date + $days * 86400,notif=0 where id='$oid'"); 
                $telegram->db->query("INSERT INTO `fl_extra_order` VALUES (NULL, '$userid', '$server_id', '$inbound_id', '$remark', '$price', '$time');");
                //echo 'تراکنش با موفقیت انجام شد';
                $msg = "✅ سفارش شما با موفقیت ثبت شد";
                $telegram->sendMessage($userid, $msg);
        $sndmsg = "
تمدید سرویس $remark با نوینو
قیمت : $price
آیدی کاربر : $userid
آیدی سرور : $server_id
تعداد روز  $days
تعداد گیگ $volume
";
		$telegram->sendMessage($sendchnl,$sndmsg);
		echo file_get_contents('html/success.html');
                $telegram->sendMessage($userid, "✅سرویس $remark با موفقیت تمدید شد");exit;
        
            }else {
                die("مشکل فنی در ارتباط با سرور. لطفا به مدیریت اطلاع بدید");
            }
        }
        
        
    }
}

if($type == 'day'){
    if($action == 'pay'){
        $token = base64_decode($_GET['token']);
        $input = explode('#',$token); 
        $server_id = intval($input[0]);
        $inbound_id = intval($input[1]);
        $remark = htmlspecialchars(strip_tags($input[2]));
        $planid = intval($input[3]);
        $userid = intval($input[4]); 
        $res = $telegram->db->query("select * from extra_day where id=$planid")->fetch(2);  
        $price = $res['price'];
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        $volume = $res['volume'];
        novino_payment($price, $TokenCode, base64_encode($token), $callback_url);
    }elseif($action == 'verify'){
        $token = base64_decode($_GET['InvoiceID']);
        if(!$token) exit;
        
        $input = explode('#',$token);
        $server_id = $input[0];
        $inbound_id = $input[1];
        $remark = $input[2];
        $planid = $input[3];
        $userid = $input[4];
        $res = $telegram->db->query("select * from extra_day where id=$planid")->fetch(2);  
        $volume = $res['volume'];
        $price = $res['price'];
        
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        
        $time = time();

        $pay_result = novino_verify($price, $TokenCode);
        if($pay_result == 'success'){
            
    
            require_once('vray.php');
            if($inbound_id > 0)
                $response = update_client_traffic($server_id, $inbound_id, $remark, 0, $volume);
            else
                $response = update_inbound_traffic($server_id, $remark, 0, $volume);
            if($response->success){
                $telegram->db->query("update fl_order set expire_date= expire_date + $volume * 86400,notif=0 where remark='$remark'");
                $telegram->db->query("INSERT INTO `fl_extra_order` VALUES (NULL, '$userid', '$server_id', '$inbound_id', '$remark', '$price', '$time');");
				//echo 'تراکنش با موفقیت انجام شد';
				$msg = "✅ سفارش شما با موفقیت ثبت شد";
				$telegram->sendMessage($userid, $msg);
                $telegram->sendMessage($userid, "✅$volume روز به مدت زمان سرویس شما اضافه شد");
                $sndmsg = "
خرید $volume روز با نوینو
قیمت : $price
آیدی کاربر : $userid
آیدی سرور : $server_id
ریمارک : $remark
";
    $telegram->sendMessage($sendchnl,$sndmsg);
    echo file_get_contents('html/success.html');
        
            }else {
                die("مشکل فنی در ارتباط با سرور. لطفا به مدیریت اطلاع بدید");
            }
        }
        
        
    }
}

if($type == 'volume'){
    if($action == 'pay'){
        $token = base64_decode($_GET['token']);
        $input = explode('#',$token); 
        $server_id = intval($input[0]);
        $inbound_id = intval($input[1]);
        $remark = htmlspecialchars(strip_tags($input[2]));
        $planid = intval($input[3]);
        $userid = intval($input[4]); 
        $res = $telegram->db->query("select * from extra_plan where id=$planid")->fetch(2);  
        $price = $res['price'];
        $volume = $res['volume'];
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        novino_payment($price, $TokenCode, base64_encode($token), $callback_url);
    }elseif($action == 'verify'){
        $token = base64_decode($_GET['InvoiceID']);
        if(!$token) exit;
        
        //$token = base64_decode($token);
        $input = explode('#',$token);
        $server_id = $input[0];
        $inbound_id = $input[1];
        $remark = $input[2];
        $planid = $input[3];
        $userid = $input[4]; 
        $res = $telegram->db->query("select * from extra_plan where id=$planid")->fetch(2);  
        $price = $res['price'];
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        $volume = $res['volume'];
        $time = time();

        $pay_result = novino_verify($price, $TokenCode);
        if($pay_result == 'success'){

    
            require_once('vray.php');
            if($inbound_id > 0)
                $response = update_client_traffic($server_id, $inbound_id, $remark, $volume, 0);
            else
                $response = update_inbound_traffic($server_id, $remark, $volume, 0);
            if($response->success){
                $telegram->db->query("update fl_order set notif=0 where remark='$remark'");
                $telegram->db->query("INSERT INTO `fl_extra_order` VALUES (NULL, '$userid', '$server_id', '$inbound_id', '$remark', '$price', '$time');");
				//echo 'تراکنش با موفقیت انجام شد';
				$msg = "✅ سفارش شما با موفقیت ثبت شد";
				$telegram->sendMessage($userid, $msg);
                $telegram->sendMessage($userid, "✅$volume گیگ به حجم سرویس شما اضافه شد");
                $sndmsg = "
خرید $volume گیگ با نوینو
قیمت : $price
آیدی کاربر : $userid
آیدی سرور : $server_id
ریمارک : $remark
";
    $telegram->sendMessage($sendchnl,$sndmsg);
    echo file_get_contents('html/success.html');

            }else {
                die("مشکل فنی در ارتباط با سرور. لطفا به مدیریت اطلاع بدید");
            }
        }
        
        
    }
}

if($type == 'wallet'){ 
    if($action == 'pay'){
        $amount = intval($_GET['amount']);// echo $amount;die;
        //if($amount < $min_wallet_charge) die('مبلغ کمتر از 2هزار تومان است');
        $userid = intval($_GET['userid']);
        $result = $telegram->db->query("select * from fl_user WHERE userid='$userid'")->rowCount();
        if($result == 0) die('اطلاعات ارسال اشتباه است');
        $telegram->db->query("INSERT INTO `fl_wallet` VALUES (NULL, $amount, $userid, '','0');");
        $woid = $telegram->db->lastInsertId();
        novino_payment($amount, $TokenCode, base64_encode($woid), $callback_url);
    }elseif($action == 'verify'){
        $woid = intval(base64_decode($_GET['InvoiceID']));
        if(!$woid) exit;
        
        $res = $telegram->db->query("select * from fl_wallet where id='$woid' and status=0")->fetch(2);
        if(empty($res)) exit;
        $amount = $res['amount'];
        $userid = $res['userid'];
        $pay_result = novino_verify($amount, $TokenCode);
        if($pay_result == 'success'){
            //echo '<h1 style="text-align:right;color:green;">کیف پول شما با موفقیت شارژ شد</h1>' ; 
            $telegram->db->query("update fl_user set wallet= wallet + $amount where userid='$userid'");
            $telegram->db->query("update fl_wallet set status=1 where id=$woid");
            $msg = "✅ کیف پول شما به مبلغ $amount تومان شارژ شد ";
            $telegram->sendMessage($userid, $msg);
            
            	$telegram->sendPhoto($userid,$acc_text,$file);
$sndmsg = "
شارژ $amount با نوینو
آیدی کاربر : $userid
";
$telegram->sendMessage($sendchnl,$sndmsg);
echo file_get_contents('html/success.html');
        }
        
        
    }
}

if($type == 'buy'){
    if($action == 'pay'){
        if(!isset($_GET['token'])){
            header('location:https://t.me/'.botid);
            exit;
        }
        
        $token = base64_decode($_GET['token']); 
        $token = explode('.',$token);
        $userid = intval($token[0]);
        $fid = intval($token[1]);
        if($token[2]) $dcode = htmlspecialchars(strip_tags($token[2]));
        
        $file_detail = $telegram->db->query("select * from fl_file WHERE id=$fid")->fetch(2); 
        $date = time();
        $days = $file_detail['days'];
        $expire_date = $date + (86400 * $days);
        $protocol = $file_detail['protocol'];
        $price = $file_detail['price'];
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        $server_id = $file_detail['server_id'];
        $acount = $file_detail['acount'];
        $inbound_id = $file_detail['inbound_id'];
        
        if($dcode){
            $dcount = $telegram->db->query("select * from fl_discount WHERE code='$dcode' and active=1");
            if($dcount->rowCount() > 0){
                $amount = $dcount->fetch(2)['amount'];
                if($amount <= 100) {
                    $price = $price * (100-$amount)/100;
                }else {
                    $price = $price - $amount ;
                }
            }
        }
            
        if($acount == 0 and $inbound_id != 0){
            echo 'ظرفیت این کانکشن پر شده است';
            exit;
        }
        
        $order = $telegram->db->query("INSERT INTO `fl_order` VALUES (NULL,  {$userid}, '', {$fid}, $server_id, $inbound_id, '', '$protocol', $expire_date, '', $price,0, '$date', 0);");
        $order_id = $telegram->db->lastInsertId();
        novino_payment($price, $TokenCode, base64_encode($order_id), $callback_url);
    }elseif($action == 'verify'){
        
        $order_id = intval(base64_decode($_GET['InvoiceID']));
        if(!$order_id) exit;
        
        $orderDetails = $telegram->db->query("select * from fl_order where id={$order_id}")->fetch(2);
        $userid = $orderDetails['userid'];
        $fid = $orderDetails['fileid'];
        $file_detail = $telegram->db->query("select * from fl_file WHERE id=$fid")->fetch(2);
        $days = $file_detail['days'];
        $date = time();
        $expire_microdate = intval(floor(microtime(true) * 1000) + (864000 * $days * 100));
        $expire_date = $date + (86400 * $days);
        $type = $file_detail['type'];
        $volume = $file_detail['volume'];
        $protocol = $file_detail['protocol'];
        $price = $file_detail['price'];
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
            if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
        $server_id = $file_detail['server_id'];
        $netType = $file_detail['type'];
        $acount = $file_detail['acount'];
        $inbound_id = $file_detail['inbound_id'];
        $limitip = $file_detail['limitip'];
        
        $price = $orderDetails['amount'];
        
        $pay_result = novino_verify($price, $TokenCode);
        if($pay_result == 'success'){
            
            $telegram->db->query("update fl_order set status=1 where id='$order_id'");
            
    
            // V2ray Api
            require_once('vray.php');
            $uniqid = generateRandomString(42,$protocol); 
        
            $savedinfo = file_get_contents('savedinfo.txt');
            $savedinfo = explode('-',$savedinfo);
            $port = $savedinfo[0] + 1;
            $last_num = $savedinfo[1] + 1;
        
            $srv_remark = $telegram->db->query("select * from fl_server WHERE id=$server_id")->fetch(2)['remark'];
            $remark = "{$srv_remark}-{$last_num}";
        
            file_put_contents('savedinfo.txt',$port.'-'.$last_num);
            //$telegram->sendMessage($cuserid,"$server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume");exit;
            
            if($inbound_id == 0){    
                $response = add_inbound($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType); 
                if(! $response->success){
                    // run again
                    $response = add_inbound($server_id, $uniqid, $protocol, $port, $expire_microdate, $remark, $volume, $netType);
                } 
            }else {
                $response = add_inbount_client($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip); 
                if(! $response->success){
                    // run again
                    $response = add_inbount_client($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip);
                } 
            }
            
            //$telegram->sendMessage($cuserid,json_encode($response));exit;
             
            $vray_link = genLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id);
            
            $acc_text = "🔗 $remark \n <code>$vray_link</code>" . " \n  برای کپی کردن لینک روی آن کلیک کنید \n";
            
            
            $vray_link = genLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id);
            if($protocol == 'vless'){
                $vray_link = explode('#',$vray_link);
                $vray_link = $vray_link[0].'#'.urlencode($vray_link[1]);
                $vray_link = str_replace('&flow=xtls-rprx-direct','',$vray_link);
                $vray_link = str_replace('&host=','&headerType=http&host=',$vray_link);
                //$telegram->sendMessage($cuserid,json_encode($vray_link));exit;
            }
            //$telegram->sendMessage($cuserid,json_encode($vray_link));exit;
           // $respd = $telegram->db->query("select * from fl_accounts WHERE fid={$id} and active=1 and sold=0")->fetch(2);
            //$acc_text = $respd['text'] . " \n  برای کپی کردن لینک روی آن کلیک کنید \n";
            $acc_text = "🔗 $remark \n <code>$vray_link</code>" . " \n  برای کپی کردن لینک روی آن کلیک کنید \n";
            //$acc_id = $respd['id'];
            
            
            
            include 'phpqrcode/qrlib.php';
            $path = 'images/';
            $file = $path.$userid.".png"; //unlink($file);
            $ecc = 'L';
            $pixel_Size = 10;
            $frame_Size = 10;
            QRcode::png($vray_link, $file, $ecc, $pixel_Size, $frame_size);
        	addBorderImage($file);
            //$fileLink = "<a href='".baseURI.$file."'>&#8194;</a>";
        	//$telegram->sendHTML($cuserid,$acc_text.$fileLink,$finalop);
        	$telegram->sendPhoto($cuserid,$acc_text,$file);
        
        	$order = $telegram->db->query("update `fl_order` set link='$vray_link',remark='$remark',status=1 where id=$order_id");
        	
        	if($inbound_id == 0) {
                $server_info = $telegram->db->query("SELECT * FROM fl_server WHERE id=$server_id")->fetch(2);
                if($server_info['ucount'] != 0)
                    $telegram->db->query("UPDATE `fl_server` SET `ucount` = ucount - 1 WHERE id=$server_id");
            }else{
                if($acount != 0) 
                    $telegram->db->query("UPDATE `fl_file` SET `acount` = acount - 1 WHERE id=$fid");
            }
			
			//echo "<h1 style='color:green'>تراکنش شما با موفقیت ثبت شد. به ربات برگردید</h1>";
			$telegram->sendMessage($userid, "✅سفارش شما با موفقیت ثبت شد");
				$telegram->sendPhoto($userid,$acc_text,$file);
$sndmsg = "
خرید درگاه نوینو 
قیمت : $price
آیدی کاربر : $userid
آیدی سرور : $server_id
لینک دریافتی :

$vray_link
";
    $telegram->sendMessage($sendchnl,$sndmsg);
    echo file_get_contents('html/success.html');
            
            // pay referer
            $userReferer = $telegram->db->query("select * from fl_subuser where userid=$userid");
            if($userReferer->rowCount() ){
                $ures = $userReferer->fetch(2);
                $userToplevel = $ures['toplevel_userid'];
                $ufname = $ures['fname'];
                $amount = ($price) * ($pursant / 100);
                $telegram->db->query("update fl_user set wallet= wallet + $amount WHERE userid=$userToplevel");
                $telegram->sendMessage($userToplevel, "💟کاربر {$ufname} یک خرید به مبلغ  $price تومان انجام داد و $pursant درصد آن یعنی $amount تومان به کیف پول شما اضافه شد👍"); 
            }

            
        }
    } // verify
}



function novino_payment($price, $TokenCode, $oid, $callback_url){
    global $userid;
    $data = [
        "merchant_id" => $TokenCode,
        "amount" => $price *10, //// rial
        "invoice_id" => $oid,
        "description" => "u:$userid oid:$oid",
        "name" => "",
        "mobile" => "",
        "email" => "",
        "callback_url" => $callback_url."&oid=$oid"
    ]; //var_dump($data) ;die;
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://api.novinopay.com/payment/ipg/v2/request");
    curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type" => "application/json"]);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
    curl_setopt($curl, CURLOPT_TIMEOUT, 50);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $curl_exec = curl_exec($curl);
    curl_close($curl);
    
    $result = json_decode($curl_exec);
    
    if (isset($result->status) && $result->status == 100) {
        ///save $result->data->authority in db
        ///save $result->data->trans_id in db
    
        header("Location: {$result->data->payment_url}");
        exit;
    } else {
        echo isset($result->status) ? "Error Code: {$result->status} | {$result->message}" : "Error Connecting to payment";
    }
}

function novino_verify($price, $TokenCode){
    if (isset($_REQUEST["PaymentStatus"]) && $_REQUEST["PaymentStatus"] == "OK") {

        $Authority = (isset($_REQUEST["Authority"]) && !empty($_REQUEST["Authority"])) ? $_REQUEST["Authority"] : "";
        $InvoiceID = (isset($_REQUEST["InvoiceID"]) &&  !empty($_REQUEST["InvoiceID"])) ? $_REQUEST["InvoiceID"] : "";
    
        $data = [
            "merchant_id" => $TokenCode,
            "amount" => $price *10,
            "authority" => $Authority 
        ];
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://api.novinopay.com/payment/ipg/v2/verification");
        curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type" => "application/json"]);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        curl_setopt($curl, CURLOPT_TIMEOUT, 50);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $curl_exec = curl_exec($curl);
        curl_close($curl);
    
        $result = json_decode($curl_exec);
    
        if (isset($result->status) && $result->status == 100) {
            return "success";
        } else {
            echo isset($result->status) ? "Error Code: {$result->status} | {$result->message}" : "Error Connecting to payment";
        }
    
    }else{
        echo 'Your Payment is failed';
    }
    
}


