<?php
	require_once "pageBase.php";
	require_once "../class/class.php";
	require_once "../../bin/system/conver.php";
	require_once "../../dal/registryDAL.php";
	
	class _version extends pageBase {
		private array $aryJ;
		private string $versionDir;

		public function __construct() {
			$this->aryJ = ["err" => "0", "msg" => ""];
			$this->versionDir = "../../" . str_replace(".", "_", $_SESSION["version"]);
		}

		public function load(): void {
			$this->aryJ["msg"] = "";

			$action = parent::getPost("do");
			switch ($action) {
				case "chk":
					$this->checkversion();
					break;
				case "down":
					$this->download();
					break;
				default:
					$this->handleError("操作異常！請重新整理頁面再試一次！", "1");
			}
		
			if ($this->aryJ["msg"] !== "") $this->aryJ["msg"] = urlencode($this->aryJ["msg"]);
			echo urldecode(json_encode($this->aryJ));
			parent::load();
		}
		
		private function handleError(string $errorMessage, int $errorStatus = 0): void {
			if ($errorStatus !== 0) $this->aryJ["err"] = $errorStatus;
			$this->aryJ["msg"] = $errorMessage;
		}
		
		private function checkversion(){
			$nowTime = time();
			$url = "https://tp60.appleseotw.com/apple/vault/update/download";
			$data = ['ver' => registryDAL::getRegistryValue("Version")];
	
			$result = $this->fetchURLContent($url, $data);
			$obj = json_decode($result);
	
			if ($obj->status == "0") {
				$numChar = new NumChar($nowTime);
				$numChar->chgChar();
	
				if ($obj->zip != "") {
					$result2 = $this->fetchURLContent($obj->zip);
					file_put_contents("../zipflash/update.zip", $result2);
	
					if (file_exists("../zipflash/update.zip")) {
						$this->extractAndUpdate("../zipflash/update.zip", $numChar->output, $obj->version);
					} else {
						$this->handleError("下載檔案失敗!", "1");
					}
				}
			} else {
				$this->handleError($obj->message, $obj->status);
			}
		}
		
		public function download(){
			if (is_dir($this->versionDir)) {
				$t = "";
				$txt = $this->getDir($this->versionDir, $t);
				
				//文字檔記錄
				$txtLog = "=============================================================================" . PHP_EOL .
					"時間: " . date("Y-m-d H:i:s") . PHP_EOL .
					"版本: " . $_SESSION["version"] . PHP_EOL .
					"更新內容: " . PHP_EOL . $txt . PHP_EOL;
					
				file_put_contents('../changelog.txt', $txtLog, FILE_APPEND);
				
				$this->rrmdir($this->versionDir);
				
				registryDAL::saveRegistry("Version", $_SESSION["version"]);
				registryDAL::saveRegistry("ModifiedTime", time());
				
				unset($_SESSION["version"]);
				
				$this->handleError("更新成功!");
			} else {
				$this->handleError("錯誤!更新檔遺失!", "1");
			}
		}
		
		private function fetchURLContent($url, $data = null) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
			curl_setopt($ch, CURLOPT_HEADER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
			if ($data !== null) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			}
	
			$result = curl_exec($ch);
			curl_close($ch);
			return $result;
		}
	
		private function extractAndUpdate($zipPath, $password, $newVersion) {
			$zip = new ZipArchive();
			$rez = $zip->open($zipPath);
	
			if ($rez === true) {
				$zip->setPassword($password);
				$zip->extractTo('../..');
				$zip->close();
				unlink($zipPath);
	
				$_SESSION["version"] = $newVersion;
			}
		}

		// 取得目錄及檔案
		public function getDir($path, &$txt): string {
			$dir = scandir($path);
	
			foreach ($dir as $value) {
				if ($value != "." && $value != "..") {
					$subPath = $path . '/' . $value;
					$oldFile = str_replace($this->versionDir, '../..', $subPath);
					$back = "." . date("Ymd") . ".system";
	
					if (is_dir($subPath)) {
						if (!is_dir($oldFile)) {
							$this->createDir($oldFile);
							$txt .= $subPath . " >>> 目錄新增成功" . PHP_EOL;
						}
						$this->getDir($subPath, $txt);
					} else {
						if ($this->moveFile($oldFile, $oldFile . $back)) {
							$txt .= $oldFile . " >>> " . $oldFile . $back . " 變更成功" . PHP_EOL;
						}
						$txt .= $this->moveFile($subPath, $oldFile) ?
							($subPath . " >>> " . $oldFile . " 移動成功" . PHP_EOL) :
							($subPath . " >>> 移動失敗" . PHP_EOL);
					}
				}
			}
			return $txt;
		}
		
		// 建立目錄
		private function createDir($dir): bool {
			return mkdir($dir, 0777, true);
		}

		//變更檔名/移動目錄
		private function moveFile($source, $destination): bool {
			if (file_exists($source)) return rename($source, $destination);
			return false;
		}

		//移除目錄
		public function rrmdir($dir) {
			if (is_dir($dir)) {
				$objects = scandir($dir);
				foreach ($objects as $object) {
					if ($object != "." && $object != "..") {
						if (filetype($dir . "/" . $object) == "dir") {
							$this->rrmdir($dir . "/" . $object);
						} else {
							unlink($dir . "/" . $object);
						}
					}
				}
				reset($objects);
				rmdir($dir);
			}
		}
	}

	$page = new _version();
	$page->load();
?>