<?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(['status' => '2', 'data' => 'Ошибка: [Прямой вызов исполнителя]']));
}

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

set_error_handler(
	function($errno, $errstr) {
		throw new Exception($errstr, $errno);
	}
);

function checkDataBaseConnectionSettings($host, $base, $user, $pass) {
	foreach([$host, $base, $user, $pass] as $item) {
		if(!(stristr($item, '"') === false && stristr($item, '\\') === false)) {
			return ['status' => 2, 'data' => 'Данные для подключения к базе не должны содержать " и \\.'];
		}
	}

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

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

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

	exit(json_encode(checkDataBaseConnectionSettings($host, $base, $user, $pass)));
}

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

	try {
		$dbConnectionResult = checkDataBaseConnectionSettings($host, $base, $user, $pass);

		if($dbConnectionResult['status'] === 1) {
			$pdo = $dbConnectionResult['pdo'];
		} else {
			exit(json_encode($dbConnectionResult));
		}

		if(!is_writable(__DIR__ . '/../../inc/db.php')) {
			exit(json_encode(['status' => 2, 'data' => 'Файл inc/db.php недоступен для записи!']));
		}

		if(!is_writable(__DIR__ . '/../../files/temp/temp.txt')) {
			exit(json_encode(['status' => 2, 'data' => 'Файл files/temp/temp.txt недоступен для записи!']));
		}

		$U = new Users;

		$salt     = crate_pass(10, 2);
		$code     = crate_pass(10, 2);
		$secret   = crate_pass(10, 2);
		$password = $U->convert_password($password, $salt);

		pdo()->exec("set names utf8");
		pdo()->exec(trim(file_get_contents(__DIR__ . '/base.sql')));

		pdo()->prepare("UPDATE config SET name=:name, password=:password, salt=:salt, code=:code, secret=:secret WHERE id='1' LIMIT 1")
			->execute(['name' => $name, 'password' => $password, 'salt' => $salt, 'code' => $code, 'secret' => $secret]);

		file_put_contents(
			__DIR__ . '/../../inc/db.php',
			'<?php
$db["host"] = "' . $host . '";
$db["name"] = "' . $base . '";
$db["user"] = "' . $user . '";
$db["password"] = "' . $pass . '";
$db["charset"] = "utf8";

try {
	$pdo = new PDO("mysql:host=".$db["host"].";dbname=".$db["name"], $db["user"], $db["password"]);
	$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
	$pdo->exec("set names " . $db["charset"]);
} catch(PDOException $e) {
	exit("Ошибка подключения к базе данных");
}
unset($db);

$STH = $pdo->query("SELECT * FROM config LIMIT 1"); $STH->setFetchMode(PDO::FETCH_OBJ);
$conf = $STH->fetch();'
		);

	} catch(Exception $exception) {
		exit(json_encode(['status' => 2, 'data' => 'Произошла ошибка: ' . $exception->getMessage()]));
	}

	removeDirectory(__DIR__ . '/../install/');

	exit(json_encode(['status' => 1, 'data' => 'Установка успешно завершена!']));
}