<?php
	namespace Main\Services;
	
	class PasswordService
	{
		public static function match($password, $hash): bool
		{
			$type = settings('passwordType');
			
			// SHA256
			if ($type == 1)
				return self::checkSHA256($password, $hash);
			
			// MD5
			if ($type == 2)
				return md5($password) == $hash;
			
			// BCRYPT
			if ($type == 3)
				return password_verify($password, $hash);
			
			return false;
		}
		
		public static function hash($password)
		{
			$type = settings('passwordType');
			
			// SHA256
			if ($type == 1)
				return self::createSHA256($password);
			
			// MD5
			if ($type == 2)
				return md5($password);
			
			// BCRYPT
			if ($type == 3)
				return password_hash($password, PASSWORD_BCRYPT);
			
			return null;
		}
		
		private static function generateSalt($length): string
		{
			$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$randomString = '';
			for ($i = 0; $i < $length; $i++) {
				$randomString .= $characters[rand(0, strlen($characters) - 1)];
			}
			
			return $randomString;
		}
		
		private static function createSHA256($password): string
		{
			$salt = self::generateSalt(16);
			
			return '$SHA$'.$salt.'$'.hash('sha256', hash('sha256', $password).$salt);
		}
		
		private static function checkSHA256($password, $realPassword): bool
		{
			$parts = explode('$', $realPassword);
			$salt = $parts[2];
			$hash = hash('sha256', hash('sha256', $password).$salt);
			$hash = '$SHA$'.$salt.'$'.$hash;
			
			return $hash == $realPassword;
		}
	}