<?php
	require_once "pageBase.php";
	require_once "../bin/web/repeater.php";
	require_once "../dal/floatbuttonDAL.php";
	class _floatbuttonSet extends pageBase {
		private $dal;
		public function load() {
			$this->dal = new floatbuttonDAL();

			$this->limitID = "79";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/floatbuttonSet.html");
			parent::load();
		}
		
		public function loadData(){
			$data = $this->dal->executeRecordset();
			foreach ($data as &$item) {
				if (empty($item["Icon"]) || !parent::image_exists($item["Icon"])) {
					$item["Icon2"] = "/images/no-pic.jpg";
					$item["Icon3"] = "javascript:void(0);";
				} else {
					$item["Icon2"] = $item["Icon"];
					$item["Icon3"] = $item["Icon"];
				}
			}
			$list = new repeater();
			$list->id = "list";
			$list->dataSource = $data;
			parent::addControl($list);

			parent::loadData();
		}

		public function saveData() {
			$types = parent::getPostArray("Type");
			$titles = parent::getPostArray("Title");
			$values = parent::getPostArray("Value");
			$icons = parent::getPostArray("Icon");
			$classes = parent::getPostArray("Class");
			$visibles = parent::getPostArray("Visible");

			$count = count($types);
		
			if ($count === count($titles) && $count === count($values) && $count === count($icons) && $count === count($classes) && $count === count($visibles)) {
				$this->dal->deleteRecord();

				for ($i = 0; $i < $count; $i++) {
					$type = $types[$i];
					$visible = $visibles[$i];
		
					if (preg_match("/^[1-6]$/", $type) && preg_match("/^[0-1]$/", $visible)) {
						$this->dal->ID = $i + 1;
						$this->dal->Type = $type;
						$this->dal->Title = $titles[$i];
						$this->dal->Value = $values[$i];
						$this->dal->Icon = $icons[$i];
						$this->dal->Class = $classes[$i];
						$this->dal->Visible = $visible;
						$this->dal->insertRecord();
					}
				}
				$this->alertMsg = "儲存完畢!";
			} else {
				$this->alertMsg = "資料傳輸異常!請重新整理再試一次!";
			}
			$this->locationHref = "floatbuttonSet.php";
		}
	}

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