<?php
// Read timezone DB
	$timezone = [];
	$file = fopen("data/timezone.csv","r");
	while(! feof($file)){
		$tmp = fgetcsv($file);
		//print_r($tmp);
		array_push($timezone,array($tmp[0],$tmp[1],$tmp[2]));
	}
	fclose($file);
// END

if($_GET["opr"] == "query"){
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
		$result["f_timezone"] = exec("tzutil /g");
		foreach ($timezone as $tz) {
			if($tz[2] == $result["f_timezone"]){
				$result["timezone"] = $tz[1];
			}
		}	
		$result["fulltime"] = exec('getTime.exe');
		$result["time"] =  explode(" ",exec('getTime.exe'))[1]." ".explode(" ",exec('getTime.exe'))[2];
	}else{
		$result["timezone"] = exec("cat /etc/timezone");
		foreach ($timezone as $tz) {
			if($tz[1] == $result["timezone"]){
				$result["f_timezone"] = $tz[2];
			}
		}
		$result["fulltime"] = exec('date +"%a %Y-%m-%d %T %Z %z"');
		$result["time"] = exec('date +"%Y-%m-%d %T"');
	}
	echo json_encode($result);
}else if($_GET["opr"] == "alltimezone"){
	echo json_encode($timezone);
}else if($_GET["opr"] == "modify"){
	if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){
		$tz_win = "";
		foreach ($timezone as $tz) {
			if($tz[1] == $_GET["tz"]){
				$tz_win = $tz[2];
			}
		}
		exec('tzutil /s "'.$tz_win.'"');
		echo "Finish";
	}else{
		//exec("sudo chmod -R 0777 /etc/systemd/timesyncd.conf");
		exec("sudo timedatectl set-timezone '".$_GET["tz"]."'");
		echo "Finish";
	}
}
?>