<?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__.'/notif.txt');
if($cron == ''){
	file_put_contents(__DIR__.'/notif.txt', 0);
	$cron = 0;
}

if(is_null($delete_delay)) $delete_delay = 3;
if(is_null($gb_notif_limit)) $gb_notif_limit = 2;
if(is_null($day_notif_limit)) $day_notif_limit = 2;

$orders = $telegram->db->query("select * from fl_order where id > $cron and status=1 and notif=0 ORDER BY id asc LIMIT 200; "); //  and remark = 'vless-4020'
if($orders){
    $orders = $orders->fetchAll(2);
    if(!empty($orders)){
    foreach ($orders as $order) {
        $send = false;
	    $userid = $order['userid'];
        $remark = $order['remark'];
        $server_id = $order['server_id'];
        $inbound_id = $order['inbound_id'];
        $amount = $order['amount'];
        $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', $order['id']);continue;}
		
        $response = getList($server_id);
        if(is_null($response) or $response === false or !isset($response->obj)) {file_put_contents(__DIR__.'/notif.txt', $order['id']);continue;}
		$response = $response->obj; 
        foreach($response as $row){
            if($inbound_id == 0) {
                if($row->remark == $remark) { 
                    $total = $row->total;
                    $up = $row->up;
                    $down = $row->down;
                    $expiryTime = $row->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 $total < 0 or $expiryTime == 0 or $expiryTime < 0) {file_put_contents(__DIR__.'/notif.txt', $order['id']);continue;}
        $leftgb = round( ($total - $up - $down) / 1073741824, 2);
        $expiryTime = substr_replace($expiryTime, "", -3);
		
		$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(is_numeric($expiryTime) and is_numeric($leftgb)){
			if($expiryTime < time() + (86400 * $day_notif_limit) ) $send = "روز"; elseif($leftgb < $gb_notif_limit) $send = "گیگ";
		}
        
        if($send){
			$notif_limit = ($send =='روز') ? $day_notif_limit : $gb_notif_limit;
			$msg = "💡 کاربر گرامی،
از سرویس اشتراک $remark کمتر از ($notif_limit $send) باقی مانده است. میتوانید سرویس خود را تمدید کنید، در غیر اینصورت این اشتراک شما حذف خواهد شد.";
            if($amount > 0) $telegram->sendMessage($userid, $msg);
            $telegram->db->query("update `fl_order` set notif= $time + 86400*$delete_delay where remark='$remark'");
        }
		file_put_contents(__DIR__.'/notif.txt', $order['id']);
    }
  } else file_put_contents(__DIR__.'/notif.txt', 0);
}


