<?php
	header('X-Frame-Options: DENY');
	header('X-XSS-Protection: 1; mode=block');
	header('Content-Type: text/html; charset=utf-8');

	include('../../../inc/db.php');
	include('../../../inc/classes/SourceQuery/class.sourcequery.php');
	include('../../../inc/classes/SourceQuery/class.basesocket.php');
	include('../../../inc/classes/SourceQuery/class.buffer.php');
	include('../../../inc/classes/SourceQuery/class.socket.php');

	$update = $_SERVER['REQUEST_TIME'];

	$conf = $pdo->query('SELECT `mon_gap`, `mon_time`, `mon_api` FROM `config2` LIMIT 1');
			$conf->setFetchMode(PDO::FETCH_OBJ);
	$conf = $conf->fetch();

	if(($update-$conf->mon_time) < $conf->mon_gap)
		exit;

	if($conf->mon_api == 1)
	{
		include('../../../inc/functions.php');

		update_monitoring($pdo);
	}else{
		$servers = $pdo->query('SELECT `id`, `ip`, `port`, `name`, `address`, `type`, `game` FROM `servers` WHERE `show`="1" ORDER BY `trim`');
				   $servers->setFetchMode(PDO::FETCH_OBJ);
		while($server = $servers->fetch())
		{
			$info = $pdo->query('SELECT `id` FROM `monitoring` WHERE `sid`="'.$server->id.'" LIMIT 1');
					$info->setFetchMode(PDO::FETCH_OBJ);
			if(!count($info->fetchAll()))
				$pdo->query('INSERT INTO `monitoring` set '
					.'`ip`="'.$server->ip.'",'
					.'`port`="'.$server->port.'",'
					.'`name`="Не определено",'
					.'`address`="'.$server->address.'",'
					.'`game`="'.$server->game.'",'
					.'`players_now`="0",'
					.'`players_max`="0",'
					.'`map`="unknown",'
					.'`type`="'.$server->type.'",'
					.'`sid`="'.$server->id.'"');

			try
			{
				$sq = new SourceQuery;
				$sq->Connect($server->ip, $server->port);
				$data = $sq->GetInfo();

				$data['name'] = $data['HostName'] != '' ? htmlspecialchars($data['HostName']) : $server->name;
				$data['map'] = $data['Map'] != '' ? htmlspecialchars($data['Map']) : 'unknown';
				$data['online'] = (int) $data['Players'];
				$data['maxonline'] = (int) $data['MaxPlayers'];

				if(strpos($data['map'], '/') !== false)
				{
					$data['map'] = explode('/', $data['map']);
					$data['map'] = end($data['map']);
				}
			}catch(Exception $e){
				$data['name'] = $server->name;
				$data['map'] = 'unknown';
				$data['online'] = 0;
				$data['maxonline'] = 0;
			}

			$pdo->query('UPDATE `monitoring` set `name`="'.$data['name'].'", `players_now`="'.$data['online'].'", `players_max`="'.$data['maxonline'].'", `map`="'.$data['map'].'" WHERE `sid`="'.$server->id.'" LIMIT 1');
		}

		$pdo->query('UPDATE `config2` SET `mon_time`="'.$update.'" WHERE `id`="1" LIMIT 1');
	}
?>