<?php
	require_once "pageBase.php";
	require_once "../dal/categoryDAL.php";
	require_once "../dal/productDAL.php";
	require_once "../bin/system/conver.php";

	class _productMultiAdd extends pageBase{
		private $cid,$pUrl;
		private $dal;

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

			$this->cid = parent::getPageParameter("cid","0");
			$this->pUrl = parent::getPageParameter("pUrl","productList.php");
			$this->dal = new productDAL();

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

			parent::load();
		}

		public function loadData(){
			//分類下拉JSON
			$dalC = new categoryDAL();
			$aryC = array();
			$aryC[0]["ID"] = "0";
			$aryC[0]["Name"] = urlencode("請選擇分類");
			$aryC[0]["Sub"] = array();
			$dataC1 = $dalC->executeRecordset("a.`ParentID`='0' AND a.`Visible`='1'");
			for($i=0;$i<count($dataC1);$i++){
				$aryC1 = array();
				$aryC1["ID"] = $dataC1[$i]["CategoryID"];
				$aryC1["Name"] = urlencode($dataC1[$i]["CategoryName"]);
				$aryC1["Sub"] = array();
				$dataC2 = $dalC->executeRecordset("a.`ParentID`='".$dataC1[$i]["CategoryID"]."' AND a.`Visible`='1'");
				for($j=0;$j<count($dataC2);$j++){
					$aryC2 = array();
					$aryC2["SubID"] = $dataC2[$j]["CategoryID"];
					$aryC2["SubName"] = urlencode($dataC2[$j]["CategoryName"]);
					$aryC1["Sub"][] = $aryC2;
				}
				$aryC[] = $aryC1;
			}
			$jsonC = urldecode(json_encode($aryC));
			parent::addParameter("jsonC",$jsonC);

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

		public function saveData(){
			$isIndex = conver::toDbString(trim($_POST["IsIndex"]));
			$visible = conver::toDbString(trim($_POST["Visible"]));
			$iconImage = $_POST["IconImage"];
			$productName = $_POST["ProductName"];
			$orderNO = $_POST["OrderNO"];
			if(count($iconImage) == count($productName) && count($iconImage) == count($orderNO)){
				$this->dal->CategoryID = $this->cid;
				$this->dal->ViewCount = "0";
				$this->dal->IsIndex = $isIndex;
				$this->dal->Visible = $visible;
				$this->dal->CreatedUserID = parent::getCurrentUserID();
				$this->dal->ModifiedUserID = parent::getCurrentUserID();
				for($i=0;$i<count($iconImage);$i++){
					$this->dal->ProductName = conver::toDbString(trim($productName[$i]));
					$this->dal->IconImage = conver::toDbString(trim($iconImage[$i]));
					$this->dal->OrderNO = conver::toDbString(trim($orderNO[$i]));
					$this->dal->insertRecord();
				}
			}
			parent::redirect($this->pUrl);
		}
	}

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