<?php
	require_once "pageBase.php";
	require_once "PHPExcel.php";
	require_once "../bin/system/guid.php";
	require_once "../bin/web/repeater.php";
	require_once "../dal/categoryDAL.php";
	require_once "../dal/productDAL.php";
	require_once "../function/function.php";

	class _productEdit extends pageBase {
		private string $id;
		private string $pUrl;
		private $dal;
		private $dalC;
		
		public function load() {
			$this->dal = new productDAL();
			$this->dalC = new categoryDAL();
			$this->id = parent::getInput("id","0");
			$this->pUrl = urldecode(parent::getInput("pUrl","productList.php"));
			
			$this->limitID = "29";
			if (!parent::chkUserLimit()) {
				$this->alertMsg = "您沒有使用此頁面的權限!如有疑問請洽主管理者!";
				$this->locationHref = "index.php";
			} else {
				parent::isPostBack() ? $this->saveData() : $this->loadData();
			}
			parent::loadTemplateFile(dirname(__FILE__) . "/templates/productExcel.html");
			parent::load();
		}

		public function loadData() {
			parent::loadData();
		}

		public function saveData() {
			$userID = parent::getCurrentUserID();
			$ip = parent::getIP();
			$saveDir = "zipflash/" . time();
			$filePath = parent::getPost("UpFileZip");

			$fullFilePath = dirname(dirname(__FILE__)) . $filePath;
			
			if (!file_exists($fullFilePath)) {
				$this->alertMsg = "找不到匯入檔案「{$fullFilePath}」!";
				$this->goBack = "Y";
				return false;
			}

			$zip = new ZipArchive();
			$res = $zip->open("..{$filePath}");
			if ($res !== true) {
				$this->alertMsg = "「..{$filePath}」解壓縮失敗!錯誤代碼：{$res}";
				$this->goBack = "Y";
				return false;
			}
			$zip->extractTo($saveDir);
			$zip->close();

			$listAry = glob("{$saveDir}/*");
			$xlsxAry = [];
			$imageAry = [];
			foreach ($listAry as $itemPath) {
				if (is_file($itemPath)) {
					$itemName = basename($itemPath);
					$extName = strtolower(pathinfo($itemName, PATHINFO_EXTENSION));
					
					if ($extName == "xlsx") {
						$xlsxAry[] = $itemPath;
					} elseif (in_array($extName, ["jpg", "jpeg", "png", "gif", "bmp"])) {
						$imageAry[] = $itemPath;
					}
				}
			}
			if (count($xlsxAry) === 0) {
				$this->alertMsg = "壓縮檔中沒有xlsx檔!";
				$this->goBack = "Y";
				return false;
			}
			$num1 = 0;
			$num2 = 0;

			$imagesDir = dirname(dirname(__FILE__)) . "/userfiles/images";
			$zipDir = "{$imagesDir}/zip";
			$dateDir = "{$zipDir}/" . date("Y-m-d");
			foreach ([$imagesDir, $zipDir, $dateDir] as $dir) {
				if (!file_exists($dir)) mkdir($dir, 0755, true);
			}
			
			foreach ($xlsxAry as $xlsx) {
				try {
					$objPHPExcel = PHPExcel_IOFactory::load($xlsx);
				} catch (\Exception $e) {
					die('Error loading file "' . pathinfo($xlsx, PATHINFO_BASENAME) . '": ' . $e->getMessage());
				}
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
				foreach ($sheetData as $key => $rows) {
					$flag = 0;
					if ($key > 1) {
						$productName = parent::specialtocode($rows["A"] ?? "");
						$categoryName = parent::specialtocode($rows["B"] ?? "");
						$productNO = parent::specialtocode($rows["C"] ?? "");
						$oldPrice = parent::specialtocode($rows["D"] ?? "0");
						$price = parent::specialtocode($rows["E"] ?? "0");
						$iconImage = parent::specialtocode($rows["F"] ?? "");
						$txtPI = parent::specialtocode($rows["G"] ?? "");
						$aryPI = [];
						if (!empty($txtPI)) $aryPI = array_map('trim', explode(PHP_EOL, $txtPI));
						$bannerImage = parent::specialtocode($rows["H"] ?? "");
						$bannerTitle = parent::specialtocode($rows["I"] ?? "");
						$bannerLink = parent::specialtocode($rows["J"] ?? "");
						$bannerColor = parent::specialtocode($rows["K"] ?? "");
						$bannerDesc = parent::specialtocode($rows["L"] ?? "");
						$introduction = parent::specialtocode($rows["M"] ?? "");
						$specification = parent::specialtocode($rows["N"] ?? "", 2);
						$title1 = parent::specialtocode($rows["O"] ?? "");
						$description1 = parent::specialtocode($rows["P"] ?? "", 2);
						$title2 = parent::specialtocode($rows["Q"] ?? "");
						$description2 = parent::specialtocode($rows["R"] ?? "", 2);
						$title3 = parent::specialtocode($rows["S"] ?? "");
						$description3 = parent::specialtocode($rows["T"] ?? "", 2);
						$ogTitle = parent::specialtocode($rows["U"] ?? "");
						$ogDescription = parent::specialtocode($rows["V"] ?? "");
						$ogImage = parent::specialtocode($rows["W"] ?? "");
						$isIndex = (strtolower($rows["X"] ?? "") !== "否") ? "1" : "0";
						$visible = (strtolower($rows["Y"] ?? "") !== "否") ? "1" : "0";
						$orderNO = parent::specialtocode($rows["Z"] ?? "0");
						$webTitle = parent::specialtocode($rows["AA"] ?? "");
						$webKeyword = parent::specialtocode($rows["AB"] ?? "");
						$webDescription = parent::specialtocode($rows["AC"] ?? "");
						
						if($productName == "") break;
						if (empty($categoryName)) {
							$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的分類名稱未輸入!\\n";
							$flag = 1;
						} else {
							$intoAry = [parent::addArray(":categoryName", $categoryName, "str", 50)];
							$dataC = $this->dalC->executeRecordset($intoAry, "a.`CategoryName`=:categoryName");
							if (count($dataC) === 0) {
								$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的分類名稱「" . $categoryName . "」找不到!\\n";
								$flag = 1;
							} else if (count($dataC) > 1) {
								$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的分類名稱「" . $categoryName . "」在系統中有兩個以上分類同名，無法確認分類!新增失敗!\\n";
								$flag = 1;
							} else {
								$into2Ary = [parent::addArray(":parentID", $dataC[0]["CategoryID"], "int")];
								$countC = $this->dalC->countRecordset($into2Ary, "a.`ParentID`=:parentID");
								if ($countC > 0) {
									$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的分類名稱「" . $categoryName . "」並非底層分類，不能選擇此分類!新增失敗!\\n";
									$flag = 1;
								}else{
									$categoryID = $dataC[0]["CategoryID"];
								}
							}
						}
						if (!ctype_digit($oldPrice)) {
							$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的產品原價「" . $oldPrice . "」不是數字!新增失敗!\\n";
							$flag = 1;
						}
						if (!ctype_digit($price)) {
							$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的產品售價「" . $price . "」不是數字!新增失敗!\\n";
							$flag = 1;
						}
						$iconImage = $this->validateAndCopyImage($xlsx, $key, "產品縮圖", $iconImage, $this->alertMsg, $flag);
						foreach ($aryPI as $i => $pi) {
							$aryPI[$i] = $this->validateAndCopyImage($xlsx, $key, $pi, "產品大圖第" . ($i + 1) . "張", $this->alertMsg, $flag);
						}
						$bannerImage = $this->validateAndCopyImage($xlsx, $key, "產品Banner圖", $bannerImage, $this->alertMsg, $flag);
						if (empty($title1)) {
							$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的產品資訊一標題未輸入!\\n";
							$flag = 1;
						}
						$ogImage = $this->validateAndCopyImage($xlsx, $key, "社群分享縮圖", $ogImage, $this->alertMsg, $flag);
						if (!ctype_digit($orderNO)) {
							$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的排序「" . $orderNO . "」不是數字!新增失敗!\\n";
							$flag = 1;
						}
						if ($flag === 0) {
							$this->dal->CategoryID = $categoryID;
							$this->dal->ProductName = $productName;
							$this->dal->PathName = guid::newGuid()->toString();
							$twPathName = parent::generateTwPathName($productName);
							$twPathName2 = $twPathName;
							$num = 0;
							while ($this->dal->checkTwPathNameExists($twPathName2) && $this->dal->TwPathName != $twPathName2) {
								$num++;
								$twPathName2 = $twPathName . "_" . $num;
							}
							$this->dal->TwPathName = $twPathName2;
							$this->dal->ProductNO = $productNO;
							$this->dal->OldPrice = is_numeric($oldPrice) ? $oldPrice : 0;
							$this->dal->Price = is_numeric($price) ? $price : 0;
							$this->dal->IconImage = validateAndCopyImage($xlsx, $key, $iconImage, $this->alertMsg, $flag);
							$this->dal->BannerImage = validateAndCopyImage($xlsx, $key, $bannerImage, $this->alertMsg, $flag);
							$this->dal->BannerTitle = $bannerTitle;
							$this->dal->BannerLink = $bannerLink;
							$this->dal->BannerColor = $bannerColor;
							$this->dal->BannerDesc = $bannerDesc;
							$this->dal->Introduction = $introduction;
							$this->dal->Specification = $specification;
							$this->dal->Title1 = $title1;
							$this->dal->Title2 = $title2;
							$this->dal->Title3 = $title3;
							$this->dal->Description1 = $description1;
							$this->dal->Description2 = $description2;
							$this->dal->Description3 = $description3;
							$this->dal->OGTitle = $ogTitle;
							$this->dal->OGDescription = $ogDescription;
							$this->dal->OGImage = $ogImage;
							$this->dal->ViewCount = 0;
							$this->dal->IsIndex = ($isIndex != "否") ? 1 : 0;
							$this->dal->Visible = ($visible != "否") ? 1 : 0;
							$this->dal->OrderNO = is_numeric($orderNO) ? $orderNO : 0;
							$this->dal->WebTitle = $webTitle;
							$this->dal->WebKeyword = $webKeyword;
							$this->dal->WebDescription = $webDescription;
							$this->dal->CreatedTime = time();
							$this->dal->CreatedUserID = $userID;
							$this->dal->CreatedIP = $ip;
							$this->dal->ModifiedTime = $this->dal->CreatedTime;
							$this->dal->ModifiedUserID = $userID;
							$this->dal->ModifiedIP = $ip;
							$this->dal->ProductImageArray = [];
							foreach ($aryPI as $v) {
								$this->dal->ProductImageArray[]["Image"] = $v;
							}
							if ($this->dal->insertRecord()) {
								$num1++;
							} else {
								$num2++;
								$this->alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的產品新增失敗!\\n";
							}
						} else {
							$num2++;
						}
					}
				}
			}

			if (!unlink(dirname(dirname(__FILE__)) . $filePath)) $this->alertMsg .= "新增完成後，刪除上傳壓縮檔失敗!\\n";
			rrmdir($saveDir);

			// 計算成功和失敗的產品數量
			$totalProducts = $num1 + $num2;
			$this->alertMsg .= "新增{$totalProducts}個產品，成功{$num1}個，失敗{$num2}個";
			$this->locationHref = "productList.php";
		}

		/* 圖片檢查和複製 */
		public function validateAndCopyImage($xlsx, $key, $imageType, $imagePath, &$alertMsg, &$flag) {
			if (empty($imagePath)) {
				$alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的" . $imageType . "未輸入!\\n";
				$flag = 1;
				return false;
			}
			if (!parent::image_exists($imagePath)) {
				$alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的" . $imageType . "「" . $imagePath . "」找不到!\\n";
				$flag = 1;
				return false;
			}
			if (!filter_var($imagePath, FILTER_VALIDATE_URL)) {
				$aryIEXT = explode(".", $imagePath);
				$ext_name = strtolower(end($aryIEXT));
				if (!in_array($ext_name, ["bmp", "jpg", "jpeg", "png", "gif"])) {
					$alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的" . $imageType . "「" . $imagePath . "」不是合法的圖檔!\\n";
					$flag = 1;
					return false;
				}
		
				$new_name = date("YmdHis") . "_" . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 4);
				$new_name2 = $new_name;
				$file_no = 0;
				while (file_exists("../userfiles/images/zip/" . date("Y-m-d") . "/" . $new_name2 . "." . $ext_name)) {
					$file_no++;
					$new_name2 = $new_name . "_" . $file_no;
				}
				$flagCP = copy($imagePath, "../userfiles/images/zip/" . date("Y-m-d") . "/" . $new_name2 . "." . $ext_name);
				if (!$flagCP) {
					$alertMsg .= "「" . basename($xlsx) . "」第" . $key . "行的" . $imageType . "「" . $imagePath . "」複製失敗!\\n";
					$flag = 1;
					return false;
				} else {
					return "/userfiles/images/zip/" . date("Y-m-d") . "/" . $new_name2 . "." . $ext_name;
				}
			}
		
			return $imagePath;
		}
	}

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