<?php
	require_once "pageBase.php";
	require_once "../bin/system/conver.php";
	require_once "../bin/web/repeater.php";
	require_once "../dal/limitDAL.php";
	require_once "../dal/menuDAL.php";
	require_once "../dal/userDAL.php";

	class _userAdd extends pageBase{
		private $pUrl;
		private $dal;

		//覆蓋父類load()方法
		public function load(){
			if(!parent::chkUserLimit('14')){
				parent::alert2('您沒有使用此頁面的權限!如有疑問請洽主管理者!','index.php');
				exit;
			}

			$this->pUrl = urldecode(parent::getPageParameter("pUrl","userList.php"));
			$this->dal = new userDAL();

			if(!parent::isPostBack())
				$this->loadData();
			else
				$this->saveData();

			parent::load();
		}

		public function loadData(){
			//功能列表
			$dalM = new menuDAL();
			$menuList = "";
			$dataM1 = $dalM->executeRecordset("a.`ParentID`='0' AND a.`Visible`='1'","a.`OrderNO`");
			for($i=0;$i<count($dataM1);$i++){
				$menuList .= "<li>";
				$menuList .= "<input type=\"checkbox\" name=\"MenuID[]\" value=\"".$dataM1[$i]["MenuID"]."\">".$dataM1[$i]["MenuName"];
				$dataM2 = $dalM->executeRecordset("a.`ParentID`='".$dataM1[$i]["MenuID"]."' AND a.`Visible`='1'","a.`OrderNO`");
				if(count($dataM2) > 0){
					$menuList .= "<ul>";
					for($j=0;$j<count($dataM2);$j++){
						$menuList .= "<li><input type=\"checkbox\" name=\"MenuID[]\" value=\"".$dataM2[$j]["MenuID"]."\">".$dataM2[$j]["MenuName"]."</li>";
					}
					$menuList .= "</ul>";
				}
				$menuList .= "</li>";
			}
			parent::addParameter("menuList",$menuList);

			parent::addParameter("pUrl",$this->pUrl);
			parent::loadTemplateFile(dirname(__FILE__)."/templates/userAdd.html");

			//父類方法
			parent::loadData();
		}
		public function saveData(){
			$dalL = new limitDAL();
			$this->dal->LoginName = conver::toDbString(trim($_POST["LoginName"]));
			$this->dal->Password = conver::toDbString(trim($_POST["Password"]));
			$this->dal->UserName = conver::toDbString(trim($_POST["UserName"]));
			$this->dal->Email = conver::toDbString(trim($_POST["Email"]));
			$this->dal->Visible = 1;
			$this->dal->UserType = 64;
			$saved = false;
			$saved = $this->dal->insertRecord();
			if($saved === false){
				parent::alert("儲存時發生錯誤!");
			}else{
				$menuID = $_POST["MenuID"];
				if(is_array($menuID)){
					$dalL->UserID = $saved;
					for($i=0;$i<count($menuID);$i++){
						$dalL->MenuID = conver::toDbString(trim($menuID[$i]));
						$dalL->insertRecord();
					}
				}
				parent::redirect($this->pUrl);
			}
		}
	}

	$page = new _userAdd();
	$page->load();
	$page->render();
?>