<?php
if (isset($_POST['install_module'])){
	$install_module = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['install_module'])))));
} else $install_module = 0;
if (isset($_POST['update_module'])){
	$update_module = addslashes(trim(strip_tags(stripslashes(rawurldecode($_POST['update_module'])))));
} else $update_module = 0;

if ($install_module OR $update_module){
	$channel = 'staging';
	$use_module = NULL;
	if ($install_module) $use_module = $install_module;
	if ($update_module) $use_module = $update_module;
	
	$response = remote_call('https://update.comator.org/update.php?domain='.$_SERVER['SERVER_NAME'].'&channel='.$channel.'&module='.$use_module);
	
	$downloaded = false;
	$current_version = 0;
	if ($use_module == 'core' && is_file('version.txt')){
		$fh = fopen('version.txt', 'r');
		while ($line = fgets($fh)) {
			if ($line) $current_version = trim($line);
		}
		fclose($fh);
	} else if (is_file('modules/'.$use_module.'/version.txt')) {
		$fh = fopen('modules/'.$use_module.'/version.txt', 'r');
		while ($line = fgets($fh)) {
			if ($line) $current_version = trim($line);
		}
		fclose($fh);				
	}
	
	$current_version = convertToVersion($current_version);
	
	if (isset($response->module)){
		$response_module = $response->module;
		if (isset($response_module->$use_module)){
			$headers = get_headers($response_module->$use_module->path);
			if (substr($headers[0], 9, 3) == '200'){
				
				if (!is_dir('module_manager')) mkdir('module_manager');
				$update_file = file_get_contents($response_module->$use_module->path);
				$handle = fopen('module_manager/'.$use_module.'.zip', 'w');
				if (fwrite($handle, $update_file)) {
					fclose($handle);
					$downloaded = true;
				}
			}
		}
	}
	
	if ($downloaded === true){
		$zip_complete = false;
		$zip = new ZipArchive;
		$zip->open('module_manager/'.$use_module.'.zip');
		$zip->extractTo('../');
		$zip->close();
		unlink('module_manager/'.$use_module.'.zip');
		rmdir('module_manager');
		$zip_complete = true;
	}
	if ($zip_complete === true){
		$files = array_diff(scandir('databases'), array('.', '..'));
		foreach ($files AS $file) {
			if ($install_module && str_ends_with($file, '_setup.php')){
				update_database('databases/'.$file, $db['dbname'], $current_version);
			} else if (str_ends_with($file, '_update.php')){
				update_database('databases/'.$file, $db['dbname'], $current_version);
			} else {
				if (is_file('databases/'.$file)) unlink('databases/'.$file);
			}
		}
		rmdir('databases');
		if (is_dir('deletes')){
			$files = array_diff(scandir('deletes'), array('.', '..'));
			foreach ($files AS $file) {
				if (is_file('deletes/'.$file)){
					include('deletes/'.$file);
					if (isset($delete_file) && $delete_file){
						foreach ($delete_file AS $version => $deletes){
							if ($version > $current_version OR $version == 0){
								foreach ($deletes AS $delete){
									if (is_file('../'.$delete)) unlink('../'.$delete);
								}
							}
						}
					}
					unlink('deletes/'.$file);
				}
			}
			rmdir('deletes');
		}
		
		if (is_dir('scripts')){
			$files = array_diff(scandir('scripts'), array('.', '..'));
			foreach ($files AS $file) {
				if (is_file('scripts/'.$file)){
					include('scripts/'.$file);
					unlink('scripts/'.$file);
				}
			}
			rmdir('scripts');
		}
		
		$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)));
	
		
	}
}

print "
<input type='hidden' name='install_module' value='0' />
<input type='hidden' name='update_module' value='0' />";


function update_database($file, $dbname, $current_version = 0){
	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){
					if (version_compare(convertToVersion($version), $current_version, '>')){
						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){
					if (version_compare(convertToVersion($version), $current_version, '>')){
						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){
					if (version_compare(convertToVersion($version), $current_version, '>')){
						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){
					if (version_compare(convertToVersion($version), $current_version, '>')){
						foreach ($update AS $key => $value){
							if (check_table($key))	$conn->prepare($value)->execute();
						}
					}
				}
			}
			unlink($file);
		}
	}
}

function convertToVersion($version) {
	if (is_numeric($version)) {
		return "0.0." . $version;
   }
   return $version;
}