<?php
include_once __DIR__.'/config.php';
include_once __DIR__.'/telegram.php';
include_once(__DIR__.'/vray.php');
$telegram = new telegram(TOKEN,HOST,USERNAME,PASSWORD,DBNAME); 
$time = time();

$telegram->db->query("DELETE FROM sendcount_list WHERE leftsend=0");
$gateways = $telegram->db->query("select * from gateway where id=1")->fetch(2);
$orders = $telegram->db->query("select * from sendcount_list where leftsend > 0 ORDER BY id asc LIMIT 50");
if($orders){
    $orders = $orders->fetchAll(2);
    if(!empty($orders)){
    foreach ($orders as $order) {
        $sdc_id = $order['id']; 
	    $userid = $order['userid'];
        $fid = $order['fileid'];
        $leftsend = $order['leftsend'];
        $sendtype = $order['type'];
        
        $seller = $telegram->db->query("select * from fl_sellers where userid=$userid")->fetch(2);
        
        if($sendtype == 'custom'){
            $custom_order = $telegram->db->query("select * from custom_order WHERE id='$fid' ")->fetch(2);
            $days = $custom_order['days'];
            $server_id = $custom_order['server_id'];  

            $file_detail = $telegram->db->query("select * from fl_file WHERE server_id='$server_id' and active=1 order by id desc limit 1")->fetch(2); 
            $inbound_id = $file_detail['inbound_id'];
            $expire_microdate = ($file_detail['first_use'] == '1' and $inbound_id > 0) ? -abs(86400000 * $days) : intval(floor(microtime(true) * 1000) + (864000 * $days * 100));
            $expire_microdate = !empty($seller) ? -abs(86400000 * $days) : intval(floor(microtime(true) * 1000) + (864000 * $days * 100));
            $expire_date = $time + (86400 * $days);
            
            $volume = $custom_order['volume'];
            $protocol = $file_detail['protocol'];
            $price = $custom_order['price'];
            
            $netType = $file_detail['type'];
            $limitip = intval($custom_order['limitip']);
            $usremark = $custom_order['remark'];
        }else{
            $file_detail = $telegram->db->query("select * from fl_file WHERE id='$fid' ")->fetch(2);
            $days = $file_detail['days'];
            $server_id = $file_detail['server_id'];
            
            $inbound_id = $file_detail['inbound_id'];
            $expire_microdate = ($file_detail['first_use'] == '1' and $inbound_id > 0) ? -abs(86400000 * $days) : intval(floor(microtime(true) * 1000) + (864000 * $days * 100));
            $expire_date = $time + (86400 * $days);
            $type = $file_detail['type'];
            $volume = $file_detail['volume'];
            $protocol = $file_detail['protocol'];
            $price = $file_detail['price'];
            
            $netType = $file_detail['type'];
            $limitip = intval($file_detail['limitip']);
        }
        
        if(!empty($seller)) $price = $price - (($price) * ($seller['percent'] / 100));
		
		$srvinfo = $telegram->db->query("select * from server_info WHERE id='$server_id'")->fetch(2);
		$srv_type = $srvinfo['ptype'];
		$panel_url = $srvinfo['panel_url'];
		
        // Api
        require_once('vray.php');
        require_once('marz.php');
        for($i=0;$i<$leftsend; $i++){
            
            $savedinfo = file_get_contents('savedinfo.txt');
            $savedinfo = explode('-',$savedinfo);
            $port = $savedinfo[0] + 1;
            $last_num = $savedinfo[1] + 1;
            
            if($srv_type == 'marzban'){

                $srv_remark = $telegram->db->query("select * from fl_server WHERE id=$server_id")->fetch(2)['remark'];
                $uremark = $telegram->db->query("select * from fl_remark where userid=$userid")->fetch(2);
                if($uremark) $uremark = $uremark['remark']; else $uremark = $srv_remark;
                $username = $remark = "{$uremark}_{$last_num}";
            
                $protocol = explode('|', $file_detail['protocol']);
                if($file_detail['first_use'] == '1' && !empty($seller))
                    $response = adduser($server_id, $username, $days, $volume, $protocol);
                else
                    $response = adduser2($server_id, $username, $expire_date, $volume, $protocol);
                //$telegram->sendMessage($userid, json_encode($response));die;
                if(is_null($response) or !$response){
                    $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
                   continue;
                }
            
            	if(!$response->subscription_url){
            	    $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
                    continue;
                }
                file_put_contents('savedinfo.txt',$port.'-'.$last_num);
                
                
                $sublink = $response->subscription_url;
                $acc_text = "🔗 $username \n <code>$sublink</code>";
    
                $file = "images/{$userid}.{$time}".rand(0,999999).".png";
		        create_qrcode($sublink, $file);
                	
            	$acc_text = "✅سرویس شما با موفقیت ایجاد شد


🚀اطلاعات سرویس شما به شکل زیر است👇
$acc_text";

            	$aa = $telegram->sendPhoto($userid,$acc_text,$file);
            	$order = $telegram->db->query("INSERT INTO fl_order VALUES (NULL,  {$userid}, '', {$fid}, $server_id, 0, '$username', '".implode('|',$protocol)."', $expire_date, '$sublink', '', $price,1, '$time', 0);");
//var_dump($order);die;
                }else{
                    $uniqid = generateRandomString(42,$protocol); 
        
                    $srv_remark = $telegram->db->query("select * from fl_server WHERE id=$server_id")->fetch(2)['remark'];
                    $uremark = $telegram->db->query("select * from fl_remark where userid='$userid'")->fetch(2);
                    if($uremark) $uremark = $uremark['remark']; else $uremark = $srv_remark;
                    if(!is_null($usremark)) $uremark = $usremark;
                    $remark = "{$uremark}-{$last_num}";
                
                    file_put_contents('savedinfo.txt',$port.'-'.$last_num);
                    //$telegram->sendMessage($userid,"$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); 
                    }else {
                        $response = add_inbount_client($server_id, $uniqid, $inbound_id, $expire_microdate, $remark, $volume, $limitip); 
                    }
                    if(is_null($response)){
                        $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
                        continue;
                    }
                	if($response == "inbound not Found"){
                	    $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
                		continue;
                	}
                	if(!$response->success){
                	    $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
                        continue;
                    }
                    $vray_link = genLink($server_id, $uniqid, $protocol, $remark, $port, $netType, $inbound_id);
                    
                    $addsub = "";
                    $token = generateRandomString2(16);
                	$getLink_url = baseURI."sub.php?token=".$token;
                	if($gateways['sublink'] == 1){
                		$addsub = "\n\n 🔗 لینک هوشمند سرویس شما: \n <code>$getLink_url</code>";
                	}
                    $acc_text = "🔗 $remark \n <code>$vray_link</code> $addsub" . " \n  برای کپی کردن لینک روی آن کلیک کنید \n";
            
                    $file = "images/{$userid}.{$time}".rand(0,999999).".png";
		        	create_qrcode($vray_link, $file);
            
                	$telegram->sendPhoto($userid,$acc_text,$file);
                	$order = $telegram->db->query("INSERT INTO `fl_order` VALUES (NULL,  {$userid}, '', {$fid}, $server_id, $inbound_id, '$remark', '$protocol', $expire_date, '$vray_link', '$token', $price,1, '$time', 0);");
                
            }
            
            $telegram->db->query("UPDATE sendcount_list SET leftsend = leftsend - 1 where id=$sdc_id");
        } // loop

    }
  }
}
echo "OK~";

