<?php
	
	namespace AutoInstall\Controllers;
	
	use AutoInstall\Core\Controller;
	use AutoInstall\Services\VariablesService;
	use Verot\Upload\Upload;
	
	class InstallerController extends Controller
	{
		public function index()
		{
			ob_start();
			include '../public/assets/index.html';
			$html_content = ob_get_contents();
			ob_end_clean();
			
			// Replace CSRF Token and LeaderOS License Location
			$html_content = str_replace(
				[
					'REPLACE_CSRF_TOKEN',
					'REPLACE_LEADEROS_LOCATION'
				],
				[
					csrf_token(),
					LOCATION
				],
				$html_content
			);
			
			echo $html_content;
		}
		
		public function languages()
		{
			response()->json(VariablesService::$languages);
		}
		
		public function admin()
		{
			validate([
				'loginProvider' => 'required',
				'accountUsername' => 'required',
				'accountRealname' => 'required',
				'accountEmail' => 'required_if:loginProvider,default|email',
				'accountPassword' => 'required_if:loginProvider,default|min:4',
				'accountPasswordRe' => 'required_if:loginProvider,default|same:accountPassword',
			]);
			
			include __ROOT__.'/apps/main/app/config/connect.php';
			
			$usernameValid = $db->prepare("SELECT * FROM Accounts WHERE username = ?");
			$usernameValid->execute(array(input("accountUsername")));
			if ($usernameValid->rowCount() > 0) {
				response()->json([
					'success' => false,
					'errors'  => [
						'username_taken',
					]
				]);
			}
			
			if (input('accountEmail') != null) {
				$emailValid = $db->prepare("SELECT * FROM Accounts WHERE email = ?");
				$emailValid->execute(array(input("accountEmail")));
				if ($emailValid->rowCount() > 0) {
					response()->json([
						'success' => false,
						'errors'  => [
							'email_taken',
						]
					]);
				}
			}
			
			response()->json([
				'success' => true,
			]);
		}
		
		public function run()
		{
			include __ROOT__.'/apps/main/app/config/connect.php';
			
			if (input('accountPassword') == null) {
				$password = null;
			} else {
				$password = createSHA256(input("accountPassword"));
			}
			
			$insertAccounts = $db->prepare("INSERT INTO Accounts (username, realname, email, password, creationIP, creationDate) VALUES (?, ?, ?, ?, ?, ?)");
			$insertAccounts->execute(array(input("accountUsername"), input("accountRealname"), input("accountEmail"), $password, getIP(), date("Y-m-d H:i:s")));
			$accountID = $db->lastInsertId();
			
			// Avatar
			if (input('accountAvatar') != null) {
				// Get the avatar from link
				$avatarData = file_get_contents(input('accountAvatar'));
				
				$upload = new Upload('data:' . $avatarData);
				$imageID = md5(uniqid(rand(0, 9999999)));
				if ($upload->uploaded) {
					$upload->allowed = ["image/png", "image/gif", "image/jpg", "image/jpeg"];
					$upload->file_new_name_body = $imageID;
					$upload->image_resize = true;
					$upload->image_ratio_crop = true;
					$upload->image_x = 256;
					$upload->image_y = 256;
					$upload->process(__ROOT__ . "/apps/main/public/images/avatars/");
					if ($upload->processed) {
						$imageType = $upload->file_dst_name_ext;
						
						$insertAvatar = $db->prepare("INSERT INTO Avatars (accountID, imageID, imageType) VALUES (?, ?, ?)");
						$insertAvatar->execute(array($accountID, $imageID, $imageType));
					}
				}
			}
			
			$addRoleToAccount = $db->prepare("INSERT INTO AccountRoles (accountID, roleID) VALUES (?, ?)");
			$addRoleToAccount->execute(array($accountID, 2));
			
			if (isset($_COOKIE["rememberMe"])) {
				setcookie("rememberMe", "", time()-86400*365, '/');
			}
			
			$settings = [
				'autoInstallation' => 'COMPLETED',
				'apiStatus' => '1',
				'apiKey' => input("apiKey"),
				'gameType' => input("game"),
				'loginProvider' => input("loginProvider"),
			];
			foreach ($settings as $key => $value) {
				$updateSettings = $db->prepare("UPDATE Settings SET `value` = ? WHERE name = ?");
				$updateSettings->execute(array($value, $key));
			}

			response()->json([
				'success' => true,
			]);
		}
	}