<?php
	require_once "../dal/productDAL.php";
	require_once "../dal/registryDAL.php";
	require_once "../pageBase.php";

	class _cart extends pageBase {
		private $dal;
		private $order;
		private array $aryJ;
		private string $regex;

		public function __construct() {
			$this->dal = new productDAL();
			$this->order = new order();
			$this->regex = "/^\d+$/";
			$this->aryJ = ["err" => "0", "msg" => ""];
		}

		public function load(): void {
			$this->aryJ["msg"] = "";

			$action = parent::getPost("do");
			switch ($action) {
				case "add":
					$this->addItem();
					break;
				case "chg":
					$this->chgQuantity();
					break;
				case "sum":
					$this->sumPrice();
					break;
				case "del":
					$this->deleteItem();
					break;
				case "cln":
					setcookie("cart", "", ["expires" => 1, "path" => "/"]);
					$this->aryJ["msg"] = "購物車已清空!";
					break;
				default:
					$this->handleError("操作異常！請重新整理頁面再試一次！");
			}
		
			$this->aryJ["msg"] = urlencode($this->aryJ["msg"]);
			file_put_contents("cart.txt", urldecode(json_encode($this->aryJ)) . PHP_EOL, FILE_APPEND);
			echo urldecode(json_encode($this->aryJ));
		}

		private function addItem(): void {
			$id = parent::getPost("id");
			$q = parent::getPost("q");
			
			if (!preg_match($this->regex, $id) || $id == "0") {
				$this->handleError("找不到指定的產品!請重新整理頁面再試一次!");
				return;
			}
			if (!preg_match($this->regex, $q) || $q == "0") {
				$this->handleError("購買數量異常!請重新整理頁面再試一次!");
				return;
			}
			
			$this->dal->ProductID = $id;
			$this->dal->loadRecord();
			if (
				($this->dal->Visible=== 1 || $this->dal->Disable == "0") &&
				($this->dal->CategoryVisible == 1 || $this->dal->CategoryDisable == "0") &&
				($this->dal->ParentID == "0" || $this->dal->ParentVisible=== 1 || $this->dal->ParentDisable == "0") &&
				($this->dal->ParentID == "0" || $this->dal->GrandID == "0" || $this->dal->GrandVisible=== 1 || $this->dal->GrandDisable == "0")
			) {
				if (isset($_COOKIE["cart"])) {
					/* 購物車有產品 */
					$cart = $_COOKIE["cart"];
					if (!preg_match("/^[\d,;]+$/", $cart)) {
						setcookie("cart", "", ["expires" => 0, "path" => "/"]);
						$this->handleError("購物車記錄異常已被清空!請重新購買!");
						return;
					}
					
					$aryC = $this->order->cart_decode($cart);
					// 檢查產品是否重複加入購物車-禁止重複加入
					$flag = false;
					foreach ($aryC as $rows) {
						if ($rows["id"] == $id) {
							$flag = true;
							break;
						}
					}
					
					if (!$flag) {
						$aryC[] = ["id" => $id, "q" => $q];
						$newCart = $this->order->cart_encode($aryC);
						setcookie("cart", $newCart, ["expires" => 0, "path" => "/"]);
						$this->aryJ["msg"] = "產品加入購物車成功!";
					} else {
						$this->handleError("購物車中已有相同的產品!");
					}
				} else {
					/* 購物車空車 */
					$aryC = [["id" => $id, "q" => $q]];
					$newCart = $this->order->cart_encode($aryC);
					setcookie("cart", $newCart, ["expires" => 0, "path" => "/"]);
					$this->aryJ["msg"] = "產品加入購物車成功!";
				}
			} else {
				$this->handleError("找不到指定的產品!請重新整理頁面再試一次!!");
			}
		}
		
		private function chgQuantity(): void {
			$id = parent::getPost("id");
			$q = parent::getPost("q");
			
			if (!preg_match($this->regex, $id) || $id == "0") {
				$this->handleError("找不到指定的產品!請重新整理頁面再試一次!");
				return;
			}
			if (!preg_match($this->regex, $q) || $q == "0") {
				$this->handleError("購買數量異常!請重新整理頁面再試一次!");
				return;
			}
    
			$q = (int)$q;
			$this->aryJ["amount"] = 0;
			
			if (isset($_COOKIE["cart"])) {
				$cart = $_COOKIE["cart"];
				if (!preg_match("/^[\d,;]+$/", $cart)) {
					setcookie("cart", "", ["expires" => 0, "path" => "/"]);
					$this->handleError("購物車記錄異常已被清空!請重新購買!");
					return;
				}
        
				$aryC = $this->order->cart_decode($cart);
				$aryNC = [];
				$flag1 = 0;
				$flag2 = 0;
        
				foreach ($aryC as $i => $row) {
					$this->dal->ProductID = $row["id"];
					$this->dal->loadRecord();
					if (
						($this->dal->Visible=== 1 || $this->dal->Disable == "0") &&
						($this->dal->CategoryVisible=== 1 || $this->dal->CategoryDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->ParentVisible=== 1 || $this->dal->ParentDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->GrandID == "0" || $this->dal->GrandVisible=== 1 || $this->dal->GrandDisable == "0")
					) {
						if ($row["id"] == $id) {
							$flag2++;
							$aryC[$i]["q"] = $q;
							$this->aryJ["amount"] = (int)$this->dal->Price * $q;
						}
						$aryNC[] = ["id" => $row["id"], "q" => $row["q"]];
					} else {
						$flag1++;
						$this->aryJ["err"] = "1";
					}
				}
        
				$newCart = $this->order->cart_encode($aryNC);
				setcookie("cart", $newCart, ["expires" => 0, "path" => "/"]);
				if ($flag1 > 0) $this->aryJ["msg"] .= "購物車中有被下架的產品，已經自動移除，請重新整理頁面確認!\\n";
				if ($flag2 == 0) {
					$this->handleError("找不到指定的產品!");
				} else {
					$this->aryJ["msg"] .= "修改產品數量成功!";
				}
			} else {
				$this->handleError("購物車中沒有產品!");
			}
		}

		private function sumPrice(): void {
			$transPrice = $this->registry->transPrice;
			if ($transPrice == "" || !preg_match($this->regex, $transPrice)) $transPrice = 0;
			$transPrice = (int)$transPrice;
			$transFreePrice = $this->registry->transFreePrice;
			if ($transFreePrice == "" || !preg_match($this->regex, $transFreePrice)) $transFreePrice = 0;
			$transFreePrice = (int)$transFreePrice;
			
			$total = 0;

			if (isset($_COOKIE["cart"])) {
				$cart = $_COOKIE["cart"];
        
				if (!preg_match("/^[\d,;]+$/", $cart)) {
					setcookie("cart", "", ["expires" => 0, "path" => "/"]);
					$this->handleError("購物車記錄異常已被清空!請重新購買!");
					return;
				}
				
				$aryC = $this->order->cart_decode($cart);
				$aryNC = [];
				$flag = 0;
        
				foreach ($aryC as $rows) {
					$this->dal->ProductID = $rows["id"];
					$this->dal->loadRecord();
					if (
						($this->dal->Visible=== 1 || $this->dal->Disable == "0") &&
						($this->dal->CategoryVisible=== 1 || $this->dal->CategoryDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->ParentVisible=== 1 || $this->dal->ParentDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->GrandID == "0" || $this->dal->GrandVisible=== 1 || $this->dal->GrandDisable == "0")
					) {
						$total += (int)$this->dal->Price * (int)$rows["q"];
						$aryNC[] = ["id" => $rows["id"], "q" => $rows["q"]];
					} else {
						$flag++;
						$this->handleError("購物車中有被下架的產品，已經自動移除，請重新整理頁面確認!");
					}
				}
        
				$newCart = $this->order->cart_encode($aryNC);
				setcookie("cart", $newCart, ["expires" => 0, "path" => "/"]);
				
				$this->aryJ["pprice"] = $total;
				$this->aryJ["tprice"] = ($total < $transFreePrice || $transFreePrice == 0) ? $transPrice : 0;
				$this->aryJ["oprice"] = $this->aryJ["pprice"] + $this->aryJ["tprice"];
			} else {
				$this->handleError("購物車中沒有產品!");
			}
		}

		private function deleteItem(): void {
			$id = parent::getPost("id");
			
			if (!preg_match($this->regex, $id) || $id == "0") {
				$this->handleError("找不到指定的產品!請重新整理頁面再試一次!");
				return;
			}

			if (isset($_COOKIE["cart"])) {
				$cart = $_COOKIE["cart"];
        
				if (!preg_match("/^[\d,;]+$/", $cart)) {
					setcookie("cart", "", ["expires" => 0, "path" => "/"]);
					$this->handleError("購物車記錄異常已被清空!請重新購買!");
					return;
				}
				
				$aryC = $this->order->cart_decode($cart);
				$aryNC = [];
				$flag = 0;
        
				foreach ($aryC as $rows) {
					$this->dal->ProductID = $rows["id"];
					$this->dal->loadRecord();
					if (
						($this->dal->Visible=== 1 || $this->dal->Disable == "0") &&
						($this->dal->CategoryVisible=== 1 || $this->dal->CategoryDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->ParentVisible=== 1 || $this->dal->ParentDisable == "0") &&
						($this->dal->ParentID == "0" || $this->dal->GrandID == "0" || $this->dal->GrandVisible=== 1 || $this->dal->GrandDisable == "0")
					) {
						if ($rows["id"] !== $id) {
							$aryNC[] = ["id" => $rows["id"], "q" => $rows["q"]];
						} else {
							$flag++;
						}
					} else {
						$this->handleError("購物車中有被下架的產品，已經自動移除，請重新整理頁面確認!\\n");
					}
				}
        
				$newCart = $this->order->cart_encode($aryNC);
				setcookie("cart", $newCart, ["expires" => 0, "path" => "/"]);
				
				if ($flag == 0) {
					$this->handleError("購物車中找不到指定刪除的產品!");
				} else {
					$this->aryJ["msg"] .= "指定產品已從購物車中移除!";
				}
			} else {
				$this->handleError("購物車中沒有產品!");
			}
		}

		private function handleError(string $errorMessage): void {
			$this->aryJ["err"] = "1";
			$this->aryJ["msg"] = $errorMessage;
		}
	}
	$page = new _cart();
	$page->load();
?>