<?php
include_once "../inc/start.php";
include_once "../inc/protect.php";

if(empty($_POST['phpaction'])) {
	log_error("Прямой вызов actions.php");
	exit('Ошибка: [Прямой вызов инклуда]');
}

if($conf->token == 1 && ($_SESSION['token'] != clean($_POST['token'], null))) {
	log_error("Неверный токен");
	exit('Ошибка: [Неверный токен]');
}

/* пользовательский */
if(isset($_POST['get_services'])) {
	$id = checkJs($_POST['id'], "int");
	if(empty($id)) {
		exit ();
	}
	$i    = 0;
	$data = '';
	$STH  = $pdo->query("SELECT id,name,rights,sale FROM gifts WHERE server = '$id' ORDER BY trim");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	while($row = $STH->fetch()) {
		if($row->sale != 2) {
			if($i == 0) {
				$service = $row->id;
				$i++;
			}
			$data .= '<option value="'.$row->id.'">'.$row->name.'</option>';
		}
	}

	exit(json_encode(array('status' => '1', 'data' => $data, 'service' => $service)));
}

if(isset($_POST['get_gift_fields'])) {
	$id = checkJs($_POST['id'], "int");
	if(empty($id)) {
		exit ();
	}
	
	$STH = $pdo->query("SELECT rights FROM gifts WHERE id = $id LIMIT 1");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$gifts = $STH->fetch();
	
	exit(json_encode(include_once "{$gifts->rights}.php"));
}

if(isset($_POST['get_tarifs'])) {
	$id = checkJs($_POST['id'], "int");
	if(empty($id)) {
		exit ();
	}

	$STH = $pdo->query("SELECT `gifts`.`text`, `gifts`.`stime`, `gifts`.`discount` AS `service_dicount`,`servers`.`discount` FROM `gifts` LEFT JOIN `servers` ON `gifts`.`server`=`servers`.`id` WHERE `gifts`.`id` = '$id' LIMIT 1");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$row  = $STH->fetch();
	$text = $row->text;
	$st = $row->stime;

	$service_discount = $row->service_dicount;
	$server_discount  = $row->discount;

	$STH = $pdo->query("SELECT discount FROM config__prices LIMIT 1");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$disc     = $STH->fetch();
	$discount = $disc->discount;

	$data = '';
	$STH  = $pdo->query("SELECT id,pirce,time,discount FROM gifts__tarifs WHERE service = '$id' ORDER BY pirce");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	while($row = $STH->fetch()) {
		
		$time = $row->time.' '.$st;

		if(isset($user->proc)) {
			$user_proc = $user->proc;
		} else {
			$user_proc = 0;
		}

		$proc  = calculate_discount($server_discount, $discount, $user_proc, $service_discount, $row->discount);
		$pirce = calculate_pirce($row->pirce, $proc);

		if($pirce != $row->pirce) {
			$data .= '<option value="'.$row->id.'">'.$time.' - '.$pirce.' '.$messages['RUB'].' (с учетом скидки в '.$proc.'%)</option>';
		} else {
			$data .= '<option value="'.$row->id.'">'.$time.' - '.$pirce.' '.$messages['RUB'].'</option>';
		}
	}
	exit(json_encode(array('status' => '1', 'data' => $data, 'text' => $text)));
}
if(isset($_POST['get_server_store'])) {
	$id   = checkJs($_POST['id'], "int");
	$type = checkJs($_POST['type'], "int");

	if(empty($id)) {
		exit ();
	}
	if(empty($type)) {
		$type = 0;
	}

	$STH = $pdo->query("SELECT `monitoring`.*, `servers`.`rcon`,`servers`.`type` FROM `monitoring` LEFT JOIN `servers` ON `monitoring`.`sid`=`servers`.`id` WHERE `monitoring`.`sid`='$id'");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$row = $STH->fetch();
	if(empty($row->id)) {
		$STH = $pdo->prepare("SELECT `id`,`ip`,`port`,`name`,`address`,`rcon`,`game`,`binds`,`type` FROM `servers` WHERE `id`=:id LIMIT 1");
		$STH->setFetchMode(PDO::FETCH_OBJ);
		$STH->execute(array(':id' => $id));
		$row              = $STH->fetch();
		$row->map         = 0;
		$row->name        = '0';
		$row->players_max = 0;
		$row->players_now = 0;
		$row->sid         = $row->id;
	}

	if($row->type == 0 || $row->type == 1) {
		$disp = 'disp-n';
	} else {
		$disp = '';
	}

	if(($row->map != '0') and file_exists('../files/maps_imgs/'.$row->map.'.jpg')) {
		$map = '/files/maps_imgs/'.$row->map.'.jpg';
	} else {
		$map = '/files/maps_imgs/none.jpg';
	}
	if($row->map == '0') {
		$row->map = "Не определено";
	}
	if($row->name == '0') {
		$row->name = "Не определено";
	}

	$tpl      = new Template;
	$tpl->dir = '../templates/'.$conf->template.'/tpl/';

	$tpl->load_template('elements/server_min.tpl');
	$tpl->set("{name}", $row->name);
	$tpl->set("{map_img}", $map);
	$tpl->set("{map_name}", $row->map);
	$tpl->set("{template}", $conf->template);
	$tpl->set("{max}", $row->players_max);
	$tpl->set("{now}", $row->players_now);
	$tpl->set("{ip}", $row->ip);
	$tpl->set("{port}", $row->port);
	$tpl->set("{id}", $row->sid);
	$tpl->set("{disp}", $disp);
	$tpl->set("{site_host}", $site_host);
	$tpl->set("{address}", $row->address);
	$tpl->set("{rcon}", $row->rcon);
	$tpl->compile('content');
	$tpl->clear();

	
	$tpl->show($tpl->result['content']);
	$tpl->global_clear();
}

if(isset($_POST['buy_service'])) {
	ignore_user_abort(1);
	set_time_limit(0);

	$server   = checkJs($_POST['server'], "int");
	$service  = checkJs($_POST['service'], "int");
	$tarif    = checkJs($_POST['tarifs'], "int");
	$nick     = checkJs($_POST['nick'], null);
	$pass     = checkJs($_POST['pass'], null);
	$steam_id = checkJs($_POST['steam_id'], null);
	$check1   = checkJs($_POST['check1'], "int");
	$check2   = checkJs($_POST['check2'], "int");

	if(empty($check1)) {
		$check1 = 0;
	}
	if(empty($check2)) {
		$check2 = 0;
	}

	if($conf->cont == 1) {
		$STH = $pdo->query("SELECT `vk` FROM `users` WHERE `id`='$_SESSION[id]' LIMIT 1");
		$STH->setFetchMode(PDO::FETCH_OBJ);
		$row = $STH->fetch();
		if($row->vk == '---' or empty($row->vk)) {
			exit (json_encode(array('status' => '3', 'data' => 'Укажите свой аккаунт Вконтакте в <a href="../settings" target="_blank">профиле</a>')));
		}
	}

	if(empty($server) or empty($service) or empty($tarif)) {
		exit (json_encode(array('status' => '3', 'data' => 'Заполните все поля!')));
	}

	$STH = $pdo->query("SELECT * FROM servers WHERE id='$server' LIMIT 1");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$server = $STH->fetch();
	if(empty($server->id)) {
		exit (json_encode(array('status' => '3', 'data' => 'Данного сервера не существует')));
	}
	
	$server->address = $server->ip.':'.$server->port;
	$binds = explode(';', $server->binds);

	$SIDO = new SteamIDOperations();

	if(empty($steam_id)) {
		exit (json_encode(array('status' => '2', 'input' => 'player_steam_id', 'reply' => 'Заполните!')));
	}
	if(mb_strlen($steam_id, 'UTF-8') > 32) {
		exit (json_encode(array('status' => '2', 'input' => 'player_steam_id', 'reply' => 'Не более 32 символов!')));
	}
	if(!$steam_id = $SIDO->GetSteamID32($steam_id)) {
		exit (json_encode(array('status' => '2', 'input' => 'player_steam_id', 'reply' => 'Неверный STEAM ID!')));
	}
	
	$AM = new AdminsManager;
	if(!$AM->check_for_bad_nicks($pdo, $admin['name'])) {
		exit (json_encode(array('status' => '3', 'data' => 'Использовать данный идентификатор запрещено!')));
	}

	$STH = $pdo->query("SELECT * FROM gifts WHERE id='$service' and server='$server->id' LIMIT 1");
	$STH->setFetchMode(PDO::FETCH_OBJ);
	$service = $STH->fetch();
	if(empty($service->id)) {
		exit (json_encode(array('status' => '3', 'data' => 'Услуга не найдена')));
	}
	if($service->sale == 2) {
		exit (json_encode(array('status' => '3', 'data' => 'Услуга не продается')));
	}
	
	include_once "{$service->rights}.php";
	
	exit (json_encode(array('status' => '3', 'data' => 'Ошибка покупки, повторите попытку через некоторое время, либо сообщите администратору')));
}