<?php
ini_set('display_errors','1');
error_reporting (E_ALL);
session_start();
setlocale (LC_ALL, 'de_DE');
setlocale (LC_TIME, 'de_DE');
header('Content-Type: text/html; charset=utf-8');
include('includes/function/database.php');
include('includes/function/helper.php');
if ($_SERVER['SERVER_NAME'] == 'update.comator.org'){
	exit();
	die();
}

$host = 'localhost';
$dbname = NULL;
$user = NULL;
$pass = NULL;
$error = NULL;

if (isset($_POST['install'])){
	$host = trim($_POST['host'] ?? '');
	$dbname = trim($_POST['dbname'] ?? '');
	$user = trim($_POST['user'] ?? '');
	$pass = trim($_POST['pass'] ?? '');
	
	if (!$host OR !$dbname OR !$user OR !$pass) {
		$error = "Please fill the required fields";
	}
	
	if (!$error){
		if (is_file('dbopen.php')) unlink('dbopen.php');
		$db['host'] = $host;
		$db['dbname'] = $dbname;
		$db['user'] = $user;
		$db['pass'] = $pass;
		$conn = database_connect($db);
		if ($conn == NULL) {
			$error = "Database connection not possible";
		} else {
			$config_dir = __DIR__.'/config';
			if (!is_dir($config_dir)) mkdir($config_dir, 0755, true);
			
			$config_path = $config_dir . '/config.ini';
			
			$ini = "[database]\n";
			$ini .= "host = \"{$host}\"\n";
			$ini .= "dbname = \"{$dbname}\"\n";
			$ini .= "user = \"{$user}\"\n";
			$ini .= "pass = \"{$pass}\"\n";
			
			file_put_contents($config_path, $ini);
			
			$dbopen_data = "<?php\n";
			$dbopen_data .= "\$config = parse_ini_file(__DIR__.'/config/config.ini', true);\n";
			$dbopen_data .= "\$db['host'] = \$config['database']['host'];\n";
			$dbopen_data .= "\$db['dbname'] = \$config['database']['dbname'];\n";
			$dbopen_data .= "\$db['user'] = \$config['database']['user'];\n";
			$dbopen_data .= "\$db['pass'] = \$config['database']['pass'];\n";
			file_put_contents(__DIR__ . '/dbopen.php', $dbopen_data);
			
			include('dbopen.php');
			$conn = database_connect($db);
			if ($conn == NULL) {
				unlink('dbopen.php');
				$error = "Database connection save error";
			}
		}
	}
	
	if (!$error && $conn != NULL) {
		install_database('databases/core_setup.php', $dbname);
		$files = array_diff(scandir('databases'), array('.', '..'));
		foreach ($files AS $file) {
			if ($file != 'core_setup.php') install_database('databases/'.$file, $dbname);
		}
		rmdir('databases');
		$installed_modules = array();
		$installed_modules['core'] = NULL;
		
		if (is_file('version.txt')){
			$fh = fopen('version.txt', 'r');
			while ($line = fgets($fh)) {
				if ($line) $installed_modules['core'] = trim($line);
			}
			fclose($fh);
		}
		
		if (is_dir('modules')){
			$dirs = array_diff(scandir('modules'), array('.', '..'));
			foreach ($dirs AS $dir){
				if (is_dir('modules/'.$dir) && is_file('modules/'.$dir.'/version.txt')){
					$fh = fopen('modules/'.$dir.'/version.txt', 'r');
					while ($line = fgets($fh)) {
						if ($line) $installed_modules[$dir] = trim($line);
					}
					fclose($fh);
				}
			}
		}
		
		$domain = $_SERVER['SERVER_NAME'];
		
		$payload = array(
			'domain'  => $domain,
			'modules' => $installed_modules
		);
		
		remote_call('https://admin.comator.org/report.php?data='.urlencode(json_encode($payload)));
		
		
		unlink('setup.php');
		header('Location: /comator/index.php?module=content&backend_module=content');
	}
	
}

function install_database($file, $dbname){
	global $conn;
	$db_data = array();
	$db_update = array();
	if (is_file($file)){
		include($file);
		if (isset($db_data['structure'])){
			foreach ($db_data['structure'] AS $key => $value){
				if (!check_table($key))	$conn->prepare($value)->execute();
			}
			if (isset($db_data['indizies'])){
				foreach ($db_data['indizies'] AS $key => $value){
					if (check_table($key)) {
						$sql_check = "SELECT * FROM information_schema.columns WHERE table_schema = :table_schema AND table_name = :table_name AND column_key = 'PRI';";
						$result = $conn->prepare($sql_check);
						$result->bindValue(':table_schema', $dbname, PDO::PARAM_STR);
						$result->bindValue(':table_name', $key, PDO::PARAM_STR);
						$result->execute();
						if (!$result->rowCount())$conn->prepare($value)->execute();
					}
				}
			}
			if (isset($db_data['increment'])){
				foreach ($db_data['increment'] AS $key => $value){
					if (check_table($key)) $conn->prepare($value)->execute();
				}
			}
			if (isset($db_data['data'])){
				foreach ($db_data['data'] AS $key => $value){
					if (check_table($key)) $conn->prepare($value)->execute();
				}
			}
			unlink($file);
		}
		if (isset($db_update) && $db_update){
			if (isset($db_update['structure'])){
				foreach ($db_update['structure'] AS $version => $update){
					foreach ($update AS $key => $value){
						if (!check_table($key))	$conn->prepare($value)->execute();
					}
				}
			}
			if (isset($db_update['indizies'])){
				foreach ($db_update['indizies'] AS $version => $update){
					foreach ($update AS $key => $value){
						if (check_table($key)) {
							$sql_check = "SELECT * FROM information_schema.columns WHERE table_schema = :table_schema AND table_name = :table_name AND column_key = 'PRI';";
							$result = $conn->prepare($sql_check);
							$result->bindValue(':table_schema', $dbname, PDO::PARAM_STR);
							$result->bindValue(':table_name', $key, PDO::PARAM_STR);
							$result->execute();
							if (!$result->rowCount())$conn->prepare($value)->execute();
						}
					}
				}
			}
			if (isset($db_update['increment'])){
				foreach ($db_update['increment'] AS $version => $update){
					foreach ($update AS $key => $value){
						if (check_table($key))	$conn->prepare($value)->execute();
					}
				}
			}
			if (isset($db_update['data'])){
				foreach ($db_update['data'] AS $version => $update){
					foreach ($update AS $key => $value){
						if (check_table($key))	$conn->prepare($value)->execute();
					}
				}
			}
			unlink($file);
		}
	}
}

?>
<!DOCTYPE html>
<html lang='de'>	
	<head>
		<meta charset='utf-8' />
		<title>Comator &middot; Setup</title>
		
		<link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-touch-icon.png">
		<link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png">
		<link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png">
		<link rel="manifest" href="images/favicon/site.webmanifest">
		<link rel="mask-icon" href="images/favicon/safari-pinned-tab.svg" color="#5bbad5">
		<link rel="shortcut icon" href="images/favicon/favicon.ico">
		<meta name="msapplication-TileColor" content="#da532c">
		<meta name="msapplication-config" content="images/favicon/browserconfig.xml">
		<meta name="theme-color" content="#ffffff">
		
		<!-- Vendor Styles -->
	
		<!-- App Styles -->
		<link rel='stylesheet' href='css/treeselect.css' />
		<link rel='stylesheet' href='css/fancybox.min.css' />
		<link rel='stylesheet' href='css/jquery-ui-1.13.2.min.css' />
		<link rel='stylesheet' href='css/fonts.css' />
		<link rel='stylesheet' href='css/style.css' />
	
		<!-- Vendor JS -->
		<script type="text/javascript" src="js/jquery-3.7.1.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.13.2.min.js"></script>
		<script type="text/javascript" src="js/treeselect.min.js"></script>
		<script type="text/javascript" src="js/fancybox.min.js"></script>
		<script type="text/javascript" src="js/uploader/jquery.ui.widget.js"></script>
	  <script type="text/javascript" src="js/ace/ace.js" charset="utf-8"></script>
	  <script type="text/javascript" src="js/ace/ext-language_tools.js" charset="utf-8"></script>
	  <script type="text/javascript" src="js/tinymce/tinymce.min.js"></script>
		<script type="text/javascript" src="js/uploader/jquery.iframe-transport.js"></script>
		<script type="text/javascript" src="js/uploader/jquery.fileupload.js"></script>
		<script type="text/javascript" src="js/uploader/jquery.fileupload-process.js"></script>
	
		<!-- App JS -->
		<script type="text/javascript" src="js/defaults.js"></script>
		<script type="text/javascript" src="js/toggle.js"></script>
		<script type="text/javascript" src="js/upload.js"></script>
		<script type="text/javascript" src="js/editor.js"></script>
		<script type="text/javascript" src="js/functions.js"></script>
	</head>
	<body class='dragging'>
		<div class='wrapper'>
			<header class='header'>
				<div class='header-inner'>
					<div class='mobile-nav'>
						<i class='material-icons md-24'>menu</i>
					</div>
					<div class='header-logo'>
						<img src='images/logo.png' />
					</div><!-- /.head-logo -->
				</div><!-- /.header-inner -->
			</header><!-- /.header -->
			
			<div class='container login'>
				<div class='form'>
					<div class='form-head'><i class='material-icons md-24'>widgets</i>Setup</div>
					<div class='form-content'>
						<form action='setup.php' method='post' enctype='multipart/form-data'>
							
							<div class='form-row'>
								<label for='host' class='form-label'>* MySQL IP/Hostname</label>
								<div class='form-cols'>
									<div class='form-col form-full'>
										<div class='form-controls'>
											<input type='text' class='field' id='host' name='host' value='<?=$host;?>'>
										</div><!-- /.form-controls -->
									</div><!-- /.form-col -->
								</div><!-- /.form-cols -->
							</div><!-- /.form-row -->
							
							<div class='form-row'>
								<label for='dbname' class='form-label'>* MySQL Database</label>
								<div class='form-cols'>
									<div class='form-col form-full'>
										<div class='form-controls'>
											<input type='text' class='field' id='dbname' name='dbname' value='<?=$dbname;?>'>
										</div><!-- /.form-controls -->
									</div><!-- /.form-col -->
								</div><!-- /.form-cols -->
							</div><!-- /.form-row -->
							
							<div class='form-row'>
								<label for='user' class='form-label'>* MySQL Username</label>
								<div class='form-cols'>
									<div class='form-col form-full'>
										<div class='form-controls'>
											<input type='text' class='field' id='user' name='user' value='<?=$user;?>'>
										</div><!-- /.form-controls -->
									</div><!-- /.form-col -->
								</div><!-- /.form-cols -->
							</div><!-- /.form-row -->
							
							<div class='form-row'>
								<label for='pass' class='form-label'>* MySQL Password</label>
								<div class='form-cols'>
									<div class='form-col form-full'>
										<div class='form-controls'>
											<input type='password' class='field' id='pass' name='pass' value=''>
										</div><!-- /.form-controls -->
									</div><!-- /.form-col -->
								</div><!-- /.form-cols -->
							</div><!-- /.form-row -->
							
							<hr/>
<?php
if (isset($error) && $error){
	print "
				<div class='alert error'>
					<strong>Error</strong>
					".$error."
				</div>
				
				<hr/>";
}
?>				
							<div class='form-action'>
								<button type='submit' class='btn login' name='install' title='Install'><i class='material-icons md-24'>send</i>Install</button>
							</div><!-- /.form-action -->
							
						</form>
					</div><!-- /.form-content -->
				</div><!-- /.form -->
				 
			</div><!-- /.container -->
		</div><!-- /.wrapper -->
	</body>
</html>