<?php
if(!isset($_SERVER['SERVER_SOFTWARE'])) {
	$_SERVER['SERVER_SOFTWARE'] = '0';
}
if(!isset($_SERVER['GATEWAY_INTERFACE'])) {
	$_SERVER['GATEWAY_INTERFACE'] = '0';
}
if(!isset($_SERVER['DOCUMENT_ROOT'])) {
	$_SERVER['DOCUMENT_ROOT'] = '0';
}

$key = md5($_SERVER['SERVER_SOFTWARE'].$_SERVER['GATEWAY_INTERFACE'].$_SERVER['DOCUMENT_ROOT']);

if ($_POST['key'] != $key) {
	exit(json_encode(array('status' => '2', 'data' => 'Ошибка: [Прямой вызов исполнителя]')));
}

include_once '../../inc/functions.php';
include_once '../../inc/classes/class.users.php';

if (isset($_POST['try_connect'])) {
	$host = check($_POST['host'],null);
	$base = check($_POST['base'],null);
	$user = check($_POST['user'],null);
	$pass = check($_POST['pass'],null);

	if (empty($host) or empty($base) or empty($user) or empty($pass)) {
		exit(json_encode(array('status' => 2, 'data' => 'Заполните все поля.')));
	}

	if(db_connect($host, $base, $user, $pass)) {
		exit(json_encode(array('status' => 1, 'data' => 'Соединение установленно')));
	} else {
		exit(json_encode(array('status' => 2, 'data' => 'Ошибка подключения к базе данных')));
	}
}

if (isset($_POST['install'])) {
	$host = check($_POST['host'],null);
	$base = check($_POST['base'],null);
	$user = check($_POST['user'],null);
	$pass = check($_POST['pass'],null);
	$name = check($_POST['name'],null);
	$password = check($_POST['password'],null);
	$email = check($_POST['email'],null);

	if (empty($host) or empty($base) or empty($user) or empty($pass) or empty($name) or empty($password)) {
		exit(json_encode(array('status' => '2', 'data' => 'Заполните все поля.')));
	}

	if (!is_writable('../../inc/db.php')) {
		exit(json_encode(array('status' => '2', 'data' => 'Файл inc/db.php недоступен для записи!')));
	}
	
	if (!is_writable('../../files/temp/temp.txt')) {
		exit(json_encode(array('status' => '2', 'data' => 'Файл files/temp/temp.txt недоступен для записи!')));
	}
	$sqli = new mysqli($host, $user, $pass, $base);
	$pdo = db_connect($host, $base, $user, $pass);
	
	if($sqli->connect_errno) {
		exit(json_encode(array('status' => 2, 'data' => 'Ошибка подключения к базе данных')));
	}

	mysqli_set_charset($sqli, "utf8");
	
	$U = new Users;

	$salt = crate_pass(10, 2);
	$code = crate_pass(10, 2);
	$password = $U->convert_password($password, $salt);
	
	$d = file_get_contents("{$_SERVER['DOCUMENT_ROOT']}/modules/install/base.sql");
		
	$d = str_replace("{name}", $name, $d);
	$d = str_replace("{password}", $password, $d);
	$d = str_replace("{email}", $email, $d);
	$d = str_replace("{salt}", $salt, $d);
	$d = str_replace("{code}", $code, $d);
	
	$sqli->multi_query($d);
	$pdo->exec("set names utf8");
	ini_set('max_execution_time', 1200);
	ignore_user_abort(1);
	set_time_limit(0);
	sleep(60);
	
	if(!$sqli->query("UPDATE `config` SET `password`='{$password}', `name`='{$name}', `salt`='{$salt}', `code`='{$code}', `email`='{$email}' WHERE `id`='1'")) {
		if(!$pdo->query("UPDATE `config` SET `password`='{$password}', `name`='{$name}', `salt`='{$salt}', `code`='{$code}', `email`='{$email}' WHERE `id`='1'")) {
			exit(json_encode(array('status' => 2, 'data' => 'База данных не успела импортироваться, нажми еще раз "Установка"')));
		}
	}
	
	$b64 = base64_decode("PD9waHAKCSRkYlsiaG9zdCJdID0gIntob3N0bmFtZX0iOwoJJGRiWyJuYW1lIl0gPSAie2RhdGFiYXNlfSI7CgkkZGJbInVzZXIiXSA9ICJ7dXNlcm5hbWV9IjsKCSRkYlsicGFzc3dvcmQiXSA9ICJ7cGFzc3dvcmR9IjsKCgl0cnkgewoJCSRwZG8gPSBuZXcgUERPKCJteXNxbDpob3N0PSIuJGRiWyJob3N0Il0uIjtkYm5hbWU9Ii4kZGJbIm5hbWUiXSwgJGRiWyJ1c2VyIl0sICRkYlsicGFzc3dvcmQiXSk7CgkJJHBkby0+c2V0QXR0cmlidXRlKCBQRE86OkFUVFJfRVJSTU9ERSwgUERPOjpFUlJNT0RFX0VYQ0VQVElPTiApOwoJCSRwZG8tPmV4ZWMoInNldCBuYW1lcyB1dGY4Iik7IAoJfQoJY2F0Y2goUERPRXhjZXB0aW9uICRlKSB7CgkJZmlsZV9wdXRfY29udGVudHMoJF9TRVJWRVJbIkRPQ1VNRU5UX1JPT1QiXS4iL2xvZ3MvcGRvX2Vycm9ycy50eHQiLCAiWyIuZGF0ZSgiWS1tLWQgSDppOnMiKS4iXSA6IFsiLiRlLT5nZXRNZXNzYWdlKCkuIl1cclxuIiwgRklMRV9BUFBFTkQpOwoJCWV4aXQoItCe0YjQuNCx0LrQsCDQv9C+0LTQutC70Y7Rh9C10L3QuNGPINC6INCx0LDQt9C1INC00LDQvdC90YvRhS4iKTsKCX0KCQoJcmVxdWlyZSgieyRfU0VSVkVSWydET0NVTUVOVF9ST09UJ119L2luYy9kYjEucGhwIik7Cg==");
	$b64 = str_replace('{hostname}', $host, $b64);
	$b64 = str_replace('{username}', $user, $b64);
	$b64 = str_replace('{database}', $base, $b64);
	$b64 = str_replace('{password}', $pass, $b64);
	
	if(file_put_contents("{$_SERVER['DOCUMENT_ROOT']}/inc/db.php", $b64)) {
		exit(json_encode(array('status' => 1, 'data' => 'Установка успешно завершена!')));
	}
	
	exit(json_encode(array('status' => 2, 'data' => 'Неизвестная ошибка..')));
}