<?php
	require_once dirname(__FILE__) . "/../bin/data/databaseFactory.php";
	class registryDAL {
		static private array $registry;
	
		// 讀取網站配置表值
		static public function getRegistryValue($name): ?string {
			if (!isset(self::$registry)) self::$registry = self::getRegistryValues();
			return self::$registry[$name] ?? null;
		}

		// 讀取網站配置表值，以陣列形式返回；Name為鍵，Value為值
		static public function getRegistryValues(): array {
			$returnValue = [];
			$data = databaseFactory::createDatabase();
			$sql = "SELECT * FROM `registry`";
			$rs = $data->executeRecordset($sql, [], 0, -1);
			foreach ($rs as $arr) {
				$returnValue[$arr["Name"]] = $arr["Value"];
			}
			return $returnValue;
		}

		// 儲存網站配置表。如果已經存在該項，則更新；否則新增
		static public function saveRegistry($name, $value): void {
			$intoAry = [];
			$intoAry[] = ["Name" => ":name", "Value" => $name, "Type" => "str", "Number" => 255];
			
			$data = databaseFactory::createDatabase();
			$sqlCount = "SELECT COUNT(*) FROM `registry` WHERE `Name`=:name";
			$count = $data->executeScalar($sqlCount, $intoAry);
			
			$sql = ($count > 0) ? "UPDATE `registry` SET `Value`=:value WHERE `Name`=:name" : "INSERT INTO `registry` (`Name`, `Value`) VALUES (:name, :value)";
		
			$intoAry[] = ["Name" => ":value", "Value" => $value, "Type" => "str"];
			$data->executeNonQuery($sql, $intoAry, true);
		}
	}
?>