<?php
	
	namespace Dashboard\Controllers;
	
	use Dashboard\Core\Controller;
	use Dashboard\Services\CategoryService;
	use PDO;
	
	class VipTableController extends Controller
	{
		public function __construct()
		{
			abort_perm('MANAGE_STORE');
		}
		
		public function index()
		{
			if (moduleIsDisabled('tebex_store')) {
				$VIPs = db()->query("SELECT VT.*, PC.name as categoryName, PC.slug as categorySlug FROM VIPTables VT INNER JOIN ProductCategories PC ON VT.categoryID = PC.id ORDER BY VT.id DESC");
				$VIPs = array_map(function ($VIP) {
					$products = db()->prepare("SELECT P.name FROM VIPs V INNER JOIN Products P ON V.vipID = P.id WHERE V.tableID = ?");
					$products->execute(array($VIP["id"]));
					$VIP["products"] = $products->fetchAll(PDO::FETCH_COLUMN);
					return $VIP;
				}, $VIPs->fetchAll(PDO::FETCH_ASSOC));
			} else {
				$VIPs = db()->query("SELECT VT.*, VT.categoryID as categoryName FROM VIPTables VT ORDER BY VT.id DESC");
				$VIPs = array_map(function ($VIP) {
					$products = db()->prepare("SELECT V.vipID as name FROM VIPs V WHERE V.tableID = ?");
					$products->execute(array($VIP["id"]));
					$VIP["products"] = $products->fetchAll(PDO::FETCH_COLUMN);
					return $VIP;
				}, $VIPs->fetchAll(PDO::FETCH_ASSOC));
			}
			
			return view('vip-tables.index', compact('VIPs'));
		}
		
		public function create()
		{
			return view('vip-tables.create');
		}
		
		public function store()
		{
			validate([
				'categoryID' => 'required',
			]);
			
			if (!isset($_POST["vips"]) || !count(array_filter($_POST["vips"])) || !count(array_filter($_POST["titles"]))) {
				return back()->flash("error", t__('Please select at least one product!'));
			}
			
			$insertVipTable = db()->prepare("INSERT INTO VIPTables (categoryID) VALUES (?)");
			$insertVipTable->execute(array(input("categoryID")));
			$vipTableID = db()->lastInsertId();
			
			if (count(array_filter($_POST["vips"]))) {
				$insertVIP = db()->prepare("INSERT INTO VIPs (vipID, tableID) VALUES (?, ?)");
				foreach ($_POST["vips"] as $vipID) {
					$insertVIP->execute(array($vipID, $vipTableID));
				}
			}
			
			if (count(array_filter($_POST["titles"]))) {
				$priority = 0;
				$vipTitles = [];
				foreach ($_POST["titles"] as $key => $title) {
					$insertVIPTitles = db()->prepare("INSERT INTO VIPTitles (title, tableID, priority) VALUES (?, ?, ?)");
					$insertVIPTitles->execute(array($title, $vipTableID, $priority));
					$titleID = db()->lastInsertId();
					if (isset($_POST["explains"][$key]) && $_POST["explains"][$key] != '') {
						$insertVIPExplain = db()->prepare("INSERT INTO VIPExplain (titleID, name) VALUES (?, ?)");
						$insertVIPExplain->execute(array($titleID, $_POST["explains"][$key]));
					}
					$vipTitles[] = $titleID;
					$priority++;
				}
				
				foreach ($vipTitles as $key => $titleID) {
					foreach ($_POST["vips"] as $vipID) {
						if (isset($_POST["description_{$vipID}"][$key]) && $_POST["description_{$vipID}"][$key] != '') {
							$description = $_POST["description_{$vipID}"][$key];
							$insertVIPDesc = db()->prepare("INSERT INTO VIPDesc (vipID, titleID, description) VALUES (?, ?, ?)");
							$insertVIPDesc->execute(array($vipID, $titleID, $description));
						}
					}
				}
			}
			
			return back()->flash("success", t__('VIP Table has been added successfully!'));
		}
		
		public function edit($id)
		{
			$vips = null;
			
			if (moduleIsDisabled('tebex_store')) {
				$vipTable = db()->prepare("SELECT VT.*, C.slug as categorySlug FROM VIPTables VT INNER JOIN ProductCategories C ON C.id = VT.categoryID WHERE VT.id = ?");
				$vipTable->execute(array($id));
				$vipTable = $vipTable->fetch();
			} else {
				$vipTable = db()->prepare("SELECT VT.*, VT.categoryID as categorySlug FROM VIPTables VT WHERE VT.id = ?");
				$vipTable->execute(array($id));
				$vipTable = $vipTable->fetch();
			}
			
			if (!$vipTable) return view('404');
			
			if (moduleIsDisabled('tebex_store')) {
				$vips = db()->prepare("SELECT V.vipID FROM VIPs V INNER JOIN Products P ON V.vipID = P.id WHERE V.tableID = ? ORDER BY P.priority DESC");
				$vips->execute(array($id));
				$vipTable["vips"] = $vips->fetchAll(PDO::FETCH_COLUMN);
			} else {
				$vips = db()->prepare("SELECT V.vipID FROM VIPs V WHERE V.tableID = ?");
				$vips->execute(array($id));
				$vipTable["vips"] = $vips->fetchAll(PDO::FETCH_COLUMN);
			}
			
			$vipTable["data"] = [];
			
			$vipTitles = db()->prepare("SELECT * FROM VIPTitles WHERE tableID = ?");
			$vipTitles->execute(array($id));
			$vipTitles = $vipTitles->fetchAll();
			foreach ($vipTitles as $vipTitle) {
				$data = [
					'title' => $vipTitle["title"],
					'explain' => '',
					'descriptions' => [],
				];
				$vipExplain = db()->prepare("SELECT * FROM VIPExplain WHERE titleID = ?");
				$vipExplain->execute(array($vipTitle["id"]));
				if ($vipExplain->rowCount() > 0) {
					$vipExplain = $vipExplain->fetch();
					$data["explain"] = $vipExplain["name"];
				}
				
				$vipDescQuery = db()->prepare("SELECT * FROM VIPDesc WHERE titleID = ? AND vipID = ?");
				foreach ($vipTable["vips"] as $vipID) {
					$vipDescQuery->execute(array($vipTitle["id"], $vipID));
					if ($vipDescQuery->rowCount() > 0) {
						$vipDesc = $vipDescQuery->fetch();
						$data["descriptions"][$vipID] = $vipDesc["description"];
					} else {
						$data["descriptions"][$vipID] = "";
					}
				}
				
				$vipTable["data"][] = $data;
			}
			
			return view('vip-tables.edit', compact('vipTable'));
		}
		
		public function update($id)
		{
			$vipTables = db()->prepare("SELECT * FROM VIPTables WHERE id = ?");
			$vipTables->execute(array($id));
			$readVipTables = $vipTables->fetch();
			
			validate([
				'categoryID' => 'required',
			]);
			
			if (!count(array_filter($_POST["vips"])) || !count(array_filter($_POST["titles"]))) {
				return back()->flash("error", t__('Please select at least one product!'));
			}
			
			if (count(array_filter($_POST["vips"]))) {
				$deleteVIPs = db()->prepare("DELETE FROM VIPs WHERE tableID = ?");
				$deleteVIPs->execute(array($readVipTables["id"]));
				
				$insertVIP = db()->prepare("INSERT INTO VIPs (vipID, tableID) VALUES (?, ?)");
				foreach ($_POST["vips"] as $vipID) {
					$insertVIP->execute(array($vipID, $readVipTables["id"]));
				}
			}
			
			if (count(array_filter($_POST["titles"]))) {
				$priority = 0;
				$vipTitles = [];
				
				$vipTitlesQuery = db()->prepare("SELECT * FROM VIPTitles WHERE tableID = ?");
				$vipTitlesQuery->execute(array($readVipTables["id"]));
				$vipTitlesQuery = $vipTitlesQuery->fetchAll();
				foreach ($vipTitlesQuery as $vipTitle) {
					$deleteVIPDesc = db()->prepare("DELETE FROM VIPDesc WHERE titleID = ?");
					$deleteVIPDesc->execute(array($vipTitle["id"]));
					
					$deleteVIPExplain = db()->prepare("DELETE FROM VIPExplain WHERE titleID = ?");
					$deleteVIPExplain->execute(array($vipTitle["id"]));
				}
				
				$deleteVIPTitles = db()->prepare("DELETE FROM VIPTitles WHERE tableID = ?");
				$deleteVIPTitles->execute(array($readVipTables["id"]));
				
				foreach ($_POST["titles"] as $key => $title) {
					$insertVIPTitles = db()->prepare("INSERT INTO VIPTitles (title, tableID, priority) VALUES (?, ?, ?)");
					$insertVIPTitles->execute(array($title, $readVipTables["id"], $priority));
					$titleID = db()->lastInsertId();
					if (isset($_POST["explains"][$key]) && $_POST["explains"][$key] != '') {
						$insertVIPExplain = db()->prepare("INSERT INTO VIPExplain (titleID, name) VALUES (?, ?)");
						$insertVIPExplain->execute(array($titleID, $_POST["explains"][$key]));
					}
					$vipTitles[] = $titleID;
					$priority++;
				}
				
				foreach ($vipTitles as $key => $titleID) {
					foreach ($_POST["vips"] as $vipID) {
						if (isset($_POST["description_{$vipID}"][$key]) && $_POST["description_{$vipID}"][$key] != '') {
							$description = $_POST["description_{$vipID}"][$key];
							$insertVIPDesc = db()->prepare("INSERT INTO VIPDesc (vipID, titleID, description) VALUES (?, ?, ?)");
							$insertVIPDesc->execute(array($vipID, $titleID, $description));
						}
					}
				}
			}
			
			return back()->flash("success", t__('Changes has been saved successfully!'));
		}
		
		public function destroy($id)
		{
			$deleteVIPTables = db()->prepare("DELETE FROM VIPTables WHERE id = ?");
			$deleteVIPTables->execute(array($id));
			return back();
		}
	}