<?php
/*--------------------------------------------------------- 
 * File:guid.php
 * Author:Tomix
 * Description: 
 * Created:2009
 * -------------------------------------------------------
 * Modified history:2023/08/22
 * Copyright © 2023 蘋果世界股份有限公司 版權所有
 * -------------------------------------------------------
 */
class guid {
	private string $value;

	public function __construct() {
        $computerName = isset($_ENV["COMPUTERNAME"]) ? $_ENV["COMPUTERNAME"] : "unknown";
        $serverAddr = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : "unknown";
        
        $address = strtolower($computerName . "/" . $serverAddr);
        
        [$usec, $sec] = explode(" ", microtime());
        $timeMillis = $sec . substr($usec, 2, 3);
        $tmp = rand(0, 1) ? '-' : '';
        $random = $tmp . rand(1000, 9999) . rand(1000, 9999) . rand(1000, 9999) . rand(100, 999) . rand(100, 999);
        $valueBeforeMD5 = $address . ":" . $timeMillis . ":" . $random;
        $this->value = md5($valueBeforeMD5);
	}

	public static function newGuid(): self {
		return new self();
	}

	public function toString(): string {
        $raw = strtolower($this->value);
        return substr($raw, 0, 8) . '-' . substr($raw, 8, 4) . '-' . substr($raw, 12, 4) . '-' . substr($raw, 16, 4) . '-' . substr($raw, 20);
    }
}
?>