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

$cron = file_get_contents(__DIR__.'/bulkd.txt');
if($cron == '0' or $cron == '') exit;

$input = explode('-', $cron);

$cronid = $input[0];
$sid = $input[1];
$day = $input[2];
$gb = $input[3];
$date = $input[4];

if($sid == 0)
    $sql = "select * from fl_order where status=1 and id > $cronid and date < $date ORDER BY id ASC LIMIT 50";
else
    $sql = "select * from fl_order where status=1 and server_id = $sid and id > $cronid and date < $date ORDER BY id ASC LIMIT 50";
    
$orders = $telegram->db->query($sql);
if($orders){
    $orders = $orders->fetchAll(2); 
    if(!empty($orders)){
    foreach ($orders as $order) {
        
        $oid = $order['id'];
        
        file_put_contents(__DIR__.'/bulkd.txt', "$oid-$sid-$day-$gb-$date");
        
	    $userid = $order['userid'];
        $remark = $username = $order['remark'];
        $server_id = $order['server_id'];
        $inbound_id = $order['inbound_id'];
        
        $panel_type = $telegram->db->query("SELECT * FROM server_info WHERE id='$server_id'")->fetch(2)['ptype'];
        if($panel_type == 'marzban'){
            
            $response = muser_detail($server_id, $username); 
            if(is_null($response) or !$response) continue;
        	if(!$response->subscription_url) continue;

        	$time = time();
        	$expire = $response->expire;
            if($expire < $time) $expire = $time + ($day * 86400);
            else $expire += $day * 86400;
            
        	$response->expire = $expire;
            $response->data_limit += $gb * 1073741824;
            $response->status = 'active';
            $result = add_mtraffic($server_id, $username, $response); 

        }else{
            if($inbound_id > 0)
                $response = update_client_traffic($server_id, $inbound_id, $remark, $gb, $day);
            else
                $response = update_inbound_traffic($server_id, $remark, $gb, $day);
        }
        
		
		$telegram->db->query("update fl_order set notif=0 where remark='$remark'");
    }
 }else file_put_contents(__DIR__.'/bulkd.txt', 0);
}

echo "Done~";