<?php $root=$_SERVER['DOCUMENT_ROOT'];$wroot=dirname($_SERVER['SCRIPT_NAME']);while((strlen($wroot)>1)&&(!file_exists($root.$wroot.'/main')))	$wroot=dirname($wroot);if($wroot=='/')$wroot='';require_once($root.$wroot.'/main/app/App.php');
class GoogleAPI{
	function debug($variable){ob_start();var_dump($variable);file_put_contents('test.txt',ob_get_contents());ob_end_clean();}
	function createUserTable(){
		try{
			$this->app->db->query("create table googleUsers(
				id varchar(21),
				name varchar(64),
				email varchar(1023),
				uuid int
			);");
		} catch (Exception $ex){return false;}
		return true;
	}
	function createAppUser($name,$icon){
		$username=str_replace(' ','',$name);
		$usernamenumber='';while ($this->app->findUser($username.$usernamenumber))if ($usernamenumber==='')$usernamenumber=0;else $usernamenumber++;
		$username=$username.$usernamenumber;
		$pw='';for ($i=0;$i<16;$i++)$pw.=chr(rand(48,122));
		$hash=password_hash($pw,PASSWORD_DEFAULT);
		$this->app->addUser('social',$username,$hash);
		$img=$this->app->imageGDSquare($this->app->imageGDCreate($icon,'.png'),512);imagepng($img,$this->app->froot."/main/users/$username/avatar.png");imagedestroy($img);
		$user=$this->app->findUser($username);
		return $user;
	}
	function getUser($id){
		$response=$this->app->db->query("select * from googleUsers where id='$id';");
		if ($response->num_rows==0) return false;
		$user=$this->app->getUser($response->fetch_assoc()['uuid']);
		return $user;
	}
	function addUser($id,$name,$email,$icon){
		$this->app->db->query("insert into googleUsers(id,name,email,uuid) values('$id','$name','$email','{$this->app->user['uuid']}');");
		file_put_contents($this->app->froot."/main/users/{$this->app->user['user']}/$id.googleID","{id:\"$id\",name:\"$name\",email:\"$email\",icon:\"$icon\"}");
		$response=$this->app->db->query("select * from googleUsers where id='$id';");
		return $this->getUser($id);
	}
	function login($uuid){
		$this->app->user=$this->app->getUser($uuid);
		$this->app->setCookie('uid',$this->app->user['uuid']);
		$this->app->setCookie('hid',md5($this->app->user['hash']));
	}
	function sociallogin($id,$name,$email,$icon){
		$this->createUserTable();
		$social=$this->getUser($id);
		if ($social){
			if ($this->app->user){if ($this->app->user['uuid']!==$social['uuid']) $this->login($social['uuid']);}
			else $this->login($social['uuid']);
		}
		else{
			if (!$this->app->user){$user=$this->createAppUser($name,$icon);$this->login($user['uuid']);}
			$social=$this->addUser($id,$name,$email,$icon);
		}
		return json_encode($social);
	}
	function __construct(){
		global $app;
		$this->app=$app;
		if (isset($_POST['c'])){
			switch($_POST['c']){
				case 'sociallogin':
					echo $this->sociallogin($_POST['id'],$_POST['name'],$_POST['email'],$_POST['icon']);
					break;
				default:echo'[]';
			}
		}
	}
}
$app=new App($wroot);
$googleAPI=new GoogleAPI();
?>
