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

$table_exists = $telegram->db->query("show tables like 'config_stat';")->rowCount();
if(!$table_exists){
	$sql = "CREATE TABLE `config_stat` (`id` INT NOT NULL AUTO_INCREMENT , `userid` VARCHAR(50) NOT NULL , `remark` VARCHAR(100) NOT NULL , `total` VARCHAR(20) NOT NULL , `up` VARCHAR(20) NOT NULL , `down` VARCHAR(20) NOT NULL , `expiryTime` VARCHAR(40) NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;";
	$telegram->db->query($sql);
}
$table_exists = $telegram->db->query("show tables like 'clog';")->rowCount();
if(!$table_exists){
	$telegram->db->query("CREATE TABLE `clog` (`id` INT NOT NULL AUTO_INCREMENT , `remark` VARCHAR(100) NOT NULL , `userid` VARCHAR(30) NOT NULL , `type` VARCHAR(50) NOT NULL , `date` VARCHAR(30) NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;");
}


$cron = file_get_contents(__DIR__.'/notifdel.txt');
if($cron == ''){
	file_put_contents(__DIR__.'/notifdel.txt', 0);
	$cron = 0;
}

/** remove */
$orders = $telegram->db->query("SELECT * FROM fl_order where status=1 and notif > 2 and $time > notif ORDER BY id asc limit 200");
if($orders){
    $orders = $orders->fetchAll(2); 
    if(!empty($orders)){
    foreach ($orders as $order) { 
        
	    $userid = $order['userid'];
	    $fileid = $order['fileid'];
        $remark = $order['remark'];
        $server_id = $order['server_id'];
        $inbound_id = $order['inbound_id'];
        $notif = $order['notif'];
        $oid = $order['id'];
        
        $rowCount = $telegram->db->query("select * from server_info where id=$server_id and ptype = 'xui'")->rowCount();
        if($rowCount == 0) {file_put_contents(__DIR__.'/notif.txt', $oid);continue;}
        
        file_put_contents(__DIR__.'/notifdel.txt', $oid);
        
        // check again
		$response = getList($server_id);
		if(is_null($response) or $response === false or !isset($response->obj)) {continue;}
		$response = $response->obj; 
		foreach($response as $row){
		    $settings = json_decode($row->settings, true); 
            $clients = $settings['clients'];
			if($inbound_id == 0) {
				if($row->remark == $remark) { 
					$total = $row->total;
					$up = $row->up;
					$down = $row->down;
					$expiryTime = $row->expiryTime;
					if($expiryTime <= 0){
                        $expiryTime = $clients[0]['expiryTime'];
                    }
					break;
				}
			}else{  
				$settings = json_decode($row->settings, true); 
				$clients = $settings['clients'];
				foreach($clients as $key => $client) {
					if($client['email'] == $remark) { 
						$total = $client['totalGB'];
					}
				}
				
				$clientStats = $row->clientStats; 
				foreach($clientStats as $key => $clientStat) {
					if($clientStat->email == $remark) {
						$up = $clientStat->up;
						$down = $clientStat->down;
						$expiryTime = $clientStat->expiryTime;
						break;
					}
				}
			}
		} 
		
		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);
		
		if(strlen($expiryTime) == 13) $expiryTime = substr_replace($expiryTime, "", -3);
		if(is_numeric($expiryTime) and is_numeric($leftgb)){
			if($expiryTime < time() or $leftgb <= 0){ // ended
				if(strlen($expiryTime) < 10 or $leftgb == 0.1) continue;
				
				$exists = $telegram->db->query("select * from config_stat where remark = '$remark'")->rowCount();
				if($exists)
					$telegram->db->query("update config_stat set total='$total',up='$up',down='$down',expiryTime='$expiryTime' where remark = '$remark'");
				else
					$telegram->db->query("insert into config_stat VALUES (NULL, '$userid', '$remark', '$total', '$up', '$down', '$expiryTime')");
				 
				if($inbound_id > 0) 
					$res = remove_client($server_id, $inbound_id, $remark, 1); 
				else 
					$res = remove_inbound($server_id, $remark, 1); 
				
				if(!$res) continue;
				$msg = "💡 کاربر گرامی،
سرویس اشتراک $remark به اتمام رسیده و به دلیل عدم تمدید، سرویس مورد نظر حذف شد.
می توانید از قسمت خرید سرویس، اقدام به تهیه سرویس جدید کنید.";
			
				$telegram->sendMessage($userid, $msg);
				$telegram->db->query("delete FROM `fl_order` where remark='$remark'");
				$telegram->db->query("insert into clog values (NULL, '$remark', '$userid','notif', $time)");
				if($inbound_id > 0)
					$telegram->db->query("UPDATE `fl_file` SET `acount` = acount+1 WHERE `id` = $fileid");
				else
					$telegram->db->query("UPDATE `fl_server` SET `ucount` = ucount+1 WHERE `id` = $server_id");
			}else{
				$telegram->db->query("update `fl_order` set notif=0 where remark='$remark'");
			}
		}
	}
 } else file_put_contents(__DIR__.'/notifdel.txt', 0);
}
