<?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();

$server_id = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
$days = isset($_GET['days']) ? intval($_GET['days']) : -30;
if($server_id == 0) die('no server id');

$response = getList($server_id);
if(is_null($response) or $response === false or !isset($response->obj)) {die('no response from server');}
$response = $response->obj; 
$count = 0;
foreach($response as $row){
	$inbound_id = $row->id;
	$total = $row->total;
	$up = $row->up;
	$down = $row->down;
	$remark = $row->remark;
	$expiryTime = $row->expiryTime;
	$settings = json_decode($row->settings, true); 
	$clientStats = $row->clientStats; 
	$clients = $settings['clients'];

	if(is_null($expiryTime) or is_null($total) or $total == 0 or $expiryTime == 0 or $expiryTime < 0) {continue;}
	$leftgb = round( ($total - $up - $down) / 1073741824, 2);
	$expiryTime = substr_replace($expiryTime, "", -3);

	if(is_numeric($expiryTime)){
		if($expiryTime < time() + ($days * 86400)){
		    $count++;
			remove_inbound($server_id, $remark, 1);
			continue;
		}
	}
	
	if(count($clients) > 1){
		foreach($clientStats as $key => $clientStat) {
			$total = $clientStat->total;
			$up = $clientStat->up;
			$down = $clientStat->down;
			$expiryTime = $clientStat->expiryTime;
			
			if(is_null($expiryTime) or is_null($total) or $total == 0 or $expiryTime == 0 or $expiryTime < 0) {continue;}
			$expiryTime = substr_replace($expiryTime, "", -3);

			if(is_numeric($expiryTime)){
				if($expiryTime < time()+($days * 86400)){
				    $count++;
					remove_client($server_id, $inbound_id, $remark, 1);
				}
			}
		}
	}
}
echo $count;