<?php
	require_once dirname(dirname(__FILE__))."/bin/web/repeater.php";

	class _indexProduct extends webPartBase {
		public $product;
		public function load() : void {
			$this->product = new product();
			$this->loadData();
			if ($this->registry->indexPShow == "1") parent::loadTemplateFile(dirname(__FILE__)."/../templates/webParts/".$this->registry->webTemplates."/indexProduct.html");
			parent::load();
		}
		
		public function loadData() : void {
			$dalP = new productDAL();

			// 首頁商品設定
			$arrPS = [];
			if ($this->registry->indexPBImg != "" && parent::image_exists($this->registry->indexPBImg)) $arrPS[] = "background-image:url({$this->registry->indexPBImg});";
			if ($this->registry->indexPBColor != "") $arrPS[] = "background-color: {$this->registry->indexPBColor};";
			$productStyle = (count($arrPS) > 0) ? "style=\"" . implode(" ", $arrPS) . "\"" : "";
			parent::addParameter("productStyle", $productStyle);
			parent::addParameter("indexPTitle", $this->registry->indexPTitle);
			parent::addParameter("indexPMLink", $this->registry->indexPMLink);
			parent::addParameter("indexPMLinkTitle", $this->registry->indexPMLinkTitle);
			
			// 條件式
			$filter = "a.`IsIndex`=1 AND a.`Visible`=1 AND a.`Disable`=0 AND b.`IsIndex`=1 AND b.`Visible`=1 AND b.`Disable`=0 AND (b.`ParentID`=0 OR (c.`IsIndex`=1 AND c.`Visible`=1 AND c.`Disable`=0)) AND (b.`ParentID`=0 OR c.`ParentID`=0 OR (d.`IsIndex`=1 AND d.`Visible`=1 AND d.`Disable`=0))";
			
			// 取得商品陣列
			$dataP = $dalP->executeRecordset(
				intoAry: [],
				filter: $filter,
				order: "RAND()",
				start: 0,
				length: ($this->registry->indexPNO ?? 0)
			);
			$dataP = $this->formatProduct($dataP);
			$listP = new repeater();
			$listP->id = "listP";
			$listP->dataSource = $dataP;
			parent::addControl($listP);
			
			$dataP2 = $dalP->executeRecordset(
				intoAry: [],
				filter: $filter,
				order: "RAND()",
				start: 0,
				length: ($this->registry->indexPNO ?? 0) * 2
			);
			$dataP2 = $this->formatProduct($dataP2);
			$listP2 = new repeater();
			$listP2->id = "listP2";
			$listP2->dataSource = $dataP2;
			parent::addControl($listP2);
		}
		private function formatProduct(array $data = []): array {
			foreach ($data as &$item) {
				if (empty($item["IconImage"]) || !parent::image_exists($item["IconImage"])) $item["IconImage"] = $this->NoPicImage;
				
				if ($this->registry->ShowPrice == "1") {
					if ($item["Price"] == "0" || $item["Price"] == "") $item["priceStyle"] = " style='display:none;'";
					if ($item["OldPrice"] == "0" || $item["OldPrice"] == "") $item["oldPriceStyle"] = " style='display:none;'";
				} else {
					$item["priceStyle"] = " style='display:none;'";
					$item["oldPriceStyle"] = " style='display:none;'";
					$item["sellStyle"] = " style='display:none;'";
				}

				$item["link"] = $this->product->linkProductDetail($item["ProductID"]);
				$item["linkC"] = $this->product->linkProductList($item["CategoryID"]);
			}
			return $data;
		}
	}
?>